From 65842a3192123049c21b12f5db744798ab56d1a9 Mon Sep 17 00:00:00 2001 From: Mathieu Bodjikian Date: Thu, 26 Feb 2026 18:01:41 +0100 Subject: [PATCH] wip: implement notification backends --- charts/plik/templates/configmap.yaml | 14 + charts/plik/templates/secret.yaml | 3 + charts/plik/values.yaml | 22 + go.mod | 12 +- go.sum | 39 +- server/common/config.go | 18 + server/common/feature_flags.go | 14 + server/common/file.go | 3 +- server/common/upload.go | 42 + server/context/context.go | 19 + server/context/upload.go | 25 + server/handlers/add_file.go | 36 + server/handlers/get_file.go | 43 + server/handlers/notification_helpers.go | 46 + server/metadata/file.go | 24 + server/metadata/migrations.go | 23 + server/metadata/migrations_test.go | 4 + server/notification/log/log.go | 34 + server/notification/log/log_test.go | 42 + server/notification/notification.go | 20 + server/notification/service.go | 309 + server/notification/service_test.go | 139 + server/notification/smtp/smtp.go | 206 + .../templates/all_downloaded.html | 134 + .../notification/templates/upload_ready.html | 112 + server/notification/testing/testing.go | 65 + server/notification/testing/testing_test.go | 61 + server/plikd.cfg | 46 + server/server/server.go | 157 +- .../atc0005/go-teams-notify/v2/.gitignore | 30 + .../atc0005/go-teams-notify/v2/.golangci.yml | 82 + .../go-teams-notify/v2/.markdownlint.yml | 22 + .../atc0005/go-teams-notify/v2/CHANGELOG.md | 599 ++ .../atc0005/go-teams-notify/v2/LICENSE | 22 + .../atc0005/go-teams-notify/v2/Makefile | 116 + .../atc0005/go-teams-notify/v2/README.md | 525 + .../v2/adaptivecard/adaptivecard.go | 3428 +++++++ .../go-teams-notify/v2/adaptivecard/doc.go | 31 + .../go-teams-notify/v2/adaptivecard/format.go | 73 + .../v2/adaptivecard/getters.go | 340 + .../v2/adaptivecard/nullstring.go | 63 + .../atc0005/go-teams-notify/v2/doc.go | 39 + .../atc0005/go-teams-notify/v2/format.go | 253 + .../v2/internal/validator/doc.go | 18 + .../v2/internal/validator/validator.go | 495 + .../atc0005/go-teams-notify/v2/messagecard.go | 858 ++ .../atc0005/go-teams-notify/v2/send.go | 665 ++ .../atc0005/go-teams-notify/v2/textutils.go | 29 + .../github.com/bwmarrin/discordgo/.gitignore | 5 + .../bwmarrin/discordgo/.golangci.yml | 19 + .../github.com/bwmarrin/discordgo/.travis.yml | 19 + .../bwmarrin/discordgo/CONTRIBUTING.md | 87 + vendor/github.com/bwmarrin/discordgo/LICENSE | 28 + .../github.com/bwmarrin/discordgo/README.md | 103 + .../bwmarrin/discordgo/components.go | 604 ++ .../github.com/bwmarrin/discordgo/discord.go | 64 + .../bwmarrin/discordgo/endpoints.go | 264 + vendor/github.com/bwmarrin/discordgo/event.go | 247 + .../bwmarrin/discordgo/eventhandlers.go | 1750 ++++ .../github.com/bwmarrin/discordgo/events.go | 487 + .../bwmarrin/discordgo/interactions.go | 662 ++ .../github.com/bwmarrin/discordgo/locales.go | 85 + .../github.com/bwmarrin/discordgo/logging.go | 103 + .../github.com/bwmarrin/discordgo/message.go | 638 ++ .../github.com/bwmarrin/discordgo/mkdocs.yml | 17 + .../github.com/bwmarrin/discordgo/oauth2.go | 154 + .../bwmarrin/discordgo/ratelimit.go | 197 + .../github.com/bwmarrin/discordgo/restapi.go | 3707 +++++++ vendor/github.com/bwmarrin/discordgo/state.go | 1310 +++ .../github.com/bwmarrin/discordgo/structs.go | 3074 ++++++ vendor/github.com/bwmarrin/discordgo/user.go | 162 + vendor/github.com/bwmarrin/discordgo/util.go | 125 + vendor/github.com/bwmarrin/discordgo/voice.go | 950 ++ .../github.com/bwmarrin/discordgo/webhook.go | 55 + vendor/github.com/bwmarrin/discordgo/wsapi.go | 989 ++ .../telegram-bot-api/.gitignore | 3 + .../telegram-bot-api/.travis.yml | 6 + .../telegram-bot-api/LICENSE.txt | 21 + .../telegram-bot-api/README.md | 121 + .../telegram-bot-api/bot.go | 967 ++ .../telegram-bot-api/configs.go | 1264 +++ .../telegram-bot-api/helpers.go | 749 ++ .../telegram-bot-api/log.go | 27 + .../telegram-bot-api/passport.go | 315 + .../telegram-bot-api/types.go | 819 ++ .../github.com/gorilla/websocket/.gitignore | 25 + vendor/github.com/gorilla/websocket/AUTHORS | 9 + vendor/github.com/gorilla/websocket/LICENSE | 22 + vendor/github.com/gorilla/websocket/README.md | 33 + vendor/github.com/gorilla/websocket/client.go | 434 + .../gorilla/websocket/compression.go | 148 + vendor/github.com/gorilla/websocket/conn.go | 1238 +++ vendor/github.com/gorilla/websocket/doc.go | 227 + vendor/github.com/gorilla/websocket/join.go | 42 + vendor/github.com/gorilla/websocket/json.go | 60 + vendor/github.com/gorilla/websocket/mask.go | 55 + .../github.com/gorilla/websocket/mask_safe.go | 16 + .../github.com/gorilla/websocket/prepared.go | 102 + vendor/github.com/gorilla/websocket/proxy.go | 77 + vendor/github.com/gorilla/websocket/server.go | 365 + .../gorilla/websocket/tls_handshake.go | 21 + .../gorilla/websocket/tls_handshake_116.go | 21 + vendor/github.com/gorilla/websocket/util.go | 298 + .../gorilla/websocket/x_net_proxy.go | 473 + vendor/github.com/nikoksr/notify/.codacy.yml | 3 + .../github.com/nikoksr/notify/.editorconfig | 12 + vendor/github.com/nikoksr/notify/.gitignore | 13 + .../github.com/nikoksr/notify/.golangci.yaml | 475 + .../github.com/nikoksr/notify/.mockery.yaml | 13 + .../nikoksr/notify/CODE_OF_CONDUCT.md | 133 + .../github.com/nikoksr/notify/CONTRIBUTING.md | 34 + vendor/github.com/nikoksr/notify/LICENSE | 21 + vendor/github.com/nikoksr/notify/Makefile | 67 + vendor/github.com/nikoksr/notify/README.md | 132 + vendor/github.com/nikoksr/notify/SECURITY.md | 9 + vendor/github.com/nikoksr/notify/notify.go | 98 + .../github.com/nikoksr/notify/renovate.json | 13 + vendor/github.com/nikoksr/notify/send.go | 46 + .../nikoksr/notify/service/discord/README.md | 122 + .../nikoksr/notify/service/discord/discord.go | 156 + .../service/discord/mock_discord_session.go | 109 + .../nikoksr/notify/service/http/README.md | 79 + .../nikoksr/notify/service/http/doc.go | 80 + .../nikoksr/notify/service/http/http.go | 281 + .../service/msteams/mock_teams_client.go | 230 + .../notify/service/msteams/ms_teams.go | 102 + .../notify/service/slack/mock_slack_client.go | 116 + .../nikoksr/notify/service/slack/slack.go | 67 + .../nikoksr/notify/service/slack/usage.md | 62 + .../notify/service/telegram/telegram.go | 87 + vendor/github.com/nikoksr/notify/use.go | 25 + vendor/github.com/nikoksr/notify/version.go | 4 + vendor/github.com/slack-go/slack/.gitignore | 5 + .../github.com/slack-go/slack/.golangci.yml | 35 + .../github.com/slack-go/slack/CONTRIBUTING.md | 40 + vendor/github.com/slack-go/slack/LICENSE | 23 + vendor/github.com/slack-go/slack/Makefile | 36 + vendor/github.com/slack-go/slack/README.md | 111 + vendor/github.com/slack-go/slack/admin.go | 207 + .../slack-go/slack/admin_conversations.go | 85 + vendor/github.com/slack-go/slack/apps.go | 72 + vendor/github.com/slack-go/slack/assistant.go | 157 + .../github.com/slack-go/slack/attachments.go | 98 + vendor/github.com/slack-go/slack/audit.go | 152 + vendor/github.com/slack-go/slack/auth.go | 82 + vendor/github.com/slack-go/slack/block.go | 85 + .../github.com/slack-go/slack/block_action.go | 31 + .../github.com/slack-go/slack/block_call.go | 28 + .../slack-go/slack/block_context.go | 37 + .../github.com/slack-go/slack/block_conv.go | 456 + .../slack-go/slack/block_divider.go | 26 + .../slack-go/slack/block_element.go | 813 ++ .../github.com/slack-go/slack/block_file.go | 31 + .../github.com/slack-go/slack/block_header.go | 43 + .../github.com/slack-go/slack/block_image.go | 55 + .../github.com/slack-go/slack/block_input.go | 47 + .../slack-go/slack/block_markdown.go | 34 + .../github.com/slack-go/slack/block_object.go | 274 + .../slack-go/slack/block_rich_text.go | 550 + .../slack-go/slack/block_section.go | 57 + .../slack-go/slack/block_unknown.go | 18 + .../github.com/slack-go/slack/block_video.go | 70 + vendor/github.com/slack-go/slack/bookmarks.go | 169 + vendor/github.com/slack-go/slack/bots.go | 69 + vendor/github.com/slack-go/slack/calls.go | 216 + vendor/github.com/slack-go/slack/canvas.go | 264 + vendor/github.com/slack-go/slack/channels.go | 37 + vendor/github.com/slack-go/slack/chat.go | 926 ++ vendor/github.com/slack-go/slack/comment.go | 10 + .../github.com/slack-go/slack/conversation.go | 914 ++ vendor/github.com/slack-go/slack/dialog.go | 120 + .../slack-go/slack/dialog_select.go | 115 + .../github.com/slack-go/slack/dialog_text.go | 59 + vendor/github.com/slack-go/slack/dnd.go | 160 + vendor/github.com/slack-go/slack/emoji.go | 37 + vendor/github.com/slack-go/slack/errors.go | 21 + vendor/github.com/slack-go/slack/files.go | 671 ++ .../slack-go/slack/function_execute.go | 93 + vendor/github.com/slack-go/slack/groups.go | 7 + vendor/github.com/slack-go/slack/history.go | 37 + vendor/github.com/slack-go/slack/im.go | 21 + vendor/github.com/slack-go/slack/info.go | 479 + .../github.com/slack-go/slack/interactions.go | 250 + .../slack/internal/backoff/backoff.go | 62 + .../slack/internal/errorsx/errorsx.go | 17 + .../slack-go/slack/internal/timex/timex.go | 18 + vendor/github.com/slack-go/slack/item.go | 75 + vendor/github.com/slack-go/slack/logger.go | 60 + vendor/github.com/slack-go/slack/logo.png | Bin 0 -> 52440 bytes vendor/github.com/slack-go/slack/manifests.go | 297 + vendor/github.com/slack-go/slack/messageID.go | 30 + vendor/github.com/slack-go/slack/messages.go | 264 + vendor/github.com/slack-go/slack/metadata.go | 7 + vendor/github.com/slack-go/slack/migration.go | 40 + vendor/github.com/slack-go/slack/misc.go | 445 + vendor/github.com/slack-go/slack/oauth.go | 200 + .../github.com/slack-go/slack/pagination.go | 20 + vendor/github.com/slack-go/slack/pins.go | 100 + vendor/github.com/slack-go/slack/reactions.go | 282 + vendor/github.com/slack-go/slack/reminders.go | 118 + .../github.com/slack-go/slack/remotefiles.go | 309 + vendor/github.com/slack-go/slack/rtm.go | 137 + vendor/github.com/slack-go/slack/search.go | 160 + vendor/github.com/slack-go/slack/security.go | 108 + vendor/github.com/slack-go/slack/slack.go | 174 + .../slack-go/slack/slackutilsx/slackutilsx.go | 64 + vendor/github.com/slack-go/slack/slash.go | 91 + .../github.com/slack-go/slack/socket_mode.go | 43 + vendor/github.com/slack-go/slack/stars.go | 269 + .../slack-go/slack/status_code_error.go | 28 + vendor/github.com/slack-go/slack/team.go | 250 + vendor/github.com/slack-go/slack/tokens.go | 52 + .../github.com/slack-go/slack/usergroups.go | 570 ++ vendor/github.com/slack-go/slack/users.go | 760 ++ vendor/github.com/slack-go/slack/views.go | 307 + vendor/github.com/slack-go/slack/webhooks.go | 64 + vendor/github.com/slack-go/slack/websocket.go | 103 + .../slack-go/slack/websocket_channels.go | 72 + .../slack/websocket_desktop_notification.go | 19 + .../github.com/slack-go/slack/websocket_dm.go | 23 + .../slack-go/slack/websocket_dnd.go | 8 + .../slack-go/slack/websocket_files.go | 49 + .../slack-go/slack/websocket_groups.go | 49 + .../slack-go/slack/websocket_internals.go | 102 + .../slack-go/slack/websocket_managed_conn.go | 611 ++ .../slack-go/slack/websocket_misc.go | 141 + .../websocket_mobile_in_app_notification.go | 20 + .../slack-go/slack/websocket_pins.go | 16 + .../slack-go/slack/websocket_reactions.go | 25 + .../slack-go/slack/websocket_stars.go | 14 + .../slack-go/slack/websocket_subteam.go | 35 + .../slack-go/slack/websocket_teams.go | 33 + .../slack-go/slack/workflows_triggers.go | 177 + .../github.com/stretchr/objx/.codeclimate.yml | 21 + vendor/github.com/stretchr/objx/.gitignore | 11 + vendor/github.com/stretchr/objx/LICENSE | 22 + vendor/github.com/stretchr/objx/README.md | 91 + vendor/github.com/stretchr/objx/Taskfile.yml | 27 + vendor/github.com/stretchr/objx/accessors.go | 197 + .../github.com/stretchr/objx/conversions.go | 280 + vendor/github.com/stretchr/objx/doc.go | 66 + vendor/github.com/stretchr/objx/map.go | 214 + vendor/github.com/stretchr/objx/mutations.go | 77 + vendor/github.com/stretchr/objx/security.go | 12 + vendor/github.com/stretchr/objx/tests.go | 17 + .../github.com/stretchr/objx/type_specific.go | 346 + .../stretchr/objx/type_specific_codegen.go | 2261 +++++ vendor/github.com/stretchr/objx/value.go | 159 + .../github.com/stretchr/testify/mock/doc.go | 44 + .../github.com/stretchr/testify/mock/mock.go | 1298 +++ .../technoweenie/multipartstreamer/LICENSE | 7 + .../technoweenie/multipartstreamer/README.md | 47 + .../multipartstreamer/multipartstreamer.go | 101 + .../google.golang.org/grpc/otelgrpc/config.go | 164 +- .../grpc/otelgrpc/metadata_supplier.go | 40 +- .../grpc/otelgrpc/stats_handler.go | 38 +- .../grpc/otelgrpc/version.go | 2 +- .../instrumentation/net/http/otelhttp/LICENSE | 30 + .../net/http/otelhttp/client.go | 19 +- .../net/http/otelhttp/config.go | 22 +- .../instrumentation/net/http/otelhttp/doc.go | 3 +- .../net/http/otelhttp/handler.go | 13 +- .../http/otelhttp/internal/semconv/client.go | 305 + .../net/http/otelhttp/internal/semconv/env.go | 323 - .../net/http/otelhttp/internal/semconv/gen.go | 11 +- .../otelhttp/internal/semconv/httpconv.go | 573 -- .../http/otelhttp/internal/semconv/server.go | 403 + .../http/otelhttp/internal/semconv/util.go | 6 +- .../http/otelhttp/internal/semconv/v1.20.0.go | 273 - .../http/otelhttp/internal/semconvutil/gen.go | 10 - .../otelhttp/internal/semconvutil/httpconv.go | 594 -- .../otelhttp/internal/semconvutil/netconv.go | 214 - .../net/http/otelhttp/transport.go | 60 +- .../net/http/otelhttp/version.go | 2 +- .../otel/semconv/v1.20.0/README.md | 3 - .../otel/semconv/v1.20.0/attribute_group.go | 1198 --- .../otel/semconv/v1.20.0/doc.go | 9 - .../otel/semconv/v1.20.0/event.go | 188 - .../otel/semconv/v1.20.0/exception.go | 9 - .../otel/semconv/v1.20.0/http.go | 10 - .../otel/semconv/v1.20.0/resource.go | 2060 ---- .../otel/semconv/v1.20.0/schema.go | 9 - .../otel/semconv/v1.20.0/trace.go | 2599 ----- .../otel/semconv/v1.26.0/README.md | 3 - .../otel/semconv/v1.26.0/attribute_group.go | 8996 ----------------- .../otel/semconv/v1.26.0/doc.go | 9 - .../otel/semconv/v1.26.0/exception.go | 9 - .../otel/semconv/v1.26.0/metric.go | 1307 --- .../otel/semconv/v1.26.0/schema.go | 9 - .../otel/semconv/v1.37.0/httpconv/metric.go | 1728 ++++ .../x/crypto/nacl/secretbox/secretbox.go | 173 + .../x/crypto/salsa20/salsa/hsalsa20.go | 150 + .../x/crypto/salsa20/salsa/salsa208.go | 201 + .../x/crypto/salsa20/salsa/salsa20_amd64.go | 23 + .../x/crypto/salsa20/salsa/salsa20_amd64.s | 880 ++ .../x/crypto/salsa20/salsa/salsa20_noasm.go | 14 + .../x/crypto/salsa20/salsa/salsa20_ref.go | 233 + vendor/golang.org/x/sync/errgroup/errgroup.go | 151 + .../internal/xds/xdsdepmgr/watch_service.go | 83 - vendor/modules.txt | 51 +- webapp/src/components/DownloadSidebar.vue | 20 + webapp/src/components/UploadSidebar.vue | 88 +- webapp/src/config.js | 4 + webapp/src/views/UploadView.vue | 13 + 304 files changed, 61120 insertions(+), 18716 deletions(-) create mode 100644 server/handlers/notification_helpers.go create mode 100644 server/notification/log/log.go create mode 100644 server/notification/log/log_test.go create mode 100644 server/notification/notification.go create mode 100644 server/notification/service.go create mode 100644 server/notification/service_test.go create mode 100644 server/notification/smtp/smtp.go create mode 100644 server/notification/templates/all_downloaded.html create mode 100644 server/notification/templates/upload_ready.html create mode 100644 server/notification/testing/testing.go create mode 100644 server/notification/testing/testing_test.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/.gitignore create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/.golangci.yml create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/.markdownlint.yml create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/CHANGELOG.md create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/LICENSE create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/Makefile create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/README.md create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/adaptivecard.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/doc.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/format.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/getters.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/nullstring.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/doc.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/format.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/doc.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/validator.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/messagecard.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/send.go create mode 100644 vendor/github.com/atc0005/go-teams-notify/v2/textutils.go create mode 100644 vendor/github.com/bwmarrin/discordgo/.gitignore create mode 100644 vendor/github.com/bwmarrin/discordgo/.golangci.yml create mode 100644 vendor/github.com/bwmarrin/discordgo/.travis.yml create mode 100644 vendor/github.com/bwmarrin/discordgo/CONTRIBUTING.md create mode 100644 vendor/github.com/bwmarrin/discordgo/LICENSE create mode 100644 vendor/github.com/bwmarrin/discordgo/README.md create mode 100644 vendor/github.com/bwmarrin/discordgo/components.go create mode 100644 vendor/github.com/bwmarrin/discordgo/discord.go create mode 100644 vendor/github.com/bwmarrin/discordgo/endpoints.go create mode 100644 vendor/github.com/bwmarrin/discordgo/event.go create mode 100644 vendor/github.com/bwmarrin/discordgo/eventhandlers.go create mode 100644 vendor/github.com/bwmarrin/discordgo/events.go create mode 100644 vendor/github.com/bwmarrin/discordgo/interactions.go create mode 100644 vendor/github.com/bwmarrin/discordgo/locales.go create mode 100644 vendor/github.com/bwmarrin/discordgo/logging.go create mode 100644 vendor/github.com/bwmarrin/discordgo/message.go create mode 100644 vendor/github.com/bwmarrin/discordgo/mkdocs.yml create mode 100644 vendor/github.com/bwmarrin/discordgo/oauth2.go create mode 100644 vendor/github.com/bwmarrin/discordgo/ratelimit.go create mode 100644 vendor/github.com/bwmarrin/discordgo/restapi.go create mode 100644 vendor/github.com/bwmarrin/discordgo/state.go create mode 100644 vendor/github.com/bwmarrin/discordgo/structs.go create mode 100644 vendor/github.com/bwmarrin/discordgo/user.go create mode 100644 vendor/github.com/bwmarrin/discordgo/util.go create mode 100644 vendor/github.com/bwmarrin/discordgo/voice.go create mode 100644 vendor/github.com/bwmarrin/discordgo/webhook.go create mode 100644 vendor/github.com/bwmarrin/discordgo/wsapi.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/.gitignore create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go create mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go create mode 100644 vendor/github.com/gorilla/websocket/.gitignore create mode 100644 vendor/github.com/gorilla/websocket/AUTHORS create mode 100644 vendor/github.com/gorilla/websocket/LICENSE create mode 100644 vendor/github.com/gorilla/websocket/README.md create mode 100644 vendor/github.com/gorilla/websocket/client.go create mode 100644 vendor/github.com/gorilla/websocket/compression.go create mode 100644 vendor/github.com/gorilla/websocket/conn.go create mode 100644 vendor/github.com/gorilla/websocket/doc.go create mode 100644 vendor/github.com/gorilla/websocket/join.go create mode 100644 vendor/github.com/gorilla/websocket/json.go create mode 100644 vendor/github.com/gorilla/websocket/mask.go create mode 100644 vendor/github.com/gorilla/websocket/mask_safe.go create mode 100644 vendor/github.com/gorilla/websocket/prepared.go create mode 100644 vendor/github.com/gorilla/websocket/proxy.go create mode 100644 vendor/github.com/gorilla/websocket/server.go create mode 100644 vendor/github.com/gorilla/websocket/tls_handshake.go create mode 100644 vendor/github.com/gorilla/websocket/tls_handshake_116.go create mode 100644 vendor/github.com/gorilla/websocket/util.go create mode 100644 vendor/github.com/gorilla/websocket/x_net_proxy.go create mode 100644 vendor/github.com/nikoksr/notify/.codacy.yml create mode 100644 vendor/github.com/nikoksr/notify/.editorconfig create mode 100644 vendor/github.com/nikoksr/notify/.gitignore create mode 100644 vendor/github.com/nikoksr/notify/.golangci.yaml create mode 100644 vendor/github.com/nikoksr/notify/.mockery.yaml create mode 100644 vendor/github.com/nikoksr/notify/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/nikoksr/notify/CONTRIBUTING.md create mode 100644 vendor/github.com/nikoksr/notify/LICENSE create mode 100644 vendor/github.com/nikoksr/notify/Makefile create mode 100644 vendor/github.com/nikoksr/notify/README.md create mode 100644 vendor/github.com/nikoksr/notify/SECURITY.md create mode 100644 vendor/github.com/nikoksr/notify/notify.go create mode 100644 vendor/github.com/nikoksr/notify/renovate.json create mode 100644 vendor/github.com/nikoksr/notify/send.go create mode 100644 vendor/github.com/nikoksr/notify/service/discord/README.md create mode 100644 vendor/github.com/nikoksr/notify/service/discord/discord.go create mode 100644 vendor/github.com/nikoksr/notify/service/discord/mock_discord_session.go create mode 100644 vendor/github.com/nikoksr/notify/service/http/README.md create mode 100644 vendor/github.com/nikoksr/notify/service/http/doc.go create mode 100644 vendor/github.com/nikoksr/notify/service/http/http.go create mode 100644 vendor/github.com/nikoksr/notify/service/msteams/mock_teams_client.go create mode 100644 vendor/github.com/nikoksr/notify/service/msteams/ms_teams.go create mode 100644 vendor/github.com/nikoksr/notify/service/slack/mock_slack_client.go create mode 100644 vendor/github.com/nikoksr/notify/service/slack/slack.go create mode 100644 vendor/github.com/nikoksr/notify/service/slack/usage.md create mode 100644 vendor/github.com/nikoksr/notify/service/telegram/telegram.go create mode 100644 vendor/github.com/nikoksr/notify/use.go create mode 100644 vendor/github.com/nikoksr/notify/version.go create mode 100644 vendor/github.com/slack-go/slack/.gitignore create mode 100644 vendor/github.com/slack-go/slack/.golangci.yml create mode 100644 vendor/github.com/slack-go/slack/CONTRIBUTING.md create mode 100644 vendor/github.com/slack-go/slack/LICENSE create mode 100644 vendor/github.com/slack-go/slack/Makefile create mode 100644 vendor/github.com/slack-go/slack/README.md create mode 100644 vendor/github.com/slack-go/slack/admin.go create mode 100644 vendor/github.com/slack-go/slack/admin_conversations.go create mode 100644 vendor/github.com/slack-go/slack/apps.go create mode 100644 vendor/github.com/slack-go/slack/assistant.go create mode 100644 vendor/github.com/slack-go/slack/attachments.go create mode 100644 vendor/github.com/slack-go/slack/audit.go create mode 100644 vendor/github.com/slack-go/slack/auth.go create mode 100644 vendor/github.com/slack-go/slack/block.go create mode 100644 vendor/github.com/slack-go/slack/block_action.go create mode 100644 vendor/github.com/slack-go/slack/block_call.go create mode 100644 vendor/github.com/slack-go/slack/block_context.go create mode 100644 vendor/github.com/slack-go/slack/block_conv.go create mode 100644 vendor/github.com/slack-go/slack/block_divider.go create mode 100644 vendor/github.com/slack-go/slack/block_element.go create mode 100644 vendor/github.com/slack-go/slack/block_file.go create mode 100644 vendor/github.com/slack-go/slack/block_header.go create mode 100644 vendor/github.com/slack-go/slack/block_image.go create mode 100644 vendor/github.com/slack-go/slack/block_input.go create mode 100644 vendor/github.com/slack-go/slack/block_markdown.go create mode 100644 vendor/github.com/slack-go/slack/block_object.go create mode 100644 vendor/github.com/slack-go/slack/block_rich_text.go create mode 100644 vendor/github.com/slack-go/slack/block_section.go create mode 100644 vendor/github.com/slack-go/slack/block_unknown.go create mode 100644 vendor/github.com/slack-go/slack/block_video.go create mode 100644 vendor/github.com/slack-go/slack/bookmarks.go create mode 100644 vendor/github.com/slack-go/slack/bots.go create mode 100644 vendor/github.com/slack-go/slack/calls.go create mode 100644 vendor/github.com/slack-go/slack/canvas.go create mode 100644 vendor/github.com/slack-go/slack/channels.go create mode 100644 vendor/github.com/slack-go/slack/chat.go create mode 100644 vendor/github.com/slack-go/slack/comment.go create mode 100644 vendor/github.com/slack-go/slack/conversation.go create mode 100644 vendor/github.com/slack-go/slack/dialog.go create mode 100644 vendor/github.com/slack-go/slack/dialog_select.go create mode 100644 vendor/github.com/slack-go/slack/dialog_text.go create mode 100644 vendor/github.com/slack-go/slack/dnd.go create mode 100644 vendor/github.com/slack-go/slack/emoji.go create mode 100644 vendor/github.com/slack-go/slack/errors.go create mode 100644 vendor/github.com/slack-go/slack/files.go create mode 100644 vendor/github.com/slack-go/slack/function_execute.go create mode 100644 vendor/github.com/slack-go/slack/groups.go create mode 100644 vendor/github.com/slack-go/slack/history.go create mode 100644 vendor/github.com/slack-go/slack/im.go create mode 100644 vendor/github.com/slack-go/slack/info.go create mode 100644 vendor/github.com/slack-go/slack/interactions.go create mode 100644 vendor/github.com/slack-go/slack/internal/backoff/backoff.go create mode 100644 vendor/github.com/slack-go/slack/internal/errorsx/errorsx.go create mode 100644 vendor/github.com/slack-go/slack/internal/timex/timex.go create mode 100644 vendor/github.com/slack-go/slack/item.go create mode 100644 vendor/github.com/slack-go/slack/logger.go create mode 100644 vendor/github.com/slack-go/slack/logo.png create mode 100644 vendor/github.com/slack-go/slack/manifests.go create mode 100644 vendor/github.com/slack-go/slack/messageID.go create mode 100644 vendor/github.com/slack-go/slack/messages.go create mode 100644 vendor/github.com/slack-go/slack/metadata.go create mode 100644 vendor/github.com/slack-go/slack/migration.go create mode 100644 vendor/github.com/slack-go/slack/misc.go create mode 100644 vendor/github.com/slack-go/slack/oauth.go create mode 100644 vendor/github.com/slack-go/slack/pagination.go create mode 100644 vendor/github.com/slack-go/slack/pins.go create mode 100644 vendor/github.com/slack-go/slack/reactions.go create mode 100644 vendor/github.com/slack-go/slack/reminders.go create mode 100644 vendor/github.com/slack-go/slack/remotefiles.go create mode 100644 vendor/github.com/slack-go/slack/rtm.go create mode 100644 vendor/github.com/slack-go/slack/search.go create mode 100644 vendor/github.com/slack-go/slack/security.go create mode 100644 vendor/github.com/slack-go/slack/slack.go create mode 100644 vendor/github.com/slack-go/slack/slackutilsx/slackutilsx.go create mode 100644 vendor/github.com/slack-go/slack/slash.go create mode 100644 vendor/github.com/slack-go/slack/socket_mode.go create mode 100644 vendor/github.com/slack-go/slack/stars.go create mode 100644 vendor/github.com/slack-go/slack/status_code_error.go create mode 100644 vendor/github.com/slack-go/slack/team.go create mode 100644 vendor/github.com/slack-go/slack/tokens.go create mode 100644 vendor/github.com/slack-go/slack/usergroups.go create mode 100644 vendor/github.com/slack-go/slack/users.go create mode 100644 vendor/github.com/slack-go/slack/views.go create mode 100644 vendor/github.com/slack-go/slack/webhooks.go create mode 100644 vendor/github.com/slack-go/slack/websocket.go create mode 100644 vendor/github.com/slack-go/slack/websocket_channels.go create mode 100644 vendor/github.com/slack-go/slack/websocket_desktop_notification.go create mode 100644 vendor/github.com/slack-go/slack/websocket_dm.go create mode 100644 vendor/github.com/slack-go/slack/websocket_dnd.go create mode 100644 vendor/github.com/slack-go/slack/websocket_files.go create mode 100644 vendor/github.com/slack-go/slack/websocket_groups.go create mode 100644 vendor/github.com/slack-go/slack/websocket_internals.go create mode 100644 vendor/github.com/slack-go/slack/websocket_managed_conn.go create mode 100644 vendor/github.com/slack-go/slack/websocket_misc.go create mode 100644 vendor/github.com/slack-go/slack/websocket_mobile_in_app_notification.go create mode 100644 vendor/github.com/slack-go/slack/websocket_pins.go create mode 100644 vendor/github.com/slack-go/slack/websocket_reactions.go create mode 100644 vendor/github.com/slack-go/slack/websocket_stars.go create mode 100644 vendor/github.com/slack-go/slack/websocket_subteam.go create mode 100644 vendor/github.com/slack-go/slack/websocket_teams.go create mode 100644 vendor/github.com/slack-go/slack/workflows_triggers.go create mode 100644 vendor/github.com/stretchr/objx/.codeclimate.yml create mode 100644 vendor/github.com/stretchr/objx/.gitignore create mode 100644 vendor/github.com/stretchr/objx/LICENSE create mode 100644 vendor/github.com/stretchr/objx/README.md create mode 100644 vendor/github.com/stretchr/objx/Taskfile.yml create mode 100644 vendor/github.com/stretchr/objx/accessors.go create mode 100644 vendor/github.com/stretchr/objx/conversions.go create mode 100644 vendor/github.com/stretchr/objx/doc.go create mode 100644 vendor/github.com/stretchr/objx/map.go create mode 100644 vendor/github.com/stretchr/objx/mutations.go create mode 100644 vendor/github.com/stretchr/objx/security.go create mode 100644 vendor/github.com/stretchr/objx/tests.go create mode 100644 vendor/github.com/stretchr/objx/type_specific.go create mode 100644 vendor/github.com/stretchr/objx/type_specific_codegen.go create mode 100644 vendor/github.com/stretchr/objx/value.go create mode 100644 vendor/github.com/stretchr/testify/mock/doc.go create mode 100644 vendor/github.com/stretchr/testify/mock/mock.go create mode 100644 vendor/github.com/technoweenie/multipartstreamer/LICENSE create mode 100644 vendor/github.com/technoweenie/multipartstreamer/README.md create mode 100644 vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go create mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/client.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go create mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/server.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/gen.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/httpconv.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/README.md delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/README.md delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/attribute_group.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/doc.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/exception.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/metric.go delete mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.26.0/schema.go create mode 100644 vendor/go.opentelemetry.io/otel/semconv/v1.37.0/httpconv/metric.go create mode 100644 vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go create mode 100644 vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go create mode 100644 vendor/golang.org/x/sync/errgroup/errgroup.go delete mode 100644 vendor/google.golang.org/grpc/internal/xds/xdsdepmgr/watch_service.go diff --git a/charts/plik/templates/configmap.yaml b/charts/plik/templates/configmap.yaml index 31795d9b9..c803dfbf5 100644 --- a/charts/plik/templates/configmap.yaml +++ b/charts/plik/templates/configmap.yaml @@ -53,6 +53,13 @@ data: FeatureClients = {{ .Values.plikd.FeatureClients | quote }} FeatureGithub = {{ .Values.plikd.FeatureGithub | quote }} FeatureText = {{ .Values.plikd.FeatureText | quote }} + FeatureE2EE = {{ .Values.plikd.FeatureE2EE | quote }} + FeatureNotification = {{ .Values.plikd.FeatureNotification | quote }} + + MaxUploadReceivers = {{ .Values.plikd.MaxUploadReceivers }} + {{- if .Values.plikd.NotificationBackend }} + NotificationBackend = {{ .Values.plikd.NotificationBackend | quote }} + {{- end }} GoogleApiClientID = {{ .Values.plikd.GoogleApiClientID | quote }} GoogleValidDomains = {{ .Values.plikd.GoogleValidDomains | toJson }} @@ -74,3 +81,10 @@ data: {{- range $key, $val := .Values.plikd.MetadataBackendConfig }} {{ $key }} = {{ $val | toJson }} {{- end }} + + {{- if .Values.plikd.NotificationBackend }} + [NotificationBackendConfig] + {{- range $key, $val := .Values.plikd.NotificationBackendConfig }} + {{ $key }} = {{ $val | toJson }} + {{- end }} + {{- end }} diff --git a/charts/plik/templates/secret.yaml b/charts/plik/templates/secret.yaml index a04cebea3..5579b3474 100644 --- a/charts/plik/templates/secret.yaml +++ b/charts/plik/templates/secret.yaml @@ -25,4 +25,7 @@ stringData: {{- if .Values.secrets.metadataBackend }} PLIKD_METADATA_BACKEND_CONFIG: {{ .Values.secrets.metadataBackend | toJson | quote }} {{- end }} + {{- if .Values.secrets.notificationBackend }} + PLIKD_NOTIFICATION_BACKEND_CONFIG: {{ .Values.secrets.notificationBackend | toJson | quote }} + {{- end }} {{- end }} diff --git a/charts/plik/values.yaml b/charts/plik/values.yaml index e51f3047f..1e39cf402 100644 --- a/charts/plik/values.yaml +++ b/charts/plik/values.yaml @@ -232,6 +232,22 @@ plikd: FeatureGithub: "enabled" # -- Enable plain-text paste mode FeatureText: "enabled" + # -- Enable end-to-end encryption (age) + FeatureE2EE: "enabled" + # -- Enable email notifications on upload/download events (`enabled`, `disabled`) + FeatureNotification: "disabled" + + # -- Maximum number of email recipients per upload + MaxUploadReceivers: 5 + # -- Notification backend type (`smtp`, `log`) + NotificationBackend: "" + # -- Non-sensitive notification backend configuration (SMTP host, port, from, TLS). + # Keys depend on the backend type. + NotificationBackendConfig: + Host: "" + Port: 587 + From: "" + TLS: true # -- Google OAuth2 client ID GoogleApiClientID: "" @@ -316,3 +332,9 @@ secrets: # Injected as `PLIKD_METADATA_BACKEND_CONFIG` JSON. metadataBackend: {} # Password: "" + + # -- Sensitive notification backend config (e.g. SMTP password). + # Injected as `PLIKD_NOTIFICATION_BACKEND_CONFIG` JSON. + notificationBackend: {} + # Username: "" + # Password: "" diff --git a/go.mod b/go.mod index 81104c685..bc7e8ec60 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/mitchellh/go-homedir v1.1.0 github.com/modelcontextprotocol/go-sdk v1.3.1 github.com/ncw/swift v1.0.53 + github.com/nikoksr/notify v1.5.0 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d github.com/pilagod/gorm-cursor-paginator/v2 v2.7.0 github.com/prometheus/client_golang v1.23.2 @@ -53,7 +54,9 @@ require ( github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 // indirect + github.com/atc0005/go-teams-notify/v2 v2.14.0 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/bwmarrin/discordgo v0.29.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect @@ -66,11 +69,13 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect github.com/google/jsonschema-go v0.4.2 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect github.com/googleapis/gax-go/v2 v2.17.0 // indirect + github.com/gorilla/websocket v1.5.3 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect @@ -95,14 +100,17 @@ require ( github.com/rs/xid v1.6.0 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.3 // indirect + github.com/slack-go/slack v0.17.3 // indirect github.com/spf13/pflag v1.0.9 // indirect github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect + github.com/stretchr/objx v0.5.3 // indirect + github.com/technoweenie/multipartstreamer v1.0.1 // indirect github.com/tinylib/msgp v1.6.1 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect go.opentelemetry.io/otel v1.40.0 // indirect go.opentelemetry.io/otel/metric v1.40.0 // indirect go.opentelemetry.io/otel/sdk v1.40.0 // indirect diff --git a/go.sum b/go.sum index 3d81fdd24..56a01b052 100644 --- a/go.sum +++ b/go.sum @@ -82,12 +82,16 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/atc0005/go-teams-notify/v2 v2.14.0 h1:7N+xw+COnYANLREaAveQ65rsNQ12nIZJED9nMLyscCo= +github.com/atc0005/go-teams-notify/v2 v2.14.0/go.mod h1:EECsWM2b0Hvoz7O+QdlsvyN2KCUOFQCGj8bUBXv3A3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/boombuler/barcode v1.1.0 h1:ChaYjBR63fr4LFyGn8E8nt7dBSt3MiU3zMOZqFvVkHo= github.com/boombuler/barcode v1.1.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/bwmarrin/discordgo v0.29.0 h1:FmWeXFaKUwrcL3Cx65c20bTRW+vOb6k8AnaP+EgjDno= +github.com/bwmarrin/discordgo v0.29.0/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= github.com/camathieu/pb v1.0.29-0.20190403132434-889de99fc8d5 h1:SozutapAMj81GkdpIHtOGYyQQXiZcnLrSTdaLwa6X+Q= github.com/camathieu/pb v1.0.29-0.20190403132434-889de99fc8d5/go.mod h1:nx+wKYI7opmj2WFVyPrOKVehnarQZcZVfDoAFJea2iM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -159,6 +163,10 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= +github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U= +github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= @@ -238,6 +246,9 @@ github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= @@ -301,6 +312,8 @@ github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/ github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA= +github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -342,15 +355,17 @@ github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI= @@ -379,6 +394,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/ncw/swift v1.0.53 h1:luHjjTNtekIEvHg5KdAFIBaH7bWfNkefwFnpDffSIks= github.com/ncw/swift v1.0.53/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= +github.com/nikoksr/notify v1.5.0 h1:mzkCw8eb0P+qHwgmGQyPPGqz4GH+07FJDr44Bs16T9k= +github.com/nikoksr/notify v1.5.0/go.mod h1:CEV9Bw9Y59K5oj7d8h83Xl32ATeL43ZEg9qTQsfwcCc= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= @@ -463,6 +480,8 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/slack-go/slack v0.17.3 h1:zV5qO3Q+WJAQ/XwbGfNFrRMaJ5T/naqaonyPV/1TP4g= +github.com/slack-go/slack v0.17.3/go.mod h1:X+UqOufi3LYQHDnMG1vxf0J8asC6+WllXrVrhl8/Prk= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= @@ -474,6 +493,9 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -482,8 +504,12 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= +github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog= github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY= github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/xhit/go-str2duration v1.2.0/go.mod h1:3cPSlfZlUHVlneIVfePFWcJZsuwf+P1v2SRTV4cUmp4= @@ -505,10 +531,10 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 h1:YH4g8lQroajqUwWbq/tr2QX1JFmEXaDLgG+ew9bLMWo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0/go.mod h1:fvPi2qXDqFs8M4B4fmJhE92TyQs9Ydjlg3RvfUp+NbQ= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0 h1:RN3ifU8y4prNWeEnQp2kRRHz8UwonAEYZl8tUzHEXAk= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0/go.mod h1:habDz3tEWiFANTo6oUE99EmaFUrCNYAAg3wiVmusm70= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ= go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.39.0 h1:5gn2urDL/FBnK8OkCfD1j3/ER79rUuTYmCvlXBKeYL8= @@ -545,6 +571,7 @@ golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= diff --git a/server/common/config.go b/server/common/config.go index 3db540bf0..9bf9e6c7d 100644 --- a/server/common/config.go +++ b/server/common/config.go @@ -23,6 +23,13 @@ import ( const envPrefix = "PLIKD_" +// NotificationChannel describes a push notification channel (e.g. Slack, Telegram). +// These use nikoksr/notify and send plain-text summaries, unlike the SMTP backend which sends HTML. +type NotificationChannel struct { + Type string `json:"type"` // slack, telegram, discord, msteams, http + Config map[string]any `json:"config"` // service-specific configuration +} + // Configuration object type Configuration struct { Debug bool `json:"-"` @@ -80,6 +87,7 @@ type Configuration struct { FeatureGithub string `json:"feature_github"` FeatureText string `json:"feature_text"` FeatureE2EE string `json:"feature_e2ee"` + FeatureNotification string `json:"feature_notification"` // Deprecated Feature Flags Authentication bool `json:"authentication"` // Deprecated: >1.3.6 @@ -113,6 +121,13 @@ type Configuration struct { DataBackend string `json:"-"` DataBackendConfig map[string]any `json:"-"` + NotificationBackend string `json:"-"` + NotificationBackendConfig map[string]any `json:"-"` + MaxUploadReceivers int `json:"maxUploadReceivers"` + + // Additional notification channels (plain text push notifications via nikoksr/notify) + NotificationChannels []NotificationChannel `json:"-"` + downloadDomainURL *url.URL downloadDomainURLAlias []*url.URL uploadWhitelist []*net.IPNet @@ -153,6 +168,8 @@ func NewConfiguration() (config *Configuration) { config.DataBackend = "file" + config.MaxUploadReceivers = 5 + config.WebappDirectory = "../webapp/dist" config.ClientsDirectory = "../clients" config.ChangelogDirectory = "../changelog" @@ -453,6 +470,7 @@ func (config *Configuration) String() string { str += fmt.Sprintf("Upload set TTL : %s\n", config.FeatureSetTTL) str += fmt.Sprintf("Upload extend TTL : %s\n", config.FeatureExtendTTL) str += fmt.Sprintf("E2E encryption : %s\n", config.FeatureE2EE) + str += fmt.Sprintf("Notification : %s\n", config.FeatureNotification) str += fmt.Sprintf("Delete account : %s\n", config.FeatureDeleteAccount) str += fmt.Sprintf("Authentication : %s\n", config.FeatureAuthentication) diff --git a/server/common/feature_flags.go b/server/common/feature_flags.go index ec0b3bf82..5e7d05678 100644 --- a/server/common/feature_flags.go +++ b/server/common/feature_flags.go @@ -57,6 +57,7 @@ func (config *Configuration) initializeFeatureFlags() error { config.initializeFeatureClients, config.initializeFeatureText, config.initializeFeatureE2EE, + config.initializeFeatureNotification, } for _, initialization := range initializations { @@ -295,3 +296,16 @@ func (config *Configuration) initializeFeatureE2EE() error { return nil } + +func (config *Configuration) initializeFeatureNotification() error { + if config.FeatureNotification == "" { + config.FeatureNotification = FeatureDisabled + } + + err := ValidateCustomFeatureFlag(config.FeatureNotification, []string{FeatureDisabled, FeatureEnabled}) + if err != nil { + return fmt.Errorf("Invalid value for FeatureNotification : %s", err) + } + + return nil +} diff --git a/server/common/file.go b/server/common/file.go index d4f0d1455..78f8e2992 100644 --- a/server/common/file.go +++ b/server/common/file.go @@ -34,7 +34,8 @@ type File struct { BackendDetails string `json:"-"` - CreatedAt time.Time `json:"createdAt"` + CreatedAt time.Time `json:"createdAt"` + DownloadedAt *time.Time `json:"downloadedAt,omitempty"` } // NewFile instantiate a new object diff --git a/server/common/upload.go b/server/common/upload.go index 40a15d514..255ec5755 100644 --- a/server/common/upload.go +++ b/server/common/upload.go @@ -2,6 +2,8 @@ package common import ( "crypto/rand" + "database/sql/driver" + "encoding/json" "fmt" "math/big" "slices" @@ -10,6 +12,42 @@ import ( "gorm.io/gorm" ) +// Receivers is a custom type for storing a list of email addresses as JSON in the database. +type Receivers []string + +// Scan implements the sql.Scanner interface for reading JSON from the database. +func (r *Receivers) Scan(value any) error { + if value == nil { + *r = nil + return nil + } + bytes, ok := value.([]byte) + if !ok { + str, ok := value.(string) + if !ok { + return fmt.Errorf("receivers: unsupported type %T", value) + } + bytes = []byte(str) + } + if len(bytes) == 0 { + *r = nil + return nil + } + return json.Unmarshal(bytes, r) +} + +// Value implements the driver.Valuer interface for writing JSON to the database. +func (r Receivers) Value() (driver.Value, error) { + if len(r) == 0 { + return nil, nil + } + bytes, err := json.Marshal(r) + if err != nil { + return nil, err + } + return string(bytes), nil +} + var ( randRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") ) @@ -41,6 +79,9 @@ type Upload struct { Login string `json:"login,omitempty"` Password string `json:"password,omitempty"` + Receivers Receivers `json:"receivers,omitempty" gorm:"type:text"` + NotifyCreator bool `json:"notifyCreator,omitempty"` + CreatedAt time.Time `json:"createdAt"` DeletedAt gorm.DeletedAt `json:"-" gorm:"index:idx_upload_deleted_at"` ExpireAt *time.Time `json:"expireAt" gorm:"index:idx_upload_expire_at"` @@ -112,6 +153,7 @@ func (upload *Upload) Sanitize(config *Configuration) { if !upload.IsAdmin { upload.UploadToken = "" + upload.Receivers = nil } upload.DownloadDomain = config.DownloadDomain diff --git a/server/context/context.go b/server/context/context.go index 282969c37..e0251c942 100644 --- a/server/context/context.go +++ b/server/context/context.go @@ -9,6 +9,7 @@ import ( "github.com/root-gg/plik/server/common" "github.com/root-gg/plik/server/data" "github.com/root-gg/plik/server/metadata" + "github.com/root-gg/plik/server/notification" ) // Context to be propagated throughout the middleware chain @@ -20,6 +21,7 @@ type Context struct { streamBackend data.Backend authenticator *common.SessionAuthenticator metrics *common.PlikMetrics + notificationService *notification.Service pagingQuery *common.PagingQuery sourceIP net.IP upload *common.Upload @@ -175,6 +177,23 @@ func (ctx *Context) SetMetrics(metrics *common.PlikMetrics) { ctx.metrics = metrics } +// GetNotificationService get notificationService from the context. +// Returns nil if notifications are not configured. +func (ctx *Context) GetNotificationService() *notification.Service { + ctx.mu.RLock() + defer ctx.mu.RUnlock() + + return ctx.notificationService +} + +// SetNotificationService set notificationService in the context +func (ctx *Context) SetNotificationService(notificationService *notification.Service) { + ctx.mu.Lock() + defer ctx.mu.Unlock() + + ctx.notificationService = notificationService +} + // GetPagingQuery get pagingQuery from the context. func (ctx *Context) GetPagingQuery() *common.PagingQuery { ctx.mu.RLock() diff --git a/server/context/upload.go b/server/context/upload.go index ff3662a3e..0ecb4c869 100644 --- a/server/context/upload.go +++ b/server/context/upload.go @@ -3,6 +3,7 @@ package context import ( "fmt" "net/http" + "net/mail" "strings" "time" @@ -11,6 +12,12 @@ import ( "github.com/root-gg/utils" ) +// isValidEmail checks if the given string is a valid email address. +func isValidEmail(email string) bool { + _, err := mail.ParseAddress(email) + return err == nil +} + // CreateUpload from params and context (check configuration and default values, generate upload and file IDs, ... ) func (ctx *Context) CreateUpload(params *common.Upload) (upload *common.Upload, err error) { upload = common.NewUpload() @@ -183,6 +190,24 @@ func (ctx *Context) setParams(upload *common.Upload, params *common.Upload) (err return fmt.Errorf("invalid e2ee scheme %q", upload.E2EE) } + // Notification parameters + if config.FeatureNotification != common.FeatureDisabled { + upload.NotifyCreator = params.NotifyCreator + if len(params.Receivers) > 0 { + // Validate and cap receivers + maxReceivers := config.MaxUploadReceivers + if maxReceivers > 0 && len(params.Receivers) > maxReceivers { + return fmt.Errorf("too many receivers: maximum is %d", maxReceivers) + } + for _, email := range params.Receivers { + if !isValidEmail(email) { + return fmt.Errorf("invalid receiver email: %q", email) + } + } + upload.Receivers = params.Receivers + } + } + return nil } diff --git a/server/handlers/add_file.go b/server/handlers/add_file.go index b4faa764d..b079b30f2 100644 --- a/server/handlers/add_file.go +++ b/server/handlers/add_file.go @@ -12,6 +12,7 @@ import ( "github.com/root-gg/plik/server/common" "github.com/root-gg/plik/server/context" "github.com/root-gg/plik/server/data" + "github.com/root-gg/plik/server/notification" ) type preprocessOutputReturn struct { @@ -196,6 +197,41 @@ func AddFile(ctx *context.Context, resp http.ResponseWriter, req *http.Request) // sending metadata back to the client file.Sanitize() + // Check if all files are uploaded and fire notification + notifySvc := ctx.GetNotificationService() + if notifySvc != nil && !upload.Stream { + go func() { + allUploaded, err := checkAllFilesUploaded(ctx, upload.ID) + if err != nil { + log.Warningf("unable to check upload file status for notification: %s", err) + return + } + if allUploaded { + // Fetch the full upload with files for the notification + fullUpload, err := ctx.GetMetadataBackend().GetUpload(upload.ID) + if err != nil { + log.Warningf("unable to fetch upload for notification: %s", err) + return + } + files, err := ctx.GetMetadataBackend().GetFiles(upload.ID) + if err != nil { + log.Warningf("unable to fetch upload files for notification: %s", err) + return + } + fullUpload.Files = files + var user *common.User + if fullUpload.User != "" { + user, _ = ctx.GetMetadataBackend().GetUser(fullUpload.User) + } + notifySvc.Notify(notification.Event{ + Type: notification.EventUploadReady, + Upload: fullUpload, + User: user, + }) + } + }() + } + if ctx.IsQuick() { // Do our best to print the file url in the response. var url string diff --git a/server/handlers/get_file.go b/server/handlers/get_file.go index 54407b487..c95b4d844 100644 --- a/server/handlers/get_file.go +++ b/server/handlers/get_file.go @@ -10,6 +10,7 @@ import ( "github.com/root-gg/plik/server/common" "github.com/root-gg/plik/server/context" "github.com/root-gg/plik/server/data" + "github.com/root-gg/plik/server/notification" ) // GetFile download a file @@ -137,6 +138,48 @@ func GetFile(ctx *context.Context, resp http.ResponseWriter, req *http.Request) } } + // Track download for notification + notifySvc := ctx.GetNotificationService() + if req.Method == "GET" && notifySvc != nil && !upload.Stream { + go func() { + firstDownload, err := ctx.GetMetadataBackend().UpdateFileDownloadedAt(file) + if err != nil { + log.Warningf("unable to update file downloaded_at: %s", err) + return + } + if firstDownload { + // Check if all files have been downloaded + allDownloaded, err := checkAllFilesDownloaded(ctx, upload.ID) + if err != nil { + log.Warningf("unable to check download status for notification: %s", err) + return + } + if allDownloaded { + fullUpload, err := ctx.GetMetadataBackend().GetUpload(upload.ID) + if err != nil { + log.Warningf("unable to fetch upload for notification: %s", err) + return + } + files, err := ctx.GetMetadataBackend().GetFiles(upload.ID) + if err != nil { + log.Warningf("unable to fetch upload files for notification: %s", err) + return + } + fullUpload.Files = files + var user *common.User + if fullUpload.User != "" { + user, _ = ctx.GetMetadataBackend().GetUser(fullUpload.User) + } + notifySvc.Notify(notification.Event{ + Type: notification.EventAllDownloaded, + Upload: fullUpload, + User: user, + }) + } + } + }() + } + if file.Status == common.FileRemoved { // Remove the file asynchronously err := purge(ctx, file) diff --git a/server/handlers/notification_helpers.go b/server/handlers/notification_helpers.go new file mode 100644 index 000000000..54ce7c565 --- /dev/null +++ b/server/handlers/notification_helpers.go @@ -0,0 +1,46 @@ +package handlers + +import ( + "github.com/root-gg/plik/server/common" + "github.com/root-gg/plik/server/context" +) + +// checkAllFilesUploaded checks if all files in the upload have been uploaded +func checkAllFilesUploaded(ctx *context.Context, uploadID string) (bool, error) { + files, err := ctx.GetMetadataBackend().GetFiles(uploadID) + if err != nil { + return false, err + } + + if len(files) == 0 { + return false, nil + } + + for _, f := range files { + if f.Status != common.FileUploaded { + return false, nil + } + } + + return true, nil +} + +// checkAllFilesDownloaded checks if all uploaded files in the upload have been downloaded at least once +func checkAllFilesDownloaded(ctx *context.Context, uploadID string) (bool, error) { + files, err := ctx.GetMetadataBackend().GetFiles(uploadID) + if err != nil { + return false, err + } + + if len(files) == 0 { + return false, nil + } + + for _, f := range files { + if f.Status == common.FileUploaded && f.DownloadedAt == nil { + return false, nil + } + } + + return true, nil +} diff --git a/server/metadata/file.go b/server/metadata/file.go index ebf6bdb54..3c34c559d 100644 --- a/server/metadata/file.go +++ b/server/metadata/file.go @@ -2,6 +2,7 @@ package metadata import ( "fmt" + "time" "gorm.io/gorm" @@ -164,3 +165,26 @@ func (b *Backend) ForEachFile(f func(file *common.File) error) (err error) { return nil } + +// UpdateFileDownloadedAt sets the DownloadedAt timestamp for a file if not already set. +// Returns true if the timestamp was actually set (first download). +func (b *Backend) UpdateFileDownloadedAt(file *common.File) (firstDownload bool, err error) { + if file.DownloadedAt != nil { + return false, nil + } + + now := time.Now() + result := b.db.Model(&common.File{}). + Where("id = ? AND downloaded_at IS NULL", file.ID). + Update("downloaded_at", now) + if result.Error != nil { + return false, result.Error + } + + if result.RowsAffected > 0 { + file.DownloadedAt = &now + return true, nil + } + + return false, nil +} diff --git a/server/metadata/migrations.go b/server/metadata/migrations.go index ac0f1bb10..8f71eea89 100644 --- a/server/metadata/migrations.go +++ b/server/metadata/migrations.go @@ -203,6 +203,29 @@ func (b *Backend) getMigrations() []*gormigrate.Migration { b.log.Criticalf("Something went wrong. Please check database status manually") return nil }, + }, { + ID: "0008-notification", + Migrate: func(tx *gorm.DB) error { + type Upload struct { + Receivers string `gorm:"type:text"` + NotifyCreator bool + } + + type File struct { + DownloadedAt *time.Time + } + + b.log.Warning("Applying database migration 0008-notification") + err := b.setupTxForMigration(tx).AutoMigrate(&Upload{}) + if err != nil { + return err + } + return b.setupTxForMigration(tx).AutoMigrate(&File{}) + }, + Rollback: func(tx *gorm.DB) error { + b.log.Criticalf("Something went wrong. Please check database status manually") + return nil + }, }, } diff --git a/server/metadata/migrations_test.go b/server/metadata/migrations_test.go index 8d793365d..7193301ab 100644 --- a/server/metadata/migrations_test.go +++ b/server/metadata/migrations_test.go @@ -75,6 +75,8 @@ func generateTestData(t *testing.T, b *Backend) { upload.Comments = "愛 الحب 사랑 αγάπη любовь प्यार Սեր माया" upload.Login = "foo" upload.Password = "bar" + upload.Receivers = common.Receivers{"receiver1@example.com", "receiver2@example.com"} + upload.NotifyCreator = true upload.TTL = 3600 upload.CreatedAt = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) deadline := time.Date(2000, 1, 1, 1, 0, 0, 0, time.UTC) @@ -89,6 +91,8 @@ func generateTestData(t *testing.T, b *Backend) { file.Reference = "1" file.Type = "application/awesome" file.Status = common.FileUploaded + downloadedAt := time.Date(2000, 1, 1, 0, 30, 0, 0, time.UTC) + file.DownloadedAt = &downloadedAt err = b.CreateUpload(upload) require.NoError(t, err, "unable to save upload metadata") diff --git a/server/notification/log/log.go b/server/notification/log/log.go new file mode 100644 index 000000000..7a007ec00 --- /dev/null +++ b/server/notification/log/log.go @@ -0,0 +1,34 @@ +package log + +import ( + "strings" + + "github.com/root-gg/logger" + "github.com/root-gg/plik/server/notification" +) + +// Ensure Log Provider implements notification.Provider interface +var _ notification.Provider = (*Provider)(nil) + +// Provider logs notifications instead of sending them. +// Useful for development, testing, and debugging. +type Provider struct { + Logger *logger.Logger +} + +// NewProvider instantiates a new Log notification provider. +func NewProvider(log *logger.Logger) *Provider { + return &Provider{Logger: log} +} + +// Name returns the provider name. +func (p *Provider) Name() string { + return "log" +} + +// Send logs the notification message. +func (p *Provider) Send(msg *notification.Message) error { + p.Logger.Infof("Notification to [%s] subject=%q text=%q", + strings.Join(msg.To, ", "), msg.Subject, msg.Text) + return nil +} diff --git a/server/notification/log/log_test.go b/server/notification/log/log_test.go new file mode 100644 index 000000000..2720085f5 --- /dev/null +++ b/server/notification/log/log_test.go @@ -0,0 +1,42 @@ +package log + +import ( + "testing" + + "github.com/root-gg/logger" + "github.com/root-gg/plik/server/notification" + "github.com/stretchr/testify/require" +) + +func TestLogProvider_Name(t *testing.T) { + p := NewProvider(logger.NewLogger()) + require.Equal(t, "log", p.Name()) +} + +func TestLogProvider_Send(t *testing.T) { + log := logger.NewLogger() + p := NewProvider(log) + + msg := ¬ification.Message{ + To: []string{"test@example.com"}, + Subject: "Test Notification", + HTML: "

Hello

", + Text: "Hello", + } + + err := p.Send(msg) + require.NoError(t, err) +} + +func TestLogProvider_SendEmpty(t *testing.T) { + log := logger.NewLogger() + p := NewProvider(log) + + msg := ¬ification.Message{ + To: []string{}, + Subject: "No recipients", + } + + err := p.Send(msg) + require.NoError(t, err) +} diff --git a/server/notification/notification.go b/server/notification/notification.go new file mode 100644 index 000000000..4aab084c9 --- /dev/null +++ b/server/notification/notification.go @@ -0,0 +1,20 @@ +package notification + +// Provider interface describes methods that notification backends +// must implement to be compatible with Plik. +type Provider interface { + // Send delivers a notification message to the specified recipients. + // Implementations must not modify the Message. + Send(msg *Message) error + + // Name returns the provider name (e.g., "smtp", "log"). + Name() string +} + +// Message represents an outgoing notification. +type Message struct { + To []string // Recipient email addresses + Subject string // Email subject line + HTML string // HTML body + Text string // Plain-text fallback body +} diff --git a/server/notification/service.go b/server/notification/service.go new file mode 100644 index 000000000..6866d11e6 --- /dev/null +++ b/server/notification/service.go @@ -0,0 +1,309 @@ +package notification + +import ( + "bytes" + gocontext "context" + "embed" + "fmt" + "html/template" + "time" + + "github.com/dustin/go-humanize" + "github.com/nikoksr/notify" + "github.com/root-gg/logger" + "github.com/root-gg/plik/server/common" +) + +//go:embed templates/*.html +var templateFS embed.FS + +// EventType defines the type of notification event. +type EventType int + +const ( + // EventUploadReady is fired when all files in an upload have been uploaded. + EventUploadReady EventType = iota + // EventAllDownloaded is fired when all files in an upload have been downloaded at least once. + EventAllDownloaded +) + +// Event represents a notification event to be processed. +type Event struct { + Type EventType + Upload *common.Upload + User *common.User // Creator, may be nil for anonymous uploads +} + +// TemplateData is the data passed to email templates. +type TemplateData struct { + Upload *common.Upload + DownloadURL string + ServerName string + ExpiresAt string + FileCount int + TotalSize string + Strings map[string]string +} + +// Service manages asynchronous notification dispatch. +type Service struct { + provider Provider + channels *notify.Notify // nikoksr/notify channels (optional, may be nil) + logger *logger.Logger + config *common.Configuration + ch chan Event + done chan struct{} + + uploadReadyTmpl *template.Template + allDownloadedTmpl *template.Template +} + +// NewService creates a new notification service. +func NewService(provider Provider, config *common.Configuration, log *logger.Logger) (*Service, error) { + funcMap := template.FuncMap{ + "humanizeBytes": func(size int64) string { + return humanize.Bytes(uint64(size)) + }, + } + + uploadReadyTmpl, err := template.New("upload_ready.html").Funcs(funcMap).ParseFS(templateFS, "templates/upload_ready.html") + if err != nil { + return nil, fmt.Errorf("failed to parse upload_ready template: %w", err) + } + + allDownloadedTmpl, err := template.New("all_downloaded.html").Funcs(funcMap).ParseFS(templateFS, "templates/all_downloaded.html") + if err != nil { + return nil, fmt.Errorf("failed to parse all_downloaded template: %w", err) + } + + return &Service{ + provider: provider, + logger: log, + config: config, + ch: make(chan Event, 100), + done: make(chan struct{}), + uploadReadyTmpl: uploadReadyTmpl, + allDownloadedTmpl: allDownloadedTmpl, + }, nil +} + +// SetChannels sets the nikoksr/notify channels for plain-text push notifications. +func (s *Service) SetChannels(channels *notify.Notify) { + s.channels = channels +} + +// Start begins the background notification worker. +func (s *Service) Start() { + go s.worker() +} + +// Stop gracefully shuts down the notification worker. +func (s *Service) Stop() { + close(s.ch) + <-s.done +} + +// Notify enqueues a notification event for async processing. +// Non-blocking: if the channel is full, the event is dropped with a warning. +func (s *Service) Notify(event Event) { + select { + case s.ch <- event: + default: + s.logger.Warningf("notification channel full, dropping event type=%d upload=%s", event.Type, event.Upload.ID) + } +} + +func (s *Service) worker() { + defer close(s.done) + + for event := range s.ch { + s.processEvent(event) + } +} + +func (s *Service) processEvent(event Event) { + defer func() { + if r := recover(); r != nil { + s.logger.Warningf("panic in notification worker: %v", r) + } + }() + + var err error + switch event.Type { + case EventUploadReady: + err = s.sendUploadReady(event) + case EventAllDownloaded: + err = s.sendAllDownloaded(event) + default: + s.logger.Warningf("unknown notification event type: %d", event.Type) + return + } + + if err != nil { + s.logger.Warningf("failed to send notification: %s", err) + } + + // Dispatch to nikoksr/notify channels (plain text) + if s.channels != nil { + s.dispatchToChannels(event) + } +} + +func (s *Service) getDownloadURL(upload *common.Upload) string { + var baseURL string + if s.config.GetDownloadDomain() != nil { + baseURL = s.config.GetDownloadDomain().String() + } else { + baseURL = s.config.GetServerURL().String() + } + return fmt.Sprintf("%s/#/?id=%s", baseURL, upload.ID) +} + +func (s *Service) getServerName() string { + if s.config.GetDownloadDomain() != nil { + return s.config.GetDownloadDomain().Host + } + return "Plik" +} + +func (s *Service) buildTemplateData(upload *common.Upload) TemplateData { + var totalSize int64 + for _, f := range upload.Files { + totalSize += f.Size + } + + var expiresAt string + if upload.ExpireAt != nil { + expiresAt = upload.ExpireAt.Format(time.RFC1123) + } else { + expiresAt = "Never" + } + + return TemplateData{ + Upload: upload, + DownloadURL: s.getDownloadURL(upload), + ServerName: s.getServerName(), + ExpiresAt: expiresAt, + FileCount: len(upload.Files), + TotalSize: humanize.Bytes(uint64(totalSize)), + Strings: defaultStrings(), + } +} + +func (s *Service) collectRecipients(event Event) []string { + recipients := make([]string, 0) + + // Add creator email if NotifyCreator is set + if event.Upload.NotifyCreator && event.User != nil && event.User.Email != "" { + recipients = append(recipients, event.User.Email) + } + + // Add receivers + recipients = append(recipients, event.Upload.Receivers...) + + return recipients +} + +func (s *Service) sendUploadReady(event Event) error { + recipients := s.collectRecipients(event) + if len(recipients) == 0 { + return nil + } + + data := s.buildTemplateData(event.Upload) + + var htmlBuf bytes.Buffer + if err := s.uploadReadyTmpl.Execute(&htmlBuf, data); err != nil { + return fmt.Errorf("failed to render upload_ready template: %w", err) + } + + subject := fmt.Sprintf("[%s] Your upload is ready — %d file(s)", data.ServerName, data.FileCount) + + // Plain-text fallback + text := fmt.Sprintf("Your upload with %d file(s) (%s) is ready for download.\n\nDownload: %s\nExpires: %s\n", + data.FileCount, data.TotalSize, data.DownloadURL, data.ExpiresAt) + + msg := &Message{ + To: recipients, + Subject: subject, + HTML: htmlBuf.String(), + Text: text, + } + + s.logger.Infof("sending upload_ready notification to %v for upload %s", recipients, event.Upload.ID) + return s.provider.Send(msg) +} + +func (s *Service) sendAllDownloaded(event Event) error { + // Only notify the creator for "all downloaded" events + if !event.Upload.NotifyCreator || event.User == nil || event.User.Email == "" { + return nil + } + + recipients := []string{event.User.Email} + data := s.buildTemplateData(event.Upload) + + var htmlBuf bytes.Buffer + if err := s.allDownloadedTmpl.Execute(&htmlBuf, data); err != nil { + return fmt.Errorf("failed to render all_downloaded template: %w", err) + } + + subject := fmt.Sprintf("[%s] All files have been downloaded", data.ServerName) + + text := fmt.Sprintf("All %d file(s) in your upload have been downloaded at least once.\n\nUpload: %s\n", + data.FileCount, data.DownloadURL) + + msg := &Message{ + To: recipients, + Subject: subject, + HTML: htmlBuf.String(), + Text: text, + } + + s.logger.Infof("sending all_downloaded notification to %v for upload %s", recipients, event.Upload.ID) + return s.provider.Send(msg) +} + +// defaultStrings returns the default (English) string map for templates. +// This is structured for future i18n support. +func defaultStrings() map[string]string { + return map[string]string{ + "UploadReady": "Your Upload is Ready", + "UploadReadyDesc": "Your files have been uploaded and are ready for download.", + "AllDownloaded": "All Files Downloaded", + "AllDownloadedDesc": "All files in your upload have been downloaded at least once.", + "Files": "Files", + "FileName": "Name", + "FileSize": "Size", + "TotalSize": "Total Size", + "Expires": "Expires", + "Download": "Download Files", + "ViewUpload": "View Upload", + "PoweredBy": "Powered by", + "FileCount": "File(s)", + } +} + +// dispatchToChannels sends a plain-text summary to all configured nikoksr/notify channels. +func (s *Service) dispatchToChannels(event Event) { + data := s.buildTemplateData(event.Upload) + + var subject, body string + switch event.Type { + case EventUploadReady: + subject = fmt.Sprintf("📦 Upload ready — %d file(s) (%s)", data.FileCount, data.TotalSize) + body = fmt.Sprintf("Download: %s\nExpires: %s", data.DownloadURL, data.ExpiresAt) + for _, f := range event.Upload.Files { + body += fmt.Sprintf("\n • %s (%s)", f.Name, humanize.Bytes(uint64(f.Size))) + } + case EventAllDownloaded: + subject = fmt.Sprintf("✅ All %d file(s) downloaded", data.FileCount) + body = fmt.Sprintf("Upload: %s", data.DownloadURL) + default: + return + } + + if err := s.channels.Send(gocontext.Background(), subject, body); err != nil { + s.logger.Warningf("failed to send channel notification: %s", err) + } +} diff --git a/server/notification/service_test.go b/server/notification/service_test.go new file mode 100644 index 000000000..2bd34ac24 --- /dev/null +++ b/server/notification/service_test.go @@ -0,0 +1,139 @@ +package notification_test + +import ( + "testing" + "time" + + "github.com/root-gg/logger" + "github.com/root-gg/plik/server/common" + "github.com/root-gg/plik/server/notification" + notifTesting "github.com/root-gg/plik/server/notification/testing" + "github.com/stretchr/testify/require" +) + +func TestServiceNotify(t *testing.T) { + config := &common.Configuration{} + config.MaxUploadReceivers = 5 + log := logger.NewLogger() + + provider := notifTesting.NewProvider() + svc, err := notification.NewService(provider, config, log) + require.NoError(t, err) + svc.Start() + defer svc.Stop() + + upload := common.NewUpload() + upload.Receivers = common.Receivers{"test@example.com"} + + file := upload.NewFile() + file.Name = "test.txt" + file.Size = 1024 + file.Status = common.FileUploaded + + svc.Notify(notification.Event{ + Type: notification.EventUploadReady, + Upload: upload, + }) + + // Wait for async processing + time.Sleep(200 * time.Millisecond) + + msgs := provider.GetMessages() + require.Len(t, msgs, 1) + require.Contains(t, msgs[0].To, "test@example.com") + require.Contains(t, msgs[0].Subject, "ready") +} + +func TestServiceNotifyAllDownloaded(t *testing.T) { + config := &common.Configuration{} + log := logger.NewLogger() + + provider := notifTesting.NewProvider() + svc, err := notification.NewService(provider, config, log) + require.NoError(t, err) + svc.Start() + defer svc.Stop() + + upload := common.NewUpload() + upload.NotifyCreator = true + upload.Receivers = common.Receivers{"creator@example.com"} + + file := upload.NewFile() + file.Name = "doc.pdf" + file.Size = 2048 + file.Status = common.FileUploaded + + user := common.NewUser(common.ProviderLocal, "testuser") + user.Email = "creator@example.com" + + svc.Notify(notification.Event{ + Type: notification.EventAllDownloaded, + Upload: upload, + User: user, + }) + + time.Sleep(200 * time.Millisecond) + + msgs := provider.GetMessages() + require.Len(t, msgs, 1) + require.Contains(t, msgs[0].Subject, "downloaded") +} + +func TestServiceNotifyCreatorWithUser(t *testing.T) { + config := &common.Configuration{} + log := logger.NewLogger() + + provider := notifTesting.NewProvider() + svc, err := notification.NewService(provider, config, log) + require.NoError(t, err) + svc.Start() + defer svc.Stop() + + upload := common.NewUpload() + upload.NotifyCreator = true + // No receivers, just notify creator + + file := upload.NewFile() + file.Name = "hello.txt" + file.Size = 512 + file.Status = common.FileUploaded + + user := common.NewUser(common.ProviderLocal, "testuser") + user.Email = "me@example.com" + + svc.Notify(notification.Event{ + Type: notification.EventUploadReady, + Upload: upload, + User: user, + }) + + time.Sleep(200 * time.Millisecond) + + msgs := provider.GetMessages() + require.Len(t, msgs, 1) + require.Contains(t, msgs[0].To, "me@example.com") +} + +func TestServiceNoRecipientsSkips(t *testing.T) { + config := &common.Configuration{} + log := logger.NewLogger() + + provider := notifTesting.NewProvider() + svc, err := notification.NewService(provider, config, log) + require.NoError(t, err) + svc.Start() + defer svc.Stop() + + upload := common.NewUpload() + // No receivers, no notifyCreator, no user + + svc.Notify(notification.Event{ + Type: notification.EventUploadReady, + Upload: upload, + }) + + time.Sleep(200 * time.Millisecond) + + msgs := provider.GetMessages() + require.Len(t, msgs, 0, "should not send any notification when no recipients") +} diff --git a/server/notification/smtp/smtp.go b/server/notification/smtp/smtp.go new file mode 100644 index 000000000..32262ba47 --- /dev/null +++ b/server/notification/smtp/smtp.go @@ -0,0 +1,206 @@ +package smtp + +import ( + "crypto/tls" + "fmt" + "mime" + "mime/quotedprintable" + "net" + "net/smtp" + "strings" + + "github.com/root-gg/plik/server/notification" + "github.com/root-gg/utils" +) + +// Ensure SMTP Provider implements notification.Provider interface +var _ notification.Provider = (*Provider)(nil) + +// Config describes configuration for the SMTP notification provider. +type Config struct { + Host string + Port int + Username string + Password string + From string + TLS bool +} + +// NewConfig instantiates a new default configuration +// and overrides it with configuration passed as argument. +func NewConfig(params map[string]any) (config *Config) { + config = new(Config) + config.Port = 587 + config.TLS = true + utils.Assign(config, params) + return +} + +// Provider sends notifications via SMTP. +type Provider struct { + Config *Config +} + +// NewProvider instantiates a new SMTP notification provider. +func NewProvider(config *Config) *Provider { + return &Provider{Config: config} +} + +// Name returns the provider name. +func (p *Provider) Name() string { + return "smtp" +} + +// Send delivers a notification message via SMTP. +func (p *Provider) Send(msg *notification.Message) error { + if len(msg.To) == 0 { + return nil + } + + addr := net.JoinHostPort(p.Config.Host, fmt.Sprintf("%d", p.Config.Port)) + + // Build RFC 2045 multipart/alternative email + boundary := "plik-boundary-" + fmt.Sprintf("%d", len(msg.HTML)+len(msg.Text)) + headers := make([]string, 0, 8) + headers = append(headers, fmt.Sprintf("From: %s", p.Config.From)) + headers = append(headers, fmt.Sprintf("To: %s", strings.Join(msg.To, ", "))) + headers = append(headers, fmt.Sprintf("Subject: %s", mime.QEncoding.Encode("utf-8", msg.Subject))) + headers = append(headers, "MIME-Version: 1.0") + headers = append(headers, fmt.Sprintf("Content-Type: multipart/alternative; boundary=%q", boundary)) + headers = append(headers, "") + + var body strings.Builder + body.WriteString(strings.Join(headers, "\r\n")) + body.WriteString("\r\n") + + // Plain-text part (quoted-printable encoded) + if msg.Text != "" { + body.WriteString("--" + boundary + "\r\n") + body.WriteString("Content-Type: text/plain; charset=utf-8\r\n") + body.WriteString("Content-Transfer-Encoding: quoted-printable\r\n\r\n") + qpWriter := quotedprintable.NewWriter(&body) + qpWriter.Write([]byte(msg.Text)) + qpWriter.Close() + body.WriteString("\r\n") + } + + // HTML part (quoted-printable encoded) + if msg.HTML != "" { + body.WriteString("--" + boundary + "\r\n") + body.WriteString("Content-Type: text/html; charset=utf-8\r\n") + body.WriteString("Content-Transfer-Encoding: quoted-printable\r\n\r\n") + qpWriter := quotedprintable.NewWriter(&body) + qpWriter.Write([]byte(msg.HTML)) + qpWriter.Close() + body.WriteString("\r\n") + } + + body.WriteString("--" + boundary + "--\r\n") + + var auth smtp.Auth + if p.Config.Username != "" { + auth = smtp.PlainAuth("", p.Config.Username, p.Config.Password, p.Config.Host) + } + + if p.Config.TLS { + return p.sendTLS(addr, auth, body.String(), msg.To) + } + + return p.sendPlain(addr, auth, body.String(), msg.To) +} + +// sendPlain sends email over a plain (non-TLS) connection. +// Unlike smtp.SendMail, this does NOT attempt STARTTLS, which avoids +// certificate validation errors with local SMTP servers. +func (p *Provider) sendPlain(addr string, auth smtp.Auth, body string, to []string) error { + conn, err := net.Dial("tcp", addr) + if err != nil { + return fmt.Errorf("dial to %s failed: %w", addr, err) + } + + client, err := smtp.NewClient(conn, p.Config.Host) + if err != nil { + return fmt.Errorf("SMTP client creation failed: %w", err) + } + defer client.Close() + + if auth != nil { + if err = client.Auth(auth); err != nil { + return fmt.Errorf("SMTP auth failed: %w", err) + } + } + + if err = client.Mail(p.Config.From); err != nil { + return fmt.Errorf("SMTP MAIL FROM failed: %w", err) + } + + for _, recipient := range to { + if err = client.Rcpt(recipient); err != nil { + return fmt.Errorf("SMTP RCPT TO <%s> failed: %w", recipient, err) + } + } + + w, err := client.Data() + if err != nil { + return fmt.Errorf("SMTP DATA failed: %w", err) + } + + _, err = w.Write([]byte(body)) + if err != nil { + return fmt.Errorf("SMTP write failed: %w", err) + } + + if err = w.Close(); err != nil { + return fmt.Errorf("SMTP close data failed: %w", err) + } + + return client.Quit() +} + +// sendTLS sends email over an explicit TLS connection (STARTTLS or direct TLS). +func (p *Provider) sendTLS(addr string, auth smtp.Auth, body string, to []string) error { + tlsConfig := &tls.Config{ServerName: p.Config.Host} + + conn, err := tls.Dial("tcp", addr, tlsConfig) + if err != nil { + return fmt.Errorf("TLS dial to %s failed: %w", addr, err) + } + + client, err := smtp.NewClient(conn, p.Config.Host) + if err != nil { + return fmt.Errorf("SMTP client creation failed: %w", err) + } + defer client.Close() + + if auth != nil { + if err = client.Auth(auth); err != nil { + return fmt.Errorf("SMTP auth failed: %w", err) + } + } + + if err = client.Mail(p.Config.From); err != nil { + return fmt.Errorf("SMTP MAIL FROM failed: %w", err) + } + + for _, recipient := range to { + if err = client.Rcpt(recipient); err != nil { + return fmt.Errorf("SMTP RCPT TO <%s> failed: %w", recipient, err) + } + } + + w, err := client.Data() + if err != nil { + return fmt.Errorf("SMTP DATA failed: %w", err) + } + + _, err = w.Write([]byte(body)) + if err != nil { + return fmt.Errorf("SMTP write failed: %w", err) + } + + if err = w.Close(); err != nil { + return fmt.Errorf("SMTP close data failed: %w", err) + } + + return client.Quit() +} diff --git a/server/notification/templates/all_downloaded.html b/server/notification/templates/all_downloaded.html new file mode 100644 index 000000000..0b73885e5 --- /dev/null +++ b/server/notification/templates/all_downloaded.html @@ -0,0 +1,134 @@ + + + + + + + {{.Strings.AllDownloaded}} + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+

+ {{.Strings.AllDownloaded}}

+

{{.Strings.AllDownloadedDesc}}

+
+ + + + +
+ + + + + + + + + +
+ {{.Strings.FileCount}} + {{.Strings.TotalSize}}
{{.FileCount}} + + {{.TotalSize}}
+
+
+ + + + + {{range .Upload.Files}} + + + + {{end}} +
+ + + + + +
+ {{.Strings.FileName}} + {{.Strings.FileSize}}
+
+ + + + + +
+ {{.Name}} + + {{humanizeBytes .Size}}
+
+
+ + {{.Strings.ViewUpload}} + +
+ + + + + + + +
+

+ {{.Strings.PoweredBy}} Plik +

+
+ +
+ + + \ No newline at end of file diff --git a/server/notification/templates/upload_ready.html b/server/notification/templates/upload_ready.html new file mode 100644 index 000000000..8cfd6ff77 --- /dev/null +++ b/server/notification/templates/upload_ready.html @@ -0,0 +1,112 @@ + + + + + +{{.Strings.UploadReady}} + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+

{{.Strings.UploadReady}}

+

{{.Strings.UploadReadyDesc}}

+
+ + + + +
+ + + + + + + + + +
{{.Strings.FileCount}}{{.Strings.Expires}}
{{.FileCount}}{{.ExpiresAt}}
+
+
+ + + + + {{range .Upload.Files}} + + + + {{end}} + + + + +
+ + + + + +
{{.Strings.FileName}}{{.Strings.FileSize}}
+
+ + + + + +
{{.Name}}{{humanizeBytes .Size}}
+
+ + + + + +
{{.Strings.TotalSize}}{{.TotalSize}}
+
+
+ + {{.Strings.Download}} + +
+ + + + + + + +
+

+ {{.Strings.PoweredBy}} Plik +

+
+ +
+ + diff --git a/server/notification/testing/testing.go b/server/notification/testing/testing.go new file mode 100644 index 000000000..73cd84bfd --- /dev/null +++ b/server/notification/testing/testing.go @@ -0,0 +1,65 @@ +package testing + +import ( + "sync" + + "github.com/root-gg/plik/server/notification" +) + +// Ensure Testing Provider implements notification.Provider interface +var _ notification.Provider = (*Provider)(nil) + +// Provider records notifications in memory for testing. +type Provider struct { + Messages []*notification.Message + err error + mu sync.Mutex +} + +// NewProvider instantiates a new Testing notification provider. +func NewProvider() *Provider { + return &Provider{} +} + +// Name returns the provider name. +func (p *Provider) Name() string { + return "testing" +} + +// Send records the notification message. +func (p *Provider) Send(msg *notification.Message) error { + p.mu.Lock() + defer p.mu.Unlock() + + if p.err != nil { + return p.err + } + + p.Messages = append(p.Messages, msg) + return nil +} + +// GetMessages returns all recorded messages. +func (p *Provider) GetMessages() []*notification.Message { + p.mu.Lock() + defer p.mu.Unlock() + + return p.Messages +} + +// SetError sets the error that this provider will return on any subsequent Send call. +func (p *Provider) SetError(err error) { + p.mu.Lock() + defer p.mu.Unlock() + + p.err = err +} + +// Reset clears all recorded messages and errors. +func (p *Provider) Reset() { + p.mu.Lock() + defer p.mu.Unlock() + + p.Messages = nil + p.err = nil +} diff --git a/server/notification/testing/testing_test.go b/server/notification/testing/testing_test.go new file mode 100644 index 000000000..eb9e5b108 --- /dev/null +++ b/server/notification/testing/testing_test.go @@ -0,0 +1,61 @@ +package testing + +import ( + "testing" + + "github.com/root-gg/plik/server/notification" + "github.com/stretchr/testify/require" +) + +func TestTestingProvider_Name(t *testing.T) { + p := NewProvider() + require.Equal(t, "testing", p.Name()) +} + +func TestTestingProvider_Send(t *testing.T) { + p := NewProvider() + + msg := ¬ification.Message{ + To: []string{"test@example.com"}, + Subject: "Test", + HTML: "

Hello

", + } + + err := p.Send(msg) + require.NoError(t, err) + + msgs := p.GetMessages() + require.Len(t, msgs, 1) + require.Equal(t, "test@example.com", msgs[0].To[0]) + require.Equal(t, "Test", msgs[0].Subject) +} + +func TestTestingProvider_MultipleMessages(t *testing.T) { + p := NewProvider() + + for i := 0; i < 3; i++ { + err := p.Send(¬ification.Message{ + To: []string{"test@example.com"}, + Subject: "Test", + }) + require.NoError(t, err) + } + + msgs := p.GetMessages() + require.Len(t, msgs, 3) +} + +func TestTestingProvider_Reset(t *testing.T) { + p := NewProvider() + + err := p.Send(¬ification.Message{ + To: []string{"test@example.com"}, + Subject: "Test", + }) + require.NoError(t, err) + + require.Len(t, p.GetMessages(), 1) + + p.Reset() + require.Len(t, p.GetMessages(), 0) +} diff --git a/server/plikd.cfg b/server/plikd.cfg index 01b4994fe..409dc81f5 100644 --- a/server/plikd.cfg +++ b/server/plikd.cfg @@ -31,6 +31,7 @@ UploadWhitelist = [] # Restrict upload and user creation to on MaxFileSizeStr = "10GB" # 10GB (or "unlimited") MaxUserSizeStr = "unlimited" # Default max uploaded size per user unless configured otherwise (or "unlimited") MaxFilePerUpload = 1000 +MaxUploadReceivers = 5 # Max number of email addresses that can receive notifications per upload (0 = unlimited) DefaultTTLStr = "30d" # 30 days MaxTTLStr = "30d" # 0 : No limit @@ -54,6 +55,7 @@ FeatureClients = "enabled" # Display the clients download button in FeatureGithub = "enabled" # Display the source code link in the web UI FeatureText = "enabled" # Upload text dialog FeatureE2EE = "enabled" # End-to-end encryption (age) +FeatureNotification = "enabled" # Email notifications on upload/download events GoogleApiClientID = "" # Google api client ID GoogleApiSecret = "" # Google api client secret @@ -129,3 +131,47 @@ DataBackend = "file" Driver = "sqlite3" ConnectionString = "plik.db" Debug = false # Log SQL requests + + + +# Notification backend configuration +# +NotificationBackend = "smtp" # smtp | log +[NotificationBackendConfig] + Host = "127.0.0.1" + Port = 25 + Username = "" + Password = "" + From = "plik@plik.root.gg" + TLS = false + +# Additional notification channels (plain text push notifications) +# Each [[NotificationChannels]] block adds a channel. +# Supported types: slack, telegram, discord, msteams, http +# +[[NotificationChannels]] + Type = "slack" + [NotificationChannels.Config] + Token = "" + Channel = "#general" +# +# [[NotificationChannels]] +# Type = "telegram" +# [NotificationChannels.Config] +# Token = "bot123:ABC..." +# ChatID = -123456789 +# +# [[NotificationChannels]] +# Type = "discord" +# [NotificationChannels.Config] +# ChannelID = "123456789012345678" +# +# [[NotificationChannels]] +# Type = "msteams" +# [NotificationChannels.Config] +# Webhook = "https://outlook.office.com/webhook/..." +# +# [[NotificationChannels]] +# Type = "http" +# [NotificationChannels.Config] +# URL = "https://example.com/webhook" \ No newline at end of file diff --git a/server/server/server.go b/server/server/server.go index 52ab0162c..8958fe37f 100644 --- a/server/server/server.go +++ b/server/server/server.go @@ -29,6 +29,16 @@ import ( "github.com/root-gg/plik/server/handlers" "github.com/root-gg/plik/server/metadata" "github.com/root-gg/plik/server/middleware" + "github.com/root-gg/plik/server/notification" + notification_log "github.com/root-gg/plik/server/notification/log" + notification_smtp "github.com/root-gg/plik/server/notification/smtp" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/discord" + notifyhttp "github.com/nikoksr/notify/service/http" + "github.com/nikoksr/notify/service/msteams" + "github.com/nikoksr/notify/service/slack" + "github.com/nikoksr/notify/service/telegram" ) // PlikServer is a Plik Server instance @@ -39,7 +49,8 @@ type PlikServer struct { dataBackend data.Backend streamBackend data.Backend - authenticator *common.SessionAuthenticator + authenticator *common.SessionAuthenticator + notificationService *notification.Service httpServer *http.Server httpListener net.Listener @@ -200,6 +211,11 @@ func (ps *PlikServer) start() (err error) { } } + err = ps.initializeNotificationService() + if err != nil { + return fmt.Errorf("unable to initialize notification service : %s", err) + } + if ps.config.IsAutoClean() { go ps.uploadsCleaningRoutine() } @@ -332,6 +348,10 @@ func (ps *PlikServer) shutdown(timeout time.Duration) (err error) { } } + if ps.notificationService != nil { + ps.notificationService.Stop() + } + return nil } @@ -596,4 +616,139 @@ func (ps *PlikServer) setupContext(ctx *context.Context) { ctx.SetStreamBackend(ps.streamBackend) ctx.SetAuthenticator(ps.authenticator) ctx.SetMetrics(ps.metrics) + ctx.SetNotificationService(ps.notificationService) +} + +// initializeNotificationService initializes the notification provider and service +func (ps *PlikServer) initializeNotificationService() error { + if ps.config.FeatureNotification == common.FeatureDisabled { + return nil + } + + log := ps.config.NewLogger() + + var provider notification.Provider + switch ps.config.NotificationBackend { + case "smtp": + config := notification_smtp.NewConfig(ps.config.NotificationBackendConfig) + if config.Host == "" || config.From == "" { + return fmt.Errorf("SMTP notification backend requires Host and From to be configured") + } + provider = notification_smtp.NewProvider(config) + case "log": + provider = notification_log.NewProvider(log) + case "": + // Default to log when no backend is specified but feature is enabled + log.Warningf("notification feature is enabled but no backend is configured, defaulting to log backend") + provider = notification_log.NewProvider(log) + default: + return fmt.Errorf("invalid notification backend: %s", ps.config.NotificationBackend) + } + + service, err := notification.NewService(provider, ps.config, log) + if err != nil { + return err + } + + ps.notificationService = service + ps.notificationService.Start() + + log.Infof("Notification service started with %s backend", provider.Name()) + + // Initialize notification channels (nikoksr/notify) + if len(ps.config.NotificationChannels) > 0 { + channels, err := ps.initializeNotificationChannels(log) + if err != nil { + return err + } + if channels != nil { + ps.notificationService.SetChannels(channels) + } + } + + return nil +} + +// initializeNotificationChannels creates nikoksr/notify services from config +func (ps *PlikServer) initializeNotificationChannels(log *logger.Logger) (*notify.Notify, error) { + n := notify.New() + count := 0 + + for _, ch := range ps.config.NotificationChannels { + switch ch.Type { + case "slack": + token, _ := ch.Config["Token"].(string) + channel, _ := ch.Config["Channel"].(string) + if token == "" || channel == "" { + return nil, fmt.Errorf("slack channel requires Token and Channel") + } + svc := slack.New(token) + svc.AddReceivers(channel) + n.UseServices(svc) + log.Infof("Notification channel added: slack -> %s", channel) + count++ + + case "telegram": + token, _ := ch.Config["Token"].(string) + if token == "" { + return nil, fmt.Errorf("telegram channel requires Token") + } + svc, err := telegram.New(token) + if err != nil { + return nil, fmt.Errorf("failed to create telegram service: %w", err) + } + // ChatID can be int64 or float64 (from JSON/TOML) + if chatID, ok := ch.Config["ChatID"].(int64); ok { + svc.AddReceivers(chatID) + } else if chatIDFloat, ok := ch.Config["ChatID"].(float64); ok { + svc.AddReceivers(int64(chatIDFloat)) + } + n.UseServices(svc) + log.Infof("Notification channel added: telegram") + count++ + + case "discord": + svc := discord.New() + if channelID, ok := ch.Config["ChannelID"].(string); ok && channelID != "" { + svc.AddReceivers(channelID) + } else { + return nil, fmt.Errorf("discord channel requires ChannelID") + } + n.UseServices(svc) + log.Infof("Notification channel added: discord") + count++ + + case "msteams": + svc := msteams.New() + if webhook, ok := ch.Config["Webhook"].(string); ok && webhook != "" { + svc.AddReceivers(webhook) + } else { + return nil, fmt.Errorf("msteams channel requires Webhook") + } + n.UseServices(svc) + log.Infof("Notification channel added: msteams") + count++ + + case "http": + svc := notifyhttp.New() + if url, ok := ch.Config["URL"].(string); ok && url != "" { + svc.AddReceiversURLs(url) + } else { + return nil, fmt.Errorf("http channel requires URL") + } + n.UseServices(svc) + log.Infof("Notification channel added: http -> %s", ch.Config["URL"]) + count++ + + default: + return nil, fmt.Errorf("unsupported notification channel type: %s", ch.Type) + } + } + + if count == 0 { + return nil, nil + } + + log.Infof("%d notification channel(s) configured", count) + return n, nil } diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/.gitignore b/vendor/github.com/atc0005/go-teams-notify/v2/.gitignore new file mode 100644 index 000000000..f30634847 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/.gitignore @@ -0,0 +1,30 @@ +# Copyright 2020 Enrico Hoffmann +# Copyright 2021 Adam Chalkley +# +# https://github.com/atc0005/go-teams-notify +# +# Licensed under the MIT License. See LICENSE file in the project root for +# full license information. + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# refs GH-6, GH-15 +# Allow vendored files to be included in this repo +#vendor + +# Ignore local scratch directory +/scratch + +# Ignore local Visual Studio Code settings +/.vscode diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/.golangci.yml b/vendor/github.com/atc0005/go-teams-notify/v2/.golangci.yml new file mode 100644 index 000000000..4bc9eaf77 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/.golangci.yml @@ -0,0 +1,82 @@ +# Copyright 2020 Enrico Hoffmann +# Copyright 2021 Adam Chalkley +# +# https://github.com/atc0005/go-teams-notify +# +# Licensed under the MIT License. See LICENSE file in the project root for +# full license information. + +linters: + enable: + - dogsled + - dupl + - gocognit + - goconst + - gocritic + - gocyclo + - gofmt + - revive + - gosec + - nakedret + - prealloc + - exportloopref + - unconvert + - unparam + - whitespace + +linters-settings: + funlen: + lines: 60 + statements: 40 + + gocognit: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 10 + + gocyclo: + # minimal code complexity to report, 30 by default (but we recommend 10-20) + min-complexity: 15 + + nakedret: + # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 + max-func-lines: 2 + + unparam: + # Inspect exported functions, default is false. Set to true if no external program/library imports your code. + # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: + # if it's called for subdir of a project it can't find external interfaces. All text editor integrations + # with golangci-lint call it on a directory with the changed file. + check-exported: true + + unused: + # treat code as a program (not a library) and report unused exported identifiers; default is false. + # XXX: if you enable this setting, unused will report a lot of false-positives in text editors: + # if it's called for subdir of a project it can't find funcs usages. All text editor integrations + # with golangci-lint call it on a directory with the changed file. + check-exported: false + + whitespace: + # Enforces newlines (or comments) after every multi-line if statement + multi-if: true + # Enforces newlines (or comments) after every multi-line function signature + multi-func: true + +issues: + # Not using default exclusions because we want to require comments on public + # functions and types. + exclude-use-default: false + +# options for analysis running +run: + # include test files or not, default is true + tests: false + + # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + modules-download-mode: vendor diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/.markdownlint.yml b/vendor/github.com/atc0005/go-teams-notify/v2/.markdownlint.yml new file mode 100644 index 000000000..cc002da80 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/.markdownlint.yml @@ -0,0 +1,22 @@ +# Copyright 2021 Adam Chalkley +# +# https://github.com/atc0005/go-teams-notify +# +# Licensed under the MIT License. See LICENSE file in the project root for +# full license information. + +# https://github.com/igorshubovych/markdownlint-cli#configuration +# https://github.com/DavidAnson/markdownlint#optionsconfig + +# Setting the special default rule to true or false includes/excludes all +# rules by default. +"default": true + +# We know that line lengths will be long in the main README file, so don't +# report those cases. +"MD013": false + +# Don't complain if sub-heading names are duplicated since this is a common +# practice in CHANGELOG.md (e.g., "Fixed"). +"MD024": + "siblings_only": true diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/CHANGELOG.md b/vendor/github.com/atc0005/go-teams-notify/v2/CHANGELOG.md new file mode 100644 index 000000000..824363255 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/CHANGELOG.md @@ -0,0 +1,599 @@ +# Changelog + +## Overview + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a +Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +Please [open an issue](https://github.com/atc0005/go-teams-notify/issues) for any +deviations that you spot; I'm still learning!. + +## Types of changes + +The following types of changes will be recorded in this file: + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +## [Unreleased] + +- placeholder + +## [v2.14.0] - 2025-11-16 + +### Changed + +- (GH-302) Go Dependency: Bump github.com/stretchr/testify from 1.9.0 to 1.10.0 + +### Fixed + +- (GH-311) fix: adjust WorkflowURLBaseDomain for both new and old urls + - credit: [@calindima](https://github.com/calindima) + +## [v2.13.0] - 2024-09-08 + +### Added + +- (GH-293) Add MSTeams CodeBlock element + - credit: [@MichaelUrman](https://github.com/MichaelUrman) +- (GH-298) Update documentation for CodeBlock element + +## [v2.12.0] - 2024-08-16 + +### Added + +- (GH-291) Expose `TeamsMessage` interface to support mocking + +## [v2.11.0] - 2024-08-02 + +### Added + +- (GH-275) Add initial support for Workflow connectors + +### Changed + +#### Dependency Updates + +- (GH-259) Go Dependency: Bump github.com/stretchr/testify from 1.8.4 to 1.9.0 + +#### Other + +- (GH-272) Documentation refresh for O365 & Workflow connectors + +### Fixed + +- (GH-261) Remove inactive maligned linter +- (GH-274) Fix validation for `Action.Type` field +- (GH-283) Update CodeQL workflow to run on dev branch PRs + +## [v2.10.0] - 2024-02-22 + +### Added + +- (GH-255) Add `IsSublte` and `HorizontalAlignment` to `Element` + - credit: [@codello](https://github.com/codello) + +### Changed + +#### Dependency Updates + +- (GH-256) Update Dependabot PR prefixes + +## [v2.9.0] - 2024-01-25 + +### Added + +- (GH-241) Add proxy server examples +- (GH-251) Initial support for toggling visibility + +### Changed + +#### Dependency Updates + +- (GH-238) ghaw: bump actions/checkout from 3 to 4 +- (GH-248) ghaw: bump github/codeql-action from 2 to 3 +- (GH-236) Update Dependabot config to monitor both branches + +#### Other + +- (GH-244) Update Go Doc comment formatting + +## [v2.8.0] - 2023-07-21 + +### Added + +- `Adaptive Card` format + - (GH-205) Ability to create a Table in AdaptiveCard +- CI + - (GH-232) Add initial automated release notes config + - (GH-233) Add initial automated release build workflow + +### Changed + +- Dependencies + - `stretchr/testify` + - `v1.8.2` to `v1.8.4` +- CI + - (GH-226) Add `quick` Makefile recipe (alias) + - (GH-225) Update vuln analysis GHAW to remove on.push hook + - (GH-230) Disable unsupported build opts in monthly workflow + +### Fixed + +- CI + - (GH-229) Restore local CodeQL workflow + +## [v2.7.1] - 2023-06-09 + +### Changed + +- Dependencies + - `github.com/stretchr/testify` + - `v1.8.1` to `v1.8.2` +- CI + - (GH-198) Add Go Module Validation, Dependency Updates jobs + - (GH-200) Drop `Push Validation` workflow + - (GH-201) Rework workflow scheduling + - (GH-203) Remove `Push Validation` workflow status badge + - (GH-207) Update vuln analysis GHAW to use on.push hook +- `Adaptive Card` format + - (GH-206) Update `AdaptiveCardMaxVersion` to 1.5 + - (GH-216) Refactor `TopLevelCard.Validate` +- Other + - (GH-212) Update `InList`, `InListIfFieldValNotEmpty` validators + +### Fixed + +- (GH-208) Validation of `(adaptivecard.Attachment).Content` is missing + +## [v2.7.0] - 2022-12-12 + +### Added + +- (GH-134) Allow setting user agent, fallback to project-specific default + value +- (GH-135) Allow overriding default `http.Client` +- (GH-157) Add `Adaptive Card` message format support + - see also discussion from GH-127, including feedback from + [@ghokun](https://github.com/ghokun) +- (GH-169) Added YAML en(de)coding support to `MessageCard` + - credit: [@pcanilho](https://github.com/pcanilho) + +### Changed + +- Dependencies + - `github.com/stretchr/testify` + - `v1.7.0` to `v1.8.1` +- (GH-154) Deprecate API interface, expose underlying "Teams" client +- (GH-183) Update Makefile and GitHub Actions Workflows +- (GH-190) Refactor GitHub Actions workflows to import logic + +### Fixed + +- (GH-166) Update `lintinstall` Makefile recipe +- (GH-184) Apply Go 1.19 specific doc comments linting fixes +- (GH-176) `./send_test.go:238:8: second argument to errors.As should not be + *error` +- (GH-179) Wrong json key name for URL (uses uri instead) + - credit: [@janfonas](https://github.com/janfonas) + +## [v2.6.1] - 2022-02-25 + +### Changed + +- Dependencies + - `actions/setup-node` + - `v2.2.0` to `v3` + +- Linting + - (GH-131) Expand linting GitHub Actions Workflow to include `oldstable`, + `unstable` container images + - (GH-132) Switch Docker image source from Docker Hub to GitHub Container + Registry (GHCR) + +### Fixed + +- (GH-137) Missing doc comment for + `teamsClient.AddWebhookURLValidationPatterns()` +- (GH-138) Missing doc comment for `teamsClient.ValidateWebhook()` +- (GH-141) send.go:306:15: nilness: tautological condition: non-nil != nil + (govet) +- (GH-144) Incorrect field referenced in error message for + `MessageCardSection.AddFact()` + +## [v2.6.0] - 2021-07-09 + +### Added + +- Features + - Add support for PotentialActions (aka, "Actions") + - credit: [@nmaupu](https://github.com/nmaupu) + +- Documentation + - Add separate `examples` directory containing standalone example code for + most common use cases + +### Changed + +- Dependencies + - `actions/setup-node` + - `v2.1.5` to `v2.2.0` + - update `node-version` value to always use latest LTS version instead of + hard-coded version + +- Linting + - replace `golint`, `scopelint` linters, cleanup config + - note: this specifically applies to linting performed via Makefile + recipe, not (at present) the bulk of the CI linting checks + +- Documentation + - move examples from README to separate `examples` directory + - Remove example from doc.go file, direct reader to main README + - Update project status + - remove history as it is likely no longer relevant (original + project is discontinued at this point) + - remove future (for the same reason) + - Add explicit "Supported Releases" section to help make clear that + the v1 series is no longer maintained + - Remove explicit "used by" details, rely on dynamic listing provided + by pkg.go.dev instead + - Minor polish + +## [v2.5.0] - 2021-04-08 + +### Added + +- Features + - Validation of webhook URLs using custom validation patterns + - credit: [@nmaupu](https://github.com/nmaupu) + - Validation of `MessageCard` type using a custom validation function (to + override default validation behavior) + - credit: [@nmaupu](https://github.com/nmaupu) + +- Documentation + - Add list of projects using this library + - Update features list to include functionality added to this fork + - Configurable validation of webhook URLs + - Configurable validation of `MessageCard` type + - Configurable timeouts + - Configurable retry support + +### Changed + +- Dependencies + - `actions/setup-node` + - `v2.1.4` to `v2.1.5` + +### Fixed + +- Documentation + - Misc typos + - Grammatical tweaks + - Attempt to clarify project status + - i.e., not mothballed, just slow cadence + +## [v2.4.2] - 2021-01-28 + +### Changed + +- Apply regex pattern match for webhook URL validation instead of fixed + strings in order to support matching private org webhook URL subdomains + +### Fixed + +- Updating an exiting webhook connector in Microsoft Teams switches the URL to + unsupported `https://*.webhook.office.com/webhookb2/` format +- `SendWithRetry` method does not honor setting to disable webhook URL prefix + validation +- Support for disabling webhook URL validation limited to just disabling + validation of prefixes + +## [v2.4.1] - 2021-01-28 + +### Changed + +- (GH-59) Webhook URL API endpoint response validation now requires a `1` text + string as the response body + +### Fixed + +- (GH-59) Microsoft Teams Webhook Connector "200 OK" status insufficient + indication of success + +## [v2.4.0] - 2021-01-28 + +### Added + +- Add (optional) support for disabling webhook URL prefix validation + - credit: [@odise](https://github.com/odise) + +### Changed + +- Documentation + - Refresh "basic" example + - Add example for disabling webhook URL prefix validation + - Update "about this project" coverage + - Swap GoDoc badge for pkg.go.dev badge + +- Tests + - Extend test coverage + - Verbose test output by default (Makefile, GitHub Actions Workflow) + +- Dependencies + - `actions/setup-node` + - `v2.1.1` to `v2.1.4` + - `actions/checkout` + - `v2.3.2` to `v2.3.4` + - `stretchr/testify` + - `v1.6.1` to `v1.7.0` + +### Fixed + +- minor linting error for commented code +- Tests fail to assert that any errors which occur are expected, only the + types + +## [v2.3.0] - 2020-08-29 + +### Added + +- Add package-level logging for formatting functions + - as with other package-level logging, this is disabled by default + +- API + - add `SendWithRetry` method based on the `teams.SendMessage` function from + the `atc0005/send2teams` project + - actively working to move relevant content from that project to this one + +### Fixed + +- YYYY-MM-DD date formatting of changelog version entries + +## [v2.2.0] - 2020-08-28 + +### Added + +- Add package-level logger +- Extend API to allow request cancellation via context +- Add formatting functions useful for text conversion + - Convert Windows/Mac/Linux EOL to Markdown break statements + - used to provide equivalent Teams-compatible formatting + - Format text as code snippet + - this inserts leading and trailing ` character to provide Markdown string + formatting + - Format text as code block + - this inserts three leading and trailing ` characters to provide Markdown + code block formatting + - *`Try`* variants of code formatting functions + - return formatted string if no errors, otherwise return the original + string + +### Changed + +- Expose API response strings containing potential error messages +- README + - Explicitly note that this fork is now standalone until such time that the + upstream project resumes development/maintenance efforts + +### Fixed + +- CHANGELOG section link in previous release +- Invalid `RoundTripper` implementation used in `TestTeamsClientSend` test + function + - see `GH-46` and `GH-47`; thank you `@davecheney` for the fix! + +## [v2.1.1] - 2020-08-25 + +### Added + +- README + - Add badges for GitHub Actions Workflows + - Add release badge for latest project release +- Add CHANGELOG file +- Add GoDoc package-level documentation +- Extend webhook validation error handling +- Add Docker-based GitHub Actions Workflows +- Enable Dependabot updates +- Add Markdownlint config file + +### Changed + +- README + - Replace badge for latest tag with latest release + - Update GoDoc badge to reference this fork + - Update license badge to reference this fork + - Add new sections common to other projects that I maintain + - table of contents + - overview + - changelog + - references + - features +- Vendor dependencies +- Update license to add @atc0005 (new) in addition to @dasrick (existing) +- Update go.mod to replace upstream with this fork +- Rename golangci-lint config file to match officially supported name +- Remove files no longer used by this fork + - Travis CI configuration + - editorconfig file (and settings) +- Add license header to source files + - combined copyright statement for existing files + - single copyright statement for new files + +### Fixed + +- Add missing Facts assignment in MessageCardSection +- scopelint: Fix improper range loop var reference +- Fix misc linting issues with README +- Test failure from previous upstream pull request submissions + - `Object expected to be of type *url.Error, but was *errors.errorString` +- Misc linting issues with primary and test files + +## [v2.1.0] - 2020-04-08 + +### Added + +- `MessageCard` type includes additional fields + - `Type` and `Context` fields provide required JSON payload + fields + - preset to required static values via updated + `NewMessageCard()` constructor + - `Summary` + - required if `Text` field is not set, optional otherwise + - `Sections` slice + - `MessageCardSection` type + +- Additional nested types + - `MessageCardSection` + - `MessageCardSectionFact` + - `MessageCardSectionImage` + +- Additional methods for `MessageCard` and nested types + - `MessageCard.AddSection()` + - `MessageCardSection.AddFact()` + - `MessageCardSection.AddFactFromKeyValue()` + - `MessageCardSection.AddImage()` + - `MessageCardSection.AddHeroImageStr()` + - `MessageCardSection.AddHeroImage()` + +- Additional factory functions + - `NewMessageCardSection()` + - `NewMessageCardSectionFact()` + - `NewMessageCardSectionImage()` + +- `IsValidMessageCard()` added to check for minimum required + field values. + - This function has the potential to be extended + later with additional validation steps. + +- Wrapper `IsValidInput()` added to handle all validation + needs from one location. + - the intent was to both solve a CI error and provide + a location to easily extend validation checks in + the future (if needed) + +### Changed + +- `MessageCard` type includes additional fields +- `NewMessageCard` factory function sets fields needed for + required JSON payload fields + - `Type` + - `Context` + +- `teamsClient.Send()` method updated to apply `MessageCard` struct + validation alongside existing webhook URL validation + +- `isValidWebhookURL()` exported as `IsValidWebhookURL()` so that client + code can use the validation functionality instead of repeating the + code + - e.g., flag value validation for "fail early" behavior + +### Known Issues + +- No support in this set of changes for `potentialAction` types + - `ViewAction` + - `OpenUri` + - `HttpPOST` + - `ActionCard` + - `InvokeAddInCommand` + - Outlook specific based on what I read; likely not included + in a future release due to non-Teams specific usage + +## [v2.0.0] - 2020-03-29 + +### Breaking + +- `NewClient()` will NOT return multiple values +- remove provided mock + +### Changed + +- switch dependency/package management tool to from `dep` to `go mod` +- switch from `golint` to `golangci-lint` +- add more golang versions to pass via travis-ci + +## [v1.3.1] - 2020-03-29 + +### Fixed + +- fix redundant error logging +- fix redundant comment + +## [v1.3.0] - 2020-03-26 + +### Changed + +- feature: allow multiple valid webhook URL FQDNs (thx @atc0005) + +## [v1.2.0] - 2019-11-08 + +### Added + +- add mock + +### Changed + +- update deps +- `gosimple` (shorten two conditions) + +## [v1.1.1] - 2019-05-02 + +### Changed + +- rename client interface into API +- update deps + +### Fixed + +- fix typo in README + +## [v1.1.0] - 2019-04-30 + +### Added + +- add missing tests +- append documentation + +### Changed + +- add/change to client/interface + +## [v1.0.0] - 2019-04-29 + +### Added + +- add initial functionality of sending messages to MS Teams channel + +[Unreleased]: https://github.com/atc0005/go-teams-notify/compare/v2.14.0...HEAD +[v2.14.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.14.0 +[v2.13.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.13.0 +[v2.12.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.12.0 +[v2.11.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.11.0 +[v2.10.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.10.0 +[v2.9.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.9.0 +[v2.8.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.8.0 +[v2.7.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.7.1 +[v2.7.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.7.0 +[v2.6.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.6.1 +[v2.6.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.6.0 +[v2.5.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.5.0 +[v2.4.2]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.4.2 +[v2.4.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.4.1 +[v2.4.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.4.0 +[v2.3.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.3.0 +[v2.2.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.2.0 +[v2.1.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.1.1 +[v2.1.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.1.0 +[v2.0.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v2.0.0 +[v1.3.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.3.1 +[v1.3.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.3.0 +[v1.2.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.2.0 +[v1.1.1]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.1.1 +[v1.1.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.1.0 +[v1.0.0]: https://github.com/atc0005/go-teams-notify/releases/tag/v1.0.0 diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/LICENSE b/vendor/github.com/atc0005/go-teams-notify/v2/LICENSE new file mode 100644 index 000000000..4d6d7cc72 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2020 Enrico Hoffmann +Copyright (c) 2020-Present Adam Chalkley + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/Makefile b/vendor/github.com/atc0005/go-teams-notify/v2/Makefile new file mode 100644 index 000000000..66e5d3f19 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/Makefile @@ -0,0 +1,116 @@ +# Copyright 2020 Enrico Hoffmann +# Copyright 2021 Adam Chalkley +# +# https://github.com/atc0005/go-teams-notify +# +# Licensed under the MIT License. See LICENSE file in the project root for +# full license information. + +# REFERENCES +# +# https://github.com/golangci/golangci-lint#install +# https://github.com/golangci/golangci-lint/releases/latest + +SHELL = /bin/bash + +BUILDCMD = go build -mod=vendor ./... +GOCLEANCMD = go clean -mod=vendor ./... +GITCLEANCMD = git clean -xfd +CHECKSUMCMD = sha256sum -b + +.DEFAULT_GOAL := help + + ########################################################################## + # Targets will not work properly if a file with the same name is ever + # created in this directory. We explicitly declare our targets to be phony + # by making them a prerequisite of the special target .PHONY + ########################################################################## + +.PHONY: help +## help: prints this help message +help: + @echo "Usage:" + @sed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /' + +.PHONY: lintinstall +## lintinstall: install common linting tools +# https://github.com/golang/go/issues/30515#issuecomment-582044819 +lintinstall: + @echo "Installing linting tools" + + @export PATH="${PATH}:$(go env GOPATH)/bin" + + @echo "Installing latest stable staticcheck version via go install command ..." + go install honnef.co/go/tools/cmd/staticcheck@latest + staticcheck --version + + @echo Installing latest stable golangci-lint version per official installation script ... + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin + golangci-lint --version + + @echo "Finished updating linting tools" + +.PHONY: linting +## linting: runs common linting checks +linting: + @echo "Running linting tools ..." + + @echo "Running go vet ..." + @go vet -mod=vendor $(shell go list -mod=vendor ./... | grep -v /vendor/) + + @echo "Running golangci-lint ..." + @golangci-lint --version + @golangci-lint run + + @echo "Running staticcheck ..." + @staticcheck --version + @staticcheck $(shell go list -mod=vendor ./... | grep -v /vendor/) + + @echo "Finished running linting checks" + +.PHONY: gotests +## gotests: runs go test recursively, verbosely +gotests: + @echo "Running go tests ..." + @go test -v -mod=vendor ./... + @echo "Finished running go tests" + +.PHONY: goclean +## goclean: removes local build artifacts, temporary files, etc +goclean: + @echo "Removing object files and cached files ..." + @$(GOCLEANCMD) + +.PHONY: clean +## clean: alias for goclean +clean: goclean + +.PHONY: gitclean +## gitclean: WARNING - recursively cleans working tree by removing non-versioned files +gitclean: + @echo "Removing non-versioned files ..." + @$(GITCLEANCMD) + +.PHONY: pristine +## pristine: run goclean and gitclean to remove local changes +pristine: goclean gitclean + +.PHONY: all +# https://stackoverflow.com/questions/3267145/makefile-execute-another-target +## all: run all applicable build steps +all: clean build + @echo "Completed build process ..." + +.PHONY: quick +## quick: alias for build recipe +quick: clean build + @echo "Completed tasks for quick build" + +.PHONY: build +## build: ensure that packages build +build: + @echo "Building packages ..." + + $(BUILDCMD) + + @echo "Completed build tasks" diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/README.md b/vendor/github.com/atc0005/go-teams-notify/v2/README.md new file mode 100644 index 000000000..1766fab86 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/README.md @@ -0,0 +1,525 @@ + +# goteamsnotify + +A package to send messages to a Microsoft Teams channel. + +[![Latest release][githubtag-image]][githubtag-url] +[![Go Reference][goref-image]][goref-url] +[![License][license-image]][license-url] +[![go.mod Go version](https://img.shields.io/github/go-mod/go-version/atc0005/go-teams-notify)](https://github.com/atc0005/go-teams-notify) +[![Lint and Build](https://github.com/atc0005/go-teams-notify/actions/workflows/lint-and-build.yml/badge.svg)](https://github.com/atc0005/go-teams-notify/actions/workflows/lint-and-build.yml) +[![Project Analysis](https://github.com/atc0005/go-teams-notify/actions/workflows/project-analysis.yml/badge.svg)](https://github.com/atc0005/go-teams-notify/actions/workflows/project-analysis.yml) + + +## Table of contents + +- [Project home](#project-home) +- [Overview](#overview) +- [Features](#features) +- [Project Status](#project-status) +- [Supported Releases](#supported-releases) + - [Plans: v2](#plans-v2) + - [Plans: v3](#plans-v3) +- [Changelog](#changelog) +- [Usage](#usage) + - [Add this project as a dependency](#add-this-project-as-a-dependency) + - [Setup a connection to Microsoft Teams](#setup-a-connection-to-microsoft-teams) + - [Overview](#overview-1) + - [Workflow connectors](#workflow-connectors) + - [Workflow webhook URL format](#workflow-webhook-url-format) + - [How to create a Workflow connector webhook URL](#how-to-create-a-workflow-connector-webhook-url) + - [Using Teams client Workflows context option](#using-teams-client-workflows-context-option) + - [Using Teams client app](#using-teams-client-app) + - [Using Power Automate web UI](#using-power-automate-web-ui) + - [O365 connectors](#o365-connectors) + - [O365 webhook URL format](#o365-webhook-url-format) + - [How to create an O365 connector webhook URL](#how-to-create-an-o365-connector-webhook-url) + - [Examples](#examples) + - [Basic](#basic) + - [Specify proxy server](#specify-proxy-server) + - [User Mention](#user-mention) + - [CodeBlock](#codeblock) + - [Tables](#tables) + - [Set custom user agent](#set-custom-user-agent) + - [Add an Action](#add-an-action) + - [Toggle visibility](#toggle-visibility) + - [Disable webhook URL prefix validation](#disable-webhook-url-prefix-validation) + - [Enable custom patterns' validation](#enable-custom-patterns-validation) +- [Used by](#used-by) +- [References](#references) + +## Project home + +See [our GitHub repo](https://github.com/atc0005/go-teams-notify) for the +latest code, to file an issue or submit improvements for review and potential +inclusion into the project. + +## Overview + +The `goteamsnotify` package (aka, `go-teams-notify`) allows sending messages +to a Microsoft Teams channel. These messages can be composed of +[🚫 deprecated][o365-connector-retirement-announcement] legacy +[`MessageCard`][msgcard-ref] or [`Adaptive Card`][adaptivecard-ref] card +formats. + +Simple messages can be created by specifying only a title and a text body. +More complex messages may be composed of multiple sections ([🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard`) or +containers (`Adaptive Card`), key/value pairs (aka, `Facts`) and externally +hosted images. See the [Features](#features) list for more information. + +**NOTE**: `Adaptive Card` support is currently limited. The goal is to expand +this support in future releases to include additional features supported by +Microsoft Teams. + +## Features + +- Submit simple or complex messages to Microsoft Teams + - simple messages consist of only a title and a text body (one or more + strings) + - complex messages may consist of multiple sections ([🚫 + deprecated][o365-connector-retirement-announcement] `MessageCard`), + containers (`Adaptive Card`) key/value pairs (aka, `Facts`) and externally + hosted images +- Support for Actions, allowing users to take quick actions within Microsoft + Teams + - [🚫 deprecated][o365-connector-retirement-announcement] [`MessageCard` `Actions`][msgcard-ref-actions] + - [`Adaptive Card` `Actions`][adaptivecard-ref-actions] +- Support for [user mentions][adaptivecard-user-mentions] (`Adaptive + Card` format) +- Configurable validation of webhook URLs + - enabled by default, attempts to match most common known webhook URL + patterns + - option to disable validation entirely + - option to use custom validation patterns +- Configurable validation of [🚫 + deprecated][o365-connector-retirement-announcement] `MessageCard` type + - default assertion that bare-minimum required fields are present + - support for providing a custom validation function to override default + validation behavior +- Configurable validation of `Adaptive Card` type + - default assertion that bare-minimum required fields are present + - support for providing a custom validation function to override default + validation behavior +- Configurable timeouts +- Configurable retry support + +## Project Status + +In short: + +- The upstream project is no longer being actively developed or maintained. +- This fork is now a standalone project, accepting contributions, bug reports + and feature requests. + - see [Supported Releases](#supported-releases) for details +- Others have also taken an interest in [maintaining their own + forks](https://github.com/atc0005/go-teams-notify/network/members) of the + original project. See those forks for other ideas/changes that you may find + useful. + +For more details, see the +[Releases](https://github.com/atc0005/go-teams-notify/releases) section or our +[Changelog](https://github.com/atc0005/go-teams-notify/blob/master/CHANGELOG.md). + +## Supported Releases + +| Series | Example | Status | +| -------- | ---------------- | --------------------------------------- | +| `v1.x.x` | `v1.3.1` | Not Supported (EOL) | +| `v2.x.x` | `v2.6.0` | Supported (until approximately 2026-01) | +| `v3.x.x` | `v3.0.0-alpha.1` | Planning (target 2026-01) | +| `v4.x.x` | `v4.0.0-alpha.1` | TBD | + +### Plans: v2 + +| Task | Start Date / Version | Status | +| ------------------------------------------------------------ | -------------------- | -------- | +| support the v2 branch with bugfixes and minor changes | 2020-03-29 (v2.0.0) | Ongoing | +| add support & documentation for Power Automate workflow URLs | v2.11.0-alpha.1 | Complete | + +### Plans: v3 + +Early January 2026: + +- Microsoft [drops support for O365 + connectors][o365-connector-retirement-announcement] in December 2025 +- we release a v3 branch + - drop support for the [🚫 +deprecated][o365-connector-retirement-announcement] O365 connectors + - drop support for the [🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard`) format +- we drop support for the v2 branch + - the focus would be on maintaining the v3 branch with bugfixes and minor + changes + +> [!NOTE] +> +> While the plan for the upcoming v3 series includes dropping support for the +[🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` format +and O365 connectors, the focus would not be on refactoring the overall code +structure; many of the rough edges currently present in the API would remain +in the v3 series and await a more focused cleanup effort made in preparation +for a future v4 series. + +## Changelog + +See the [`CHANGELOG.md`](CHANGELOG.md) file for the changes associated with +each release of this application. Changes that have been merged to `master`, +but not yet an official release may also be noted in the file under the +`Unreleased` section. A helpful link to the Git commit history since the last +official release is also provided for further review. + +## Usage + +### Add this project as a dependency + +See the [Examples](#examples) section for more details. + +### Setup a connection to Microsoft Teams + +#### Overview + +> [!WARNING] +> +> Microsoft announced July 3rd, 2024 that Office 365 (O365) connectors within +Microsoft Teams would be [retired in 3 +months][o365-connector-retirement-announcement] and replaced by Power Automate +workflows (or just "Workflows" for short). + +Quoting from the microsoft365dev blog: + +> We will gradually roll out this change in waves: +> +> - Wave 1 - effective August 15th, 2024: All new Connector creation will be +> blocked within all clouds +> - Wave 2 - effective October 1st, 2024: All connectors within all clouds +> will stop working + +[Microsoft later changed some of the +details][o365-connector-retirement-announcement] regarding the retirement +timeline of O365 connectors: + +> Update 07/23/2024: We understand and appreciate the feedback that customers +> have shared with us regarding the timeline provided for the migration from +> Office 365 connectors. We have extended the retirement timeline through +> December 2025 to provide ample time to migrate to another solution such as +> Power Automate, an app within Microsoft Teams, or Microsoft Graph. Please +> see below for more information about the extension: +> +> - All existing connectors within all clouds will continue to work until +> December 2025, however using connectors beyond December 31, 2024 will +> require additional action. +> - Connector owners will be required to update the respective URL to post +> by December 31st, 2024. At least 90 days prior to the December 31, 2024 +> deadline, we will send further guidance about making this URL update. If +> the URL is not updated by December 31, 2024 the connector will stop +> working. This is due to further service hardening updates being +> implemented for Office 365 connectors in alignment with Microsoft’s +> [Secure Future +> Initiative](https://blogs.microsoft.com/blog/2024/05/03/prioritizing-security-above-all-else/) +> - Starting August 15th, 2024 all new creations should be created using the +> Workflows app in Microsoft Teams + +Since O365 connectors will likely persist in many environments until the very +end of the deprecation period this project will [continue to support +them](#supported-releases) until then alongside Power Automate workflows. + +#### Workflow connectors + +##### Workflow webhook URL format + +Valid Power Automate Workflow URLs used to submit messages to Microsoft Teams +use this format: + +- `https://*.logic.azure.com:443/workflows/GUID_HERE/triggers/manual/paths/invoke?api-version=YYYY-MM-DD&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=SIGNATURE_HERE` + +Example URL from the LinkedIn [Bring Microsoft Teams incoming webhook security to +the next level with Azure Logic App][linkedin-teams-webhook-security-article] +article: + +- `https://webhook-jenkins.azure-api.net/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=f2QjZY50uoRnX6PIpyPT3xk` + +##### How to create a Workflow connector webhook URL + +> [!TIP] +> +> Use a dedicated "service" account not tied to a specific team member to help +ensure that the Workflow connector is long lived. + +The [initial O365 retirement blog +post][o365-connector-retirement-announcement] provides a list of templates +which guide you through the process of creating a Power Automate Workflow +webhook URL. + +###### Using Teams client Workflows context option + +1. Navigate to a channel or chat +1. Select the ellipsis on the channel or chat +1. Select `Workflows` +1. Type `when a webhook request` +1. Select the appropriate template + - `Post to a channel when a webhook request is received` + - `Post to a chat when a webhook request is received` +1. Verify that `Microsoft Teams` is successfully enabled +1. Select `Next` +1. Select an appropriate value from the `Microsoft Teams Team` drop-down list. +1. Select an appropriate `Microsoft Teams Channel` drop-down list. +1. Select `Create flow` +1. Copy the new workflow URL +1. Select `Done` + +###### Using Teams client app + +1. Open `Workflows` application in teams +1. Select `Create` across the top of the UI +1. Choose `Notifications` at the left +1. Select `Post to a channel when a webhook request is received` +1. Verify that `Microsoft Teams` is successfully enabled +1. Select `Next` +1. Select an appropriate value from the `Microsoft Teams Team` drop-down list. +1. Select an appropriate `Microsoft Teams Channel` drop-down list. +1. Select `Create flow` +1. Copy the new workflow URL +1. Select `Done` + +###### Using Power Automate web UI + +[This][workflow-channel-post-from-webhook-request] template walks you through +the steps of creating a new Workflow using the + web UI: + +1. Select or create a new connection (e.g., ) to Microsoft + Teams +1. Select `Create` +1. Select an appropriate value from the `Microsoft Teams Team` drop-down list. +1. Select an appropriate `Microsoft Teams Channel` drop-down list. +1. Select `Create` +1. If prompted, read the info message (e.g., "Your flow is ready to go") and + dismiss it. +1. Select `Edit` from the menu across the top + - alternatively, select `My flows` from the side menu, then select `Edit` + from the "More commands" ellipsis +1. Select `When a Teams webhook request is received` (e.g., left click) +1. Copy the `HTTP POST URL` value + - this is your *private* custom Workflow connector URL + - by default anyone can `POST` a request to this Workflow connector URL + - while this access setting can be changed it will prevent this library + from being used to submit webhook requests + +#### O365 connectors + +##### O365 webhook URL format + +> [!WARNING] +> +> O365 connector webhook URLs are deprecated and [scheduled to be +retired][o365-connector-retirement-announcement] on 2024-10-01. + +Valid (***deprecated***) O365 webhook URLs for Microsoft Teams use one of several +(confirmed) FQDNs patterns: + +- `outlook.office.com` +- `outlook.office365.com` +- `*.webhook.office.com` + - e.g., `example.webhook.office.com` + +Using an O365 webhook URL with any of these FQDN patterns appears to give +identical results. + +Here are complete, equivalent example webhook URLs from Microsoft's +documentation using the FQDNs above: + +- +- +- + - note the `webhookb2` sub-URI specific to this FQDN pattern + +All of these patterns when provided to this library should pass the default +validation applied. See the example further down for the option of disabling +webhook URL validation entirely. + +##### How to create an O365 connector webhook URL + +> [!WARNING] +> +> O365 connector webhook URLs are deprecated and [scheduled to be +retired][o365-connector-retirement-announcement] on 2024-10-01. + +1. Open Microsoft Teams +1. Navigate to the channel where you wish to receive incoming messages from + this application +1. Select `⋯` next to the channel name and then choose Connectors. +1. Scroll through the list of Connectors to Incoming Webhook, and choose Add. +1. Enter a name for the webhook, upload an image to associate with data from + the webhook, and choose Create. +1. Copy the webhook URL to the clipboard and save it. You'll need the webhook + URL for sending information to Microsoft Teams. + - NOTE: While you can create another easily enough, you should treat this + webhook URL as sensitive information as anyone with this unique URL is + able to send messages (without authentication) into the associated + channel. +1. Choose Done. + +Credit: +[docs.microsoft.com](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using#setting-up-a-custom-incoming-webhook), +[gist comment from +shadabacc3934](https://gist.github.com/chusiang/895f6406fbf9285c58ad0a3ace13d025#gistcomment-3562501) + +### Examples + +#### Basic + +This is an example of a simple client application which uses this library. + +- `Adaptive Card` + - File: [basic](./examples/adaptivecard/basic/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [basic](./examples/messagecard/basic/main.go) + +#### Specify proxy server + +This is an example of a simple client application which uses this library to +route a generated message through a specified proxy server. + +- `Adaptive Card` + - File: [basic](./examples/adaptivecard/proxy/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [basic](./examples/messagecard/proxy/main.go) + +#### User Mention + +These examples illustrates the use of one or more user mentions. This feature +is not available in the legacy [🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard` card format. + +- File: [user-mention-single](./examples/adaptivecard/user-mention-single/main.go) +- File: [user-mention-multiple](./examples/adaptivecard/user-mention-multiple/main.go) +- File: [user-mention-verbose](./examples/adaptivecard/user-mention-verbose/main.go) + - this example does not necessarily reflect an optimal implementation + +#### CodeBlock + +This example illustrates the use of a [`CodeBlock`][adaptivecard-codeblock]. +This feature is not available in the legacy [🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard` card format. + +- File: [codeblock](./examples/adaptivecard/codeblock/main.go) + +#### Tables + +These examples illustrates the use of a [`Table`][adaptivecard-table]. This +feature is not available in the legacy [🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard` card format. + +- File: [table-manually-created](./examples/adaptivecard/table-manually-created/main.go) +- File: [table-unordered-grid](./examples/adaptivecard/table-unordered-grid/main.go) +- File: [table-with-headers](./examples/adaptivecard/table-with-headers/main.go) + +#### Set custom user agent + +This example illustrates setting a custom user agent. + +- `Adaptive Card` + - File: [custom-user-agent](./examples/adaptivecard/custom-user-agent/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [custom-user-agent](./examples/messagecard/custom-user-agent/main.go) + +#### Add an Action + +This example illustrates adding an [`OpenUri`][msgcard-ref-actions] ([🚫 +deprecated][o365-connector-retirement-announcement] `MessageCard`) or +[`OpenUrl`][adaptivecard-ref-actions] Action. When used, this action triggers +opening a URL in a separate browser or application. + +- `Adaptive Card` + - File: [actions](./examples/adaptivecard/actions/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [actions](./examples/messagecard/actions/main.go) + +#### Toggle visibility + +These examples illustrates using +[`ToggleVisibility`][adaptivecard-ref-actions] Actions to control the +visibility of various Elements of an `Adaptive Card` message. + +- File: [toggle-visibility-single-button](./examples/adaptivecard/toggle-visibility-single-button/main.go) +- File: [toggle-visibility-multiple-buttons](./examples/adaptivecard/toggle-visibility-multiple-buttons/main.go) +- File: [toggle-visibility-column-action](./examples/adaptivecard/toggle-visibility-column-action/main.go) +- File: [toggle-visibility-container-action](./examples/adaptivecard/toggle-visibility-container-action/main.go) + +#### Disable webhook URL prefix validation + +This example disables the validation webhook URLs, including the validation of +known prefixes so that custom/private webhook URL endpoints can be used (e.g., +testing purposes). + +- `Adaptive Card` + - File: [disable-validation](./examples/adaptivecard/disable-validation/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [disable-validation](./examples/messagecard/disable-validation/main.go) + +#### Enable custom patterns' validation + +This example demonstrates how to enable custom validation patterns for webhook +URLs. + +- `Adaptive Card` + - File: [custom-validation](./examples/adaptivecard/custom-validation/main.go) +- [🚫 deprecated][o365-connector-retirement-announcement] `MessageCard` + - File: [custom-validation](./examples/messagecard/custom-validation/main.go) + +## Used by + +See the Known importers lists below for a dynamically updated list of projects +using either this library or the original project. + +- [this fork](https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2?tab=importedby) +- [original project](https://pkg.go.dev/github.com/dasrick/go-teams-notify/v2?tab=importedby) + +## References + +- [Original project](https://github.com/dasrick/go-teams-notify) +- [Forks of original project](https://github.com/atc0005/go-teams-notify/network/members) + + +- Microsoft Teams + - Adaptive Cards + ([de-de](https://docs.microsoft.com/de-de/outlook/actionable-messages/adaptive-card), + [en-us](https://docs.microsoft.com/en-us/outlook/actionable-messages/adaptive-card)) + - O365 connectors + - [Send via connectors](https://docs.microsoft.com/en-us/outlook/actionable-messages/send-via-connectors)) + - [Create Incoming Webhooks](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook) + - [adaptivecards.io](https://adaptivecards.io/designer) + - [Legacy actionable message card reference][msgcard-ref] + - Workflow connectors + - [Creating a workflow from a chat in Teams](https://support.microsoft.com/en-us/office/creating-a-workflow-from-a-channel-in-teams-242eb8f2-f328-45be-b81f-9817b51a5f0e) + - [Creating a workflow from a channel in Teams](https://support.microsoft.com/en-us/office/creating-a-workflow-from-a-chat-in-teams-e3b51c4f-49de-40aa-a6e7-bcff96b99edc) + + + +[o365-connector-retirement-announcement]: "Retirement of Office 365 connectors within Microsoft Teams" +[workflow-channel-post-from-webhook-request]: "Post to a channel when a webhook request is received" +[linkedin-teams-webhook-security-article]: "Bring Microsoft Teams incoming webhook security to the next level with Azure Logic App" + +[githubtag-image]: https://img.shields.io/github/release/atc0005/go-teams-notify.svg?style=flat +[githubtag-url]: https://github.com/atc0005/go-teams-notify + +[goref-image]: https://pkg.go.dev/badge/github.com/atc0005/go-teams-notify/v2.svg +[goref-url]: https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2 + +[license-image]: https://img.shields.io/github/license/atc0005/go-teams-notify.svg?style=flat +[license-url]: https://github.com/atc0005/go-teams-notify/blob/master/LICENSE + +[msgcard-ref]: +[msgcard-ref-actions]: + +[adaptivecard-ref]: +[adaptivecard-ref-actions]: +[adaptivecard-user-mentions]: +[adaptivecard-table]: + +[adaptivecard-codeblock]: + + diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/adaptivecard.go b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/adaptivecard.go new file mode 100644 index 000000000..fd36eb1f0 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/adaptivecard.go @@ -0,0 +1,3428 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package adaptivecard + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "regexp" + "strconv" + "strings" + + goteamsnotify "github.com/atc0005/go-teams-notify/v2" + "github.com/atc0005/go-teams-notify/v2/internal/validator" +) + +// General constants. +const ( + // TypeMessage is the type for an Adaptive Card Message. + TypeMessage string = "message" + + // PixelSizeRegex is a regular expression pattern intended to match + // specific pixel size (height, width) values such as "50px". + PixelSizeRegex string = "^[0-9]+px$" + + // PixelSizeExample is an example of a valid pixel size (height, width) + // value. + PixelSizeExample string = "50px" +) + +// Card & TopLevelCard specific constants. +const ( + // TypeAdaptiveCard is the supported type value for an Adaptive Card. + TypeAdaptiveCard string = "AdaptiveCard" + + // AdaptiveCardSchema represents the URI of the Adaptive Card schema. + AdaptiveCardSchema string = "http://adaptivecards.io/schemas/adaptive-card.json" + + // AdaptiveCardMaxVersion represents the highest supported version of the + // Adaptive Card schema supported in Microsoft Teams messages. + // + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards + // https://adaptivecards.io/designer + // + // NOTE: Documented as 1.5 (adaptivecards.io/designer), but in practice > + // 1.4 is rejected for Power Automate workflow connectors. + // + // Setting to 1.4 works both for legacy O365 connectors and Workflow + // connectors. + AdaptiveCardMaxVersion float64 = 1.4 + AdaptiveCardMinVersion float64 = 1.0 + AdaptiveCardVersionTmpl string = "%0.1f" +) + +// Mention constants. +const ( + // TypeMention is the type for a user mention for a Adaptive Card Message. + TypeMention string = "mention" + + // MentionTextFormatTemplate is the expected format of the Mention.Text + // field value. + MentionTextFormatTemplate string = "%s" + + // defaultMentionTextSeparator is the default separator used between the + // contents of the Mention.Text field and a TextBlock.Text field. + defaultMentionTextSeparator string = " " +) + +// Attachment constants. +// +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference +// - https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.schema.attachmentlayouttypes +// - https://docs.microsoft.com/en-us/javascript/api/botframework-schema/attachmentlayouttypes +// - https://github.com/matthidinger/ContosoScubaBot/blob/master/Cards/1-Schools.JSON +const ( + + // AttachmentContentType is the supported type value for an attached + // Adaptive Card for a Microsoft Teams message. + AttachmentContentType string = "application/vnd.microsoft.card.adaptive" + + AttachmentLayoutList string = "list" + AttachmentLayoutCarousel string = "carousel" +) + +// TextBlock specific constants. +// https://adaptivecards.io/explorer/TextBlock.html +const ( + // TextBlockStyleDefault indicates that the TextBlock uses the default + // style which provides no special styling or behavior. + TextBlockStyleDefault string = "default" + + // TextBlockStyleHeading indicates that the TextBlock is a heading. This + // will apply the heading styling defaults and mark the text block as a + // heading for accessibility. + TextBlockStyleHeading string = "heading" +) + +// Column specific constants. +// https://adaptivecards.io/explorer/Column.html +const ( + // TypeColumn is the type for an Adaptive Card Column. + TypeColumn string = "Column" + + // ColumnWidthAuto indicates that a column's width should be determined + // automatically based on other columns in the column group. + ColumnWidthAuto string = "auto" + + // ColumnWidthStretch indicates that a column's width should be stretched + // to fill the enclosing column group. + ColumnWidthStretch string = "stretch" +) + +// Table specific constants. +// +// https://adaptivecards.io/explorer/Table.html +// https://adaptivecards.io/explorer/TableCell.html +const ( + + // NOTE: Table is not a type, it is an Card Element + // TypeTable string = "Table" + + TypeTableColumnDefinition string = "TableColumnDefinition" + TypeTableRow string = "TableRow" + TypeTableCell string = "TableCell" +) + +// Text size for TextBlock or TextRun elements. +const ( + SizeSmall string = "small" + SizeDefault string = "default" + SizeMedium string = "medium" + SizeLarge string = "large" + SizeExtraLarge string = "extraLarge" +) + +// Text weight for TextBlock or TextRun elements. +const ( + WeightBolder string = "bolder" + WeightLighter string = "lighter" + WeightDefault string = "default" +) + +// Supported colors for TextBlock or TextRun elements. +const ( + ColorDefault string = "default" + ColorDark string = "dark" + ColorLight string = "light" + ColorAccent string = "accent" + ColorGood string = "good" + ColorWarning string = "warning" + ColorAttention string = "attention" +) + +// Image specific constants. +// https://adaptivecards.io/explorer/Image.html +const ( + ImageStyleDefault string = "" + ImageStylePerson string = "" +) + +// ChoiceInput specific constants. +const ( + ChoiceInputStyleCompact string = "compact" + ChoiceInputStyleExpanded string = "expanded" + ChoiceInputStyleFiltered string = "filtered" // Introduced in version 1.5 +) + +// TextInput specific constants. +const ( + TextInputStyleText string = "text" + TextInputStyleTel string = "tel" + TextInputStyleURL string = "url" + TextInputStyleEmail string = "email" + TextInputStylePassword string = "password" // Introduced in version 1.5 +) + +// Container specific constants. +const ( + ContainerStyleDefault string = "default" + ContainerStyleEmphasis string = "emphasis" + ContainerStyleGood string = "good" + ContainerStyleAttention string = "attention" + ContainerStyleWarning string = "warning" + ContainerStyleAccent string = "accent" +) + +// Supported spacing values for FactSet, Container and other container element +// types. +const ( + SpacingDefault string = "default" + SpacingNone string = "none" + SpacingSmall string = "small" + SpacingMedium string = "medium" + SpacingLarge string = "large" + SpacingExtraLarge string = "extraLarge" + SpacingPadding string = "padding" +) + +// Supported Horizontal alignment values for (supported) container and text +// types. +const ( + HorizontalAlignmentLeft string = "left" + HorizontalAlignmentCenter string = "center" + HorizontalAlignmentRight string = "right" +) + +// Supported Horizontal alignment values for (supported) container types. +const ( + VerticalAlignmentTop string = "top" + VerticalAlignmentCenter string = "center" + VerticalAlignmentBottom string = "bottom" +) + +// Supported width values for the msteams property used in in Adaptive Card +// messages sent via Microsoft Teams. +const ( + MSTeamsWidthFull string = "Full" +) + +// Supported Actions +const ( + + // TeamsActionsDisplayLimit is the observed limit on the number of visible + // URL "buttons" in a Microsoft Teams message. + // + // Unlike the MessageCard format which has a clearly documented limit of 4 + // actions, testing reveals that Desktop / Web displays 6 without the + // option to expand and see any additional defined actions. Mobile + // displays 6 with an ellipsis to expand into a list of other Actions. + // + // This results in a maximum limit of 6 actions in the Actions array for a + // Card. + // + // A workaround is to create multiple ActionSet elements and limit the + // number of Actions in each set ot 6. + // + // https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference#actions + TeamsActionsDisplayLimit int = 6 + + // TypeActionExecute is an action that gathers input fields, merges with + // optional data field, and sends an event to the client. Clients process + // the event by sending an Invoke activity of type adaptiveCard/action to + // the target Bot. The inputs that are gathered are those on the current + // card, and in the case of a show card those on any parent cards. See + // Universal Action Model documentation for more details: + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model + // + // TypeActionExecute was introduced in Adaptive Cards schema version 1.4. + // TypeActionExecute actions may not render with earlier versions of the + // Teams client. + TypeActionExecute string = "Action.Execute" + + // ActionExecuteMinCardVersionRequired is the minimum version of the + // Adaptive Card schema required to support Action.Execute. + ActionExecuteMinCardVersionRequired float64 = 1.4 + + // TypeActionSubmit is used in Adaptive Cards schema version 1.3 and + // earlier or as a fallback for TypeActionExecute in schema version 1.4. + // TypeActionSubmit is not supported in Incoming Webhooks. + TypeActionSubmit string = "Action.Submit" + + // TypeActionOpenURL (when invoked) shows the given url either by + // launching it in an external web browser or showing within an embedded + // web browser. + TypeActionOpenURL string = "Action.OpenUrl" + + // TypeActionShowCard defines an AdaptiveCard which is shown to the user + // when the button or link is clicked. + TypeActionShowCard string = "Action.ShowCard" + + // TypeActionToggleVisibility toggles the visibility of associated card + // elements. + TypeActionToggleVisibility string = "Action.ToggleVisibility" +) + +// Supported Fallback options. +const ( + TypeFallbackActionExecute string = TypeActionExecute + TypeFallbackActionOpenURL string = TypeActionOpenURL + TypeFallbackActionShowCard string = TypeActionShowCard + TypeFallbackActionSubmit string = TypeActionSubmit + TypeFallbackActionToggleVisibility string = TypeActionToggleVisibility + + // TypeFallbackOptionDrop causes this element to be dropped immediately + // when unknown elements are encountered. The unknown element doesn't + // bubble up any higher. + TypeFallbackOptionDrop string = "drop" +) + +// Valid types for an Adaptive Card element. Not all types are supported by +// Microsoft Teams. +// +// TODO: Confirm whether all types are supported. +// +// - https://adaptivecards.io/explorer/AdaptiveCard.html +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards +// - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#schema +const ( + TypeElementActionSet string = "ActionSet" + TypeElementColumnSet string = "ColumnSet" + TypeElementContainer string = "Container" + TypeElementFactSet string = "FactSet" + TypeElementImage string = "Image" + TypeElementImageSet string = "ImageSet" + TypeElementInputChoiceSet string = "Input.ChoiceSet" + TypeElementInputDate string = "Input.Date" + TypeElementInputNumber string = "Input.Number" + TypeElementInputText string = "Input.Text" + TypeElementInputTime string = "Input.Time" + TypeElementInputToggle string = "Input.Toggle" + TypeElementMedia string = "Media" // Introduced in version 1.1 (TODO: Is this supported in Teams message?) + TypeElementRichTextBlock string = "RichTextBlock" // Introduced in version 1.2 + TypeElementTable string = "Table" // Introduced in version 1.5 + TypeElementTextBlock string = "TextBlock" + TypeElementTextRun string = "TextRun" // Introduced in version 1.2 +) + +// Known extension types for an Adaptive Card element. +// +// - https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format?tabs=adaptive-md%2Cdesktop%2Cconnector-html#codeblock-in-adaptive-cards +const ( + TypeElementMSTeamsCodeBlock string = "CodeBlock" +) + +// Sentinel errors for this package. +var ( + // ErrInvalidType indicates that an invalid type was specified. + ErrInvalidType = errors.New("invalid type value") + + // ErrInvalidFieldValue indicates that an invalid value was specified. + ErrInvalidFieldValue = errors.New("invalid field value") + + // ErrMissingValue indicates that an expected value was missing. + ErrMissingValue = errors.New("missing expected value") + + // ErrValueNotFound indicates that a requested value was not found. + ErrValueNotFound = errors.New("requested value not found") +) + +// Message represents a Microsoft Teams message containing one or more +// Adaptive Cards. +type Message struct { + // Type is required; must be set to "message". + Type string `json:"type"` + + // Attachments is a collection of one or more Adaptive Cards. + // + // NOTE: Including multiple attachment *without* AttachmentLayout set to + // "carousel" hides cards after the first. Not sure if this is a bug, or + // if it's intentional. + Attachments []Attachment `json:"attachments"` + + // AttachmentLayout controls the layout for Adaptive Cards in the + // Attachments collection. + AttachmentLayout string `json:"attachmentLayout,omitempty"` + + // ValidateFunc is an optional user-specified validation function that is + // responsible for validating a Message. If not specified, default + // validation is performed. + ValidateFunc func() error `json:"-"` + + // payload is a prepared Message in JSON format for submission or pretty + // printing. + payload *bytes.Buffer `json:"-"` +} + +// Attachments is a collection of Adaptive Cards for a Microsoft Teams +// message. +type Attachments []Attachment + +// Attachment represents an attached Adaptive Card for a Microsoft Teams +// message. +type Attachment struct { + + // ContentType is required; must be set to + // "application/vnd.microsoft.card.adaptive". + ContentType string `json:"contentType"` + + // ContentURL appears to be related to support for tabs. Most examples + // have this value set to null. + // + // TODO: Update this description with confirmed details. + ContentURL NullString `json:"contentUrl,omitempty"` + + // Content represents the content of an Adaptive Card. + // + // TODO: Should this be a pointer? + Content TopLevelCard `json:"content"` +} + +// TopLevelCard represents the outer or top-level Card for a Microsoft Teams +// Message attachment. +type TopLevelCard struct { + Card +} + +// Card represents the content of an Adaptive Card. The TopLevelCard is a +// superset of this one, asserting that the Version field is properly set. +// That type is used exclusively for Message Attachments. This type is used +// directly for the Action.ShowCard Card field. +type Card struct { + + // Type is required; must be set to "AdaptiveCard" + Type string `json:"type"` + + // Schema represents the URI of the Adaptive Card schema. + Schema string `json:"$schema"` + + // Version is required for top-level cards (i.e., the outer card in an + // attachment); the schema version that the content for an Adaptive Card + // requires. + // + // The TopLevelCard type is a superset of the Card type and asserts that + // this field is properly set, whereas the validation logic for this + // (Card) type skips that assertion. + Version string `json:"version"` + + // FallbackText is the text shown when the client doesn't support the + // version specified (may contain markdown). + FallbackText string `json:"fallbackText,omitempty"` + + // Body represents the body of an Adaptive Card. The body is made up of + // building-blocks known as elements. Elements can be composed to create + // many types of cards. These elements are shown in the primary card + // region. + Body []Element `json:"body"` + + // Actions is a collection of actions to show in the card's action bar. + // The action bar is displayed at the bottom of a Card. + // + // NOTE: The max display limit has been observed to be a fixed value for + // web/desktop app and a matching value as an initial display limit for + // mobile app with the option to expand remaining actions in a list. + // + // This value is recorded in this package as "TeamsActionsDisplayLimit". + // + // To work around this limit, create multiple ActionSets each limited to + // the value of TeamsActionsDisplayLimit. + Actions []Action `json:"actions,omitempty"` + + // MSTeams is a container for properties specific to Microsoft Teams + // messages, including formatting properties and user mentions. + // + // NOTE: Using pointer in order to omit unused field from JSON output. + // https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go + // MSTeams *MSTeams `json:"msteams,omitempty"` + // + // TODO: Revisit this and use a pointer if remote API doesn't like + // receiving an empty object, though brief testing doesn't show this to be + // a problem. + MSTeams MSTeams `json:"msteams,omitempty"` + + // MinHeight specifies the minimum height of the card. + MinHeight string `json:"minHeight,omitempty"` + + // VerticalContentAlignment defines how the content should be aligned + // vertically within the container. Only relevant for fixed-height cards, + // or cards with a minHeight specified. If MinHeight field is specified, + // this field is required. + VerticalContentAlignment string `json:"verticalContentAlignment,omitempty"` +} + +// Elements is a collection of Element values. +type Elements []Element + +// Element is a "building block" for an Adaptive Card. Elements are shown +// within the primary card region (aka, "body"), columns and other container +// types. Not all fields of this Go struct type are supported by all Adaptive +// Card element types. +type Element struct { + + // Type is required and indicates the type of the element used in the body + // of an Adaptive Card. + // https://adaptivecards.io/explorer/AdaptiveCard.html + Type string `json:"type"` + + // ID is a unique identifier associated with this Element. + ID string `json:"id,omitempty"` + + // Text is required by the TextBlock and TextRun element types. Text is + // used to display text. A subset of markdown is supported for text used + // in TextBlock elements, but no formatting is permitted in text used in + // TextRun elements. + // + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features + // https://adaptivecards.io/explorer/TextBlock.html + // https://adaptivecards.io/explorer/TextRun.html + Text string `json:"text,omitempty"` + + // URL is required for the Image element type. URL is the URL to an Image + // in an ImageSet element type. + // + // https://adaptivecards.io/explorer/Image.html + // https://adaptivecards.io/explorer/ImageSet.html + URL string `json:"url,omitempty"` + + // Size controls the size of text within a TextBlock element. + Size string `json:"size,omitempty"` + + // Weight controls the weight of text in TextBlock or TextRun elements. + Weight string `json:"weight,omitempty"` + + // Color controls the color of TextBlock elements or text used in TextRun + // elements. + Color string `json:"color,omitempty"` + + // Spacing controls the amount of spacing between this element and the + // preceding element. + Spacing string `json:"spacing,omitempty"` + + // HorizontalAlignment controls the horizontal text alignment. + HorizontalAlignment string `json:"horizontalAlignment,omitempty"` + + // The style of the element for accessibility purposes. Valid values + // differ based on the element type. For example, a TextBlock element + // supports the "heading" style, whereas the Column element supports the + // "attention" style (TextBlock does not). + Style string `json:"style,omitempty"` + + // Items is required for most Container element types. Items is a + // collection of card elements to render inside the Container. + Items []Element `json:"items,omitempty"` + + // Columns is a collection of Columns used to divide a region. This field + // is used both by ColumnSet and Table element types. The specific field + // validation applied is based on the Type field of this Element. + Columns []Column `json:"columns,omitempty"` + + // Rows defines the rows of the table. This field is used by a Table + // element type. + Rows []TableRow `json:"rows,omitempty"` + + // GridStyle defines the style of the grid. This property currently only + // controls the grid's color. This field is used by a Table element type. + GridStyle string `json:"gridStyle,omitempty"` + + // FirstRowAsHeaders specifies whether the first row of the table should be + // treated as a header row, and be announced as such by accessibility + // software. This field is used by a Table element type. + // + // If not specified defaults to true. + // + // NOTE: We define this field as a pointer type so that omitting a value + // for the pointer leaves the field out of the generated JSON payload (due + // to 'omitempty' behavior of the JSON encoder and results in the + // "defaults to true" behavior as defined by the schema. + FirstRowAsHeaders *bool `json:"firstRowAsHeaders,omitempty"` + + // Visible specifies whether this element will be removed from the visual + // tree. + // + // If not specified defaults to true. + // + // NOTE: We define this field as a pointer type so that omitting a value + // for the pointer leaves the field out of the generated JSON payload (due + // to 'omitempty' behavior of the JSON encoder and results in the + // "defaults to true" behavior as defined by the schema. + Visible *bool `json:"isVisible,omitempty"` + + // ShowGridLines specified whether grid lines should be displayed. This + // field is used by a Table element type. + // + // If not specified defaults to true. + // + // NOTE: We define this field as a pointer type so that omitting a value + // for the pointer leaves the field out of the generated JSON payload (due + // to 'omitempty' behavior of the JSON encoder and results in the + // "defaults to true" behavior as defined by the schema. + ShowGridLines *bool `json:"showGridLines,omitempty"` + + // Actions is required for the ActionSet element type. Actions is a + // collection of Actions to show for an ActionSet element type. + // + // TODO: Should this be a pointer? + Actions []Action `json:"actions,omitempty"` + + // SelectAction is an Action that will be invoked when the Container + // element is tapped or selected. Action.ShowCard is not supported. + // + // This field is used by supported Container element types (Column, + // ColumnSet, Container). + // + SelectAction *ISelectAction `json:"selectAction,omitempty"` + + // Facts is required for the FactSet element type. Actions is a collection + // of Fact values that are part of a FactSet element type. Each Fact value + // is a key/value pair displayed in tabular form. + // + // TODO: Should this be a pointer? + Facts []Fact `json:"facts,omitempty"` + + // Wrap controls whether text is allowed to wrap or is clipped for + // TextBlock elements. + Wrap bool `json:"wrap,omitempty"` + + // IsSubtle specifies whether this element should appear slightly toned + // down. + IsSubtle bool `json:"isSubtle,omitempty"` + + // Separator, when true, indicates that a separating line shown should be + // drawn at the top of the element. + Separator bool `json:"separator,omitempty"` + + // CodeSnippet provides the content for a CodeBlock element, specific to MSTeams. + CodeSnippet string `json:"codeSnippet,omitempty"` + + // Language specifies the language of a CodeBlock element, specific to MSTeams. + Language string `json:"language,omitempty"` + + // StartLineNumber specifies the initial line number of CodeBlock element, specific to MSTeams. + StartLineNumber int `json:"startLineNumber,omitempty"` +} + +// Container is an Element type that allows grouping items together. +type Container Element + +// FactSet is an Element type that groups and displays a series of facts (i.e. +// name/value pairs) in a tabular form. +type FactSet Element + +// Columns is a collection of Column values for a ColumnSet or a Table. +type Columns []Column + +// ColumnItems is a collection of card elements that should be rendered inside +// of the column. +type ColumnItems []*Element + +// Column is a container used by a ColumnSet or Table element type. Each +// container may contain one or more elements. +// +// https://adaptivecards.io/explorer/Column.html +type Column struct { + // Type is required; must be set to "Column" when used with ColumnSet type + // or "TableColumnDefinition" when used as a Table column. + Type string `json:"type,omitempty"` + + // ID is a unique identifier associated with this Column. + ID string `json:"id,omitempty"` + + // Width represents the width of a column in the column group OR a column + // in a table. Valid values consist of fixed strings OR a number + // representing the relative width. + // + // If used in a column group, valid values are "auto", "stretch", a number + // representing relative width of the column in the column group or a + // string that specifies a pixel width, like "50px". + // + // If used in a table, valid values are a number representing relative + // width of the column relative to the other columns in the table or a + // string that specifies a pixel width, like "50px". + Width interface{} `json:"width,omitempty"` + + // Items are the card elements that should be rendered inside of the + // column. + Items []*Element `json:"items,omitempty"` + + // SelectAction is an action that will be invoked when the Column is + // tapped or selected. Action.ShowCard is not supported. + SelectAction *ISelectAction `json:"selectAction,omitempty"` + + // HorizontalCellContentAlignment is a property of the Table element type. + // + // This field controls how the content of all cells in the column is + // horizontally aligned by default. When specified, this value overrides + // the setting at the table level. When not specified, horizontal + // alignment is defined at the table, row or cell level. + HorizontalCellContentAlignment string `json:"horizontalCellContentAlignment,omitempty"` + + // VerticalCellContentAlignment is a property of the Table element type. + // + // This field controls how the content of all cells in the column is + // vertically aligned by default. When specified, this value overrides the + // setting at the table level. When not specified, vertical alignment is + // defined at the table, row or cell level. + VerticalCellContentAlignment string `json:"verticalCellContentAlignment,omitempty"` +} + +// Facts is a collection of Fact values. +type Facts []Fact + +// Fact represents a Fact in a FactSet as a key/value pair. +type Fact struct { + // Title is required; the title of the fact. + Title string `json:"title"` + + // Value is required; the value of the fact. + Value string `json:"value"` +} + +// TableColumnDefinition defines the characteristics of a column in a Table +// element such as number of columns or their sizes. +// +// https://adaptivecards.io/explorer/Table.html +type TableColumnDefinition Column + +// TableColumnDefinitions is a collection of TableColumnDefinition values. +// +// We use this as a "wrapper" type to convert a Columns collection so that we +// can apply specific validation requirements specific to a Table column. +type TableColumnDefinitions []Column + +// TableCell represents a cell within a row of a Table element. +// +// https://adaptivecards.io/explorer/TableCell.html +type TableCell struct { + // Type is required; must be set to "TableCell". + Type string `json:"type"` + + // Style is a style hint for a TableCell. + Style string `json:"style,omitempty"` + + // Bleed determines whether the element should bleed through its parent's + // padding. + Bleed bool `json:"bleed,omitempty"` + + // MinHeight specifies the minimum height of the container in pixels + // (e.g., 80px). + MinHeight string `json:"minHeight,omitempty"` + + // VerticalContentAlignment defines how the content should be aligned + // vertically within the container. + // + // When not specified, the value of VerticalContentAlignment is inherited + // from the parent container. If no parent container has + // VerticalContentAlignment set, it defaults to Top. + VerticalContentAlignment string `json:"verticalContentAlignment,omitempty"` + + // Items are the card elements that should be rendered inside of the + // cell. + Items []*Element `json:"items,omitempty"` +} + +// TableCells is a collection of TableCell values. +type TableCells []TableCell + +// TableRow is a row within a Table each being a collection of cells. Rows are +// not required, which allows empty Tables to be generated via templating +// without breaking the rendering of the whole card. +// +// https://adaptivecards.io/explorer/Table.html +type TableRow struct { + // Type is required; must be set to "TableRow". + Type string `json:"type"` + + // Style defines the style of the entire row. + Style string `json:"style,omitempty"` + + // HorizontalCellContentAlignment is a property of the Table element type. + // + // This field controls how the content of all cells in the row is + // horizontally aligned by default. When specified, this value overrides + // both the setting at the table and columns level. When not specified, + // horizontal alignment is defined at the table, column or cell level. + HorizontalCellContentAlignment string `json:"horizontalCellContentAlignment,omitempty"` + + // VerticalCellContentAlignment is a property of the Table element type. + // + // This field controls how the content of all cells in the column is + // vertically aligned by default. When specified, this value overrides the + // setting at the table and column level. When not specified, vertical + // alignment is defined either at the table, column or cell level. + VerticalCellContentAlignment string `json:"verticalCellContentAlignment,omitempty"` + + // Cells are the cells in this row. If a row contains more cells than + // there are columns defined on the Table element, the extra cells are + // ignored. + Cells []TableCell `json:"cells"` +} + +// TableRows is a collection of TableRow values. +type TableRows []TableRow + +// Actions is a collection of Action values. +type Actions []Action + +// Action represents an action that a user may take on a card. Actions +// typically get rendered in an "action bar" at the bottom of a card. +// +// - https://adaptivecards.io/explorer/ActionSet.html +// - https://adaptivecards.io/explorer/AdaptiveCard.html +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference +// +// TODO: Extend with additional supported fields. +type Action struct { + + // Type is required; specific values are supported. + // + // Action.Submit is not supported for Incoming Webhooks. + // + // Action.Execute was added in Adaptive Card schema version 1.4. which + // Teams MAY not fully support. + // + // The supported actions are Action.OpenURL, Action.ShowCard, + // Action.ToggleVisibility, and Action.Execute (see above). + // + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#schema + Type string `json:"type"` + + // ID is a unique identifier associated with this Action. + ID string `json:"id,omitempty"` + + // Title is a label for the button or link that represents this action. + Title string `json:"title,omitempty"` + + // URL to open; required for the Action.OpenUrl type, optional for other + // action types. + URL string `json:"url,omitempty"` + + // Fallback describes what to do when an unknown element is encountered or + // the requirements of this or any children can't be met. + Fallback string `json:"fallback,omitempty"` + + // Card property is used by Action.ShowCard type. + // + // NOTE: Based on a review of JSON content, it looks like `ActionCard` is + // really just a `Card` type. + // + // refs https://github.com/matthidinger/ContosoScubaBot/blob/master/Cards/SubscriberNotification.JSON + Card *Card `json:"card,omitempty"` + + // TargetElements is the collection of TargetElement values. + // + // It is not recommended to include Input elements with validation due to + // confusion that can arise from invalid inputs that are not currently + // visible. + // + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/input-validation + TargetElements []TargetElement `json:"targetElements,omitempty"` +} + +// TargetElement represents an entry for Action.ToggleVisibility's +// targetElements property. +// +// - https://adaptivecards.io/explorer/TargetElement.html +// - https://adaptivecards.io/explorer/Action.ToggleVisibility.html +type TargetElement struct { + // ElementID is the ID value of the element to toggle. + ElementID string `json:"elementId"` + + // Visible provides display or visibility control for a target Element. + // + // - If true, always show target element. + // - If false, always hide target element. + // - If not supplied, toggle target element's visibility. + // + // NOTE: We define this field as a pointer type so that omitting a value + // for the pointer leaves the field out of the generated JSON payload (due + // to 'omitempty' behavior of the JSON encoder. If leaving this field out, + // visibility can be toggled for target Elements. + Visible *bool `json:"isVisible,omitempty"` +} + +/* + +General scratch notes for https://github.com/atc0005/go-teams-notify/issues/243 +=============================================================================== + +https://adaptivecards.io/explorer/Action.ToggleVisibility.html +https://adaptivecards.io/explorer/TargetElement.html + +While the targetElements array (JSON) supports raw text strings OR +TargetElement values, we will opt to only support TargetElement values. +Otherwise, we end up needing to use more complicated logic. + +Instead of trying to support this: + + "targetElements": [ + "textToToggle", + "imageToToggle", + "imageToToggle2" + ] + +we support this instead: + + "targetElements": [ + { + "elementId": "textToToggle" + }, + { + "elementId": "imageToToggle" + }, + { + "elementId": "imageToToggle2" + } + ] + + +A Container type has a selectAction field. That slice contains TargetElement +entries. + +*/ + +// ISelectAction represents an Action that will be invoked when a container +// type (e.g., Column, ColumnSet, Container) is tapped or selected. +// Action.ShowCard is not supported. +// +// - https://adaptivecards.io/explorer/Container.html +// - https://adaptivecards.io/explorer/ColumnSet.html +// - https://adaptivecards.io/explorer/Column.html +// +// TODO: Extend with additional supported fields. +type ISelectAction struct { + + // Type is required; specific values are supported. + // + // The supported actions are Action.Execute, Action.OpenUrl, + // Action.ToggleVisibility. + // + // See also https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + Type string `json:"type"` + + // ID is a unique identifier associated with this ISelectAction. + ID string `json:"id,omitempty"` + + // Title is a label for the button or link that represents this action. + Title string `json:"title,omitempty"` + + // URL is required for the Action.OpenUrl type, optional for other action + // types. + URL string `json:"url,omitempty"` + + // Fallback describes what to do when an unknown element is encountered or + // the requirements of this or any children can't be met. + Fallback string `json:"fallback,omitempty"` + + // TargetElements is the collection of TargetElement values. + // + // This field is specific to the Action.ToggleVisibility Action type. + // + // It is not recommended to include Input elements with validation due to + // confusion that can arise from invalid inputs that are not currently + // visible. + // + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/input-validation + TargetElements []TargetElement `json:"targetElements,omitempty"` +} + +// MSTeams represents a container for properties specific to Microsoft Teams +// messages, including formatting properties and user mentions. +type MSTeams struct { + + // Width controls the width of Adaptive Cards within a Microsoft Teams + // messages. + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#full-width-adaptive-card + Width string `json:"width,omitempty"` + + // AllowExpand controls whether images can be displayed in stage view + // selectively. + // + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#stage-view-for-images-in-adaptive-cards + AllowExpand bool `json:"allowExpand,omitempty"` + + // Entities is a collection of user mentions. + // TODO: Should this be a slice of pointers? + Entities []Mention `json:"entities,omitempty"` +} + +// Mentions is a collection of Mention values. +type Mentions []Mention + +// Mention represents a mention in the message for a specific user. +type Mention struct { + // Type is required; must be set to "mention". + Type string `json:"type"` + + // Text must match a portion of the message text field. If it does not, + // the mention is ignored. + // + // Brief testing indicates that this needs to wrap a name/value in NAME + // HERE tags. + Text string `json:"text"` + + // Mentioned represents a user that is mentioned. + Mentioned Mentioned `json:"mentioned"` +} + +// Mentioned represents the user id and name of a user that is mentioned. +type Mentioned struct { + // ID is the unique identifier for a user that is mentioned. This value + // can be an object ID (e.g., 5e8b0f4d-2cd4-4e17-9467-b0f6a5c0c4d0) or a + // UserPrincipalName (e.g., NewUser@contoso.onmicrosoft.com). + ID string `json:"id"` + + // Name is the DisplayName of the user mentioned. + Name string `json:"name"` +} + +// NewMessage creates a new Message with required fields predefined. +func NewMessage() *Message { + return &Message{ + Type: TypeMessage, + } +} + +// NewSimpleMessage creates a new simple Message using the specified text and +// optional title. If specified, text wrapping is enabled. An error is +// returned if an empty text string is specified. +func NewSimpleMessage(text string, title string, wrap bool) (*Message, error) { + if text == "" { + return nil, fmt.Errorf( + "required field text is empty: %w", + ErrMissingValue, + ) + } + + msg := Message{ + Type: TypeMessage, + } + + textCard, err := NewTextBlockCard(text, title, wrap) + if err != nil { + return nil, fmt.Errorf( + "failed to create TextBlock card: %w", + err, + ) + } + + if err := msg.Attach(textCard); err != nil { + return nil, fmt.Errorf( + "failed to create simple message: %w", + err, + ) + } + + return &msg, nil +} + +// NewTextBlockCard creates a new Card using the specified text and optional +// title. If specified, the TextBlock has text wrapping enabled. +func NewTextBlockCard(text string, title string, wrap bool) (Card, error) { + if text == "" { + return Card{}, fmt.Errorf( + "required field text is empty: %w", + ErrMissingValue, + ) + } + + textBlock := Element{ + Type: TypeElementTextBlock, + Wrap: wrap, + Text: text, + } + + card := Card{ + Type: TypeAdaptiveCard, + Schema: AdaptiveCardSchema, + Version: fmt.Sprintf(AdaptiveCardVersionTmpl, AdaptiveCardMaxVersion), + Body: []Element{ + textBlock, + }, + } + + if title != "" { + titleTextBlock := NewTitleTextBlock(title, wrap) + card.Body = append([]Element{titleTextBlock}, card.Body...) + } + + return card, nil +} + +// NewCard creates and returns an empty Card. +func NewCard() Card { + return Card{ + Type: TypeAdaptiveCard, + Schema: AdaptiveCardSchema, + Version: fmt.Sprintf(AdaptiveCardVersionTmpl, AdaptiveCardMaxVersion), + } +} + +// Attach receives and adds one or more Card values to the Attachments +// collection for a Microsoft Teams message. +// +// NOTE: Including multiple cards in the attachments collection *without* +// attachmentLayout set to "carousel" hides cards after the first. Not sure if +// this is a bug, or if it's intentional. +func (m *Message) Attach(cards ...Card) error { + if len(cards) == 0 { + return fmt.Errorf( + "received empty collection of cards: %w", + ErrMissingValue, + ) + } + + for _, card := range cards { + attachment := Attachment{ + ContentType: AttachmentContentType, + + // Explicitly convert Card to TopLevelCard in order to assert that + // TopLevelCard specific requirements are checked during + // validation. + Content: TopLevelCard{card}, + } + + m.Attachments = append(m.Attachments, attachment) + } + + return nil +} + +// Carousel sets the Message Attachment layout to Carousel display mode. +func (m *Message) Carousel() *Message { + m.AttachmentLayout = AttachmentLayoutCarousel + return m +} + +// PrettyPrint returns a formatted JSON payload of the Message if the +// Prepare() method has been called, or an empty string otherwise. +func (m *Message) PrettyPrint() string { + if m.payload != nil { + var prettyJSON bytes.Buffer + _ = json.Indent(&prettyJSON, m.payload.Bytes(), "", "\t") + + return prettyJSON.String() + } + + return "" +} + +// Prepare handles tasks needed to construct a payload from a Message for +// delivery to an endpoint. +func (m *Message) Prepare() error { + jsonMessage, err := json.Marshal(m) + if err != nil { + return fmt.Errorf( + "error marshalling Message to JSON: %w", + err, + ) + } + + switch { + case m.payload == nil: + m.payload = &bytes.Buffer{} + default: + m.payload.Reset() + } + + _, err = m.payload.Write(jsonMessage) + if err != nil { + return fmt.Errorf( + "error updating JSON payload for Message: %w", + err, + ) + } + + return nil +} + +// Payload returns the prepared Message payload. The caller should call +// Prepare() prior to calling this method, results are undefined otherwise. +func (m *Message) Payload() io.Reader { + return m.payload +} + +// Validate performs validation for Message using ValidateFunc if defined, +// otherwise applying default validation. +func (m Message) Validate() error { + if m.ValidateFunc != nil { + return m.ValidateFunc() + } + + v := validator.Validator{} + + v.FieldHasSpecificValue( + m.Type, + "type", + TypeMessage, + "message", + ErrInvalidType, + ) + + // We need an attachment (containing one or more Adaptive Cards) in order + // to generate a valid Message for Microsoft Teams delivery. + v.NotEmptyCollection("Attachments", m.Type, ErrMissingValue, m.Attachments) + + v.SelfValidate(Attachments(m.Attachments)) + + // Optional field, but only specific values permitted if set. + v.InListIfFieldValNotEmpty( + m.AttachmentLayout, + "AttachmentLayout", + "message", + supportedAttachmentLayoutValues(), + ErrInvalidFieldValue, + ) + + return v.Err() +} + +// Validate asserts that fields have valid values. +func (a Attachment) Validate() error { + v := validator.Validator{} + + v.FieldHasSpecificValue( + a.ContentType, + "attachment type", + AttachmentContentType, + "attachment", + ErrInvalidType, + ) + + v.SelfValidate(a.Content) + + return v.Err() +} + +// Validate asserts that the collection of Attachment values are all valid. +func (a Attachments) Validate() error { + for _, attachment := range a { + if err := attachment.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that fields have valid values. +func (c Card) Validate() error { + v := validator.Validator{} + + // TODO: Version field validation + // + // The Version field is required for top-level cards, optional for Cards + // nested within an Action.ShowCard. Because we don't have a reliable way + // to assert that relationship, we skip applying validation for that value + // for now. + + v.FieldHasSpecificValue( + c.Type, + "type", + TypeAdaptiveCard, + "card", + ErrInvalidType, + ) + + // While the schema value should be set it is not strictly required. If it + // is set, we assert that it is the correct value. + v.FieldHasSpecificValueIfFieldNotEmpty( + c.Schema, + "Schema", + AdaptiveCardSchema, + "card", + ErrInvalidFieldValue, + ) + + // Both are optional fields, unless MinHeight is set in which case + // VerticalContentAlignment is required. + v.SuccessfulFuncCall( + func() error { + return assertHeightAlignmentFieldsSetWhenRequired( + c.MinHeight, c.VerticalContentAlignment, + ) + }, + ) + + v.SuccessfulFuncCall( + func() error { + return assertCardBodyHasMention(c.Body, c.MSTeams.Entities) + }, + ) + + v.SelfValidate(Elements(c.Body)) + v.SelfValidate(Actions(c.Actions)) + + return v.Err() +} + +// Validate asserts that fields have valid values. +func (tc TopLevelCard) Validate() error { + v := validator.Validator{} + + // Validate embedded Card first as those validation requirements apply + // here also. + v.SelfValidate(tc.Card) + + // The Version field is required for top-level cards (this one), optional + // for Cards nested within an Action.ShowCard. + v.SuccessfulFuncCall( + func() error { return assertValidVersionFieldValue(tc.Version) }, + ) + + return v.Err() +} + +// Validate asserts that the collection of Element values are all valid. +func (e Elements) Validate() error { + for _, element := range e { + if err := element.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that fields have valid values. +func (e Element) Validate() error { + v := validator.Validator{} + + supportedElementTypes := supportedElementTypes() + supportedSizeValues := supportedSizeValues() + supportedWeightValues := supportedWeightValues() + supportedColorValues := supportedColorValues() + supportedSpacingValues := supportedSpacingValues() + supportedHorizontalAlignmentValues := supportedHorizontalAlignmentValues() + + // Valid Style field values differ based on type. For example, a Container + // element supports Container styles whereas a TextBlock supports a + // different and more limited set of style values. We use a helper + // function to retrieve valid style values for evaluation. + supportedStyleValues := supportedStyleValues(e.Type) + + /****************************************************************** + General requirements for all Element types. + ******************************************************************/ + + v.InListIfFieldValNotEmpty(e.Type, "Type", "element", supportedElementTypes, ErrInvalidType) + v.InListIfFieldValNotEmpty(e.Size, "Size", "element", supportedSizeValues, ErrInvalidFieldValue) + v.InListIfFieldValNotEmpty(e.Weight, "Weight", "element", supportedWeightValues, ErrInvalidFieldValue) + v.InListIfFieldValNotEmpty(e.Color, "Color", "element", supportedColorValues, ErrInvalidFieldValue) + v.InListIfFieldValNotEmpty(e.Spacing, "Spacing", "element", supportedSpacingValues, ErrInvalidFieldValue) + v.InListIfFieldValNotEmpty(e.HorizontalAlignment, "HorizontalAlignment", "element", supportedHorizontalAlignmentValues, ErrInvalidFieldValue) + v.InListIfFieldValNotEmpty(e.Style, "Style", "element", supportedStyleValues, ErrInvalidFieldValue) + + /****************************************************************** + Requirements for specific Element types. + ******************************************************************/ + + switch { + // The Text field is required by TextBlock and TextRun elements, but an + // empty string appears to be permitted. Because of this, we avoid + // asserting that a value is present for the field. + // case e.Type == TypeElementTextBlock: + // case e.Type == TypeElementTextRun: + + // Columns collection is used by the ColumnSet type. While not required, + // the collection should be checked. + case e.Type == TypeElementColumnSet: + v.SelfValidate(Columns(e.Columns)) + + if e.SelectAction != nil { + v.SelfValidate(e.SelectAction) + } + + // Actions collection is required for ActionSet element type. + // https://adaptivecards.io/explorer/ActionSet.html + case e.Type == TypeElementActionSet: + v.NotEmptyCollection("Actions", e.Type, ErrMissingValue, e.Actions) + v.SelfValidate(Actions(e.Actions)) + + // Items collection is required for Container element type. + // https://adaptivecards.io/explorer/Container.html + case e.Type == TypeElementContainer: + v.NotEmptyCollection("Items", e.Type, ErrMissingValue, e.Items) + v.SelfValidate(Elements(e.Items)) + + if e.SelectAction != nil { + v.SelfValidate(e.SelectAction) + } + + // URL is required for Image element type. + // https://adaptivecards.io/explorer/Image.html + case e.Type == TypeElementImage: + v.NotEmptyValue(e.URL, "URL", e.Type, ErrMissingValue) + + // Facts collection is required for FactSet element type. + // https://adaptivecards.io/explorer/FactSet.html + case e.Type == TypeElementFactSet: + v.NotEmptyCollection("Facts", e.Type, ErrMissingValue, e.Facts) + v.SelfValidate(Facts(e.Facts)) + + case e.Type == TypeElementTable: + v.InListIfFieldValNotEmpty( + e.GridStyle, + "GridStyle", + e.Type, + supportedContainerStyleValues(), + ErrInvalidFieldValue, + ) + + v.SelfValidate(TableRows(e.Rows)) + + v.SelfValidate(TableColumnDefinitions(e.Columns)) + + case e.Type == TypeElementMSTeamsCodeBlock: + v.NotEmptyValue(e.CodeSnippet, "CodeSnippet", e.Type, ErrMissingValue) + v.NotEmptyValue(e.Language, "Language", e.Type, ErrMissingValue) + } + + // Return the last recorded validation error, or nil if no validation + // errors occurred. + return v.Err() +} + +// Validate asserts that the collection of Column values are all valid. +func (c Columns) Validate() error { + for _, column := range c { + if err := column.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that the Items collection field for a column contains +// valid values. Special handling is applied since the collection could +// contain nil values. +func (ci ColumnItems) Validate() error { + for _, item := range ci { + if item == nil { + return fmt.Errorf( + "card element in Column is nil: %w", + ErrMissingValue, + ) + } + + if err := item.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that the collection of TableColumnDefinition values are +// all valid. +func (tcds TableColumnDefinitions) Validate() error { + for _, c := range tcds { + // We convert the Column type to a TableColumnDefinition so that + // fields specific to that "subtype" have separate validation logic + // applied vs the Column type used by the ColumnSet container type. + if err := TableColumnDefinition(c).Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that fields have valid values. +func (tcd TableColumnDefinition) Validate() error { + v := validator.Validator{} + + // The schema shows that this is supposed to be set to + // "TableColumnDefinition", though the example payload I reviewed did not + // set the Type field. Because of this, we should support either not + // setting the field at all OR requiring this specific type. + v.FieldHasSpecificValueIfFieldNotEmpty( + tcd.Type, + "type", + TypeTableColumnDefinition, + "column", + ErrInvalidType, + ) + + v.SuccessfulFuncCall( + func() error { return assertTableColumnDefinitionWidthValidValues(tcd) }, + ) + + v.InListIfFieldValNotEmpty( + tcd.VerticalCellContentAlignment, + "VerticalCellContentAlignment", + TypeTableColumnDefinition, + supportedVerticalContentAlignmentValues(), + ErrInvalidFieldValue, + ) + + v.InListIfFieldValNotEmpty( + tcd.HorizontalCellContentAlignment, + "HorizontalCellContentAlignment", + TypeTableColumnDefinition, + supportedHorizontalAlignmentValues(), + ErrInvalidFieldValue, + ) + + return v.Err() +} + +// Validate asserts that the collection of TableRow values are all valid. +func (trs TableRows) Validate() error { + for _, row := range trs { + if err := row.Validate(); err != nil { + return err + } + } + + return nil +} + +// AddCell adds one or many TableCell values to a TableRow. An error is +// returned if any TableCell value fails validation. +func (tr *TableRow) AddCell(cells ...TableCell) error { + if len(cells) == 0 { + return fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + for _, cell := range cells { + if err := cell.Validate(); err != nil { + return err + } + } + + tr.Cells = append(tr.Cells, cells...) + + return nil +} + +// // TableCells returns a collection of underlying TableCell pointers or an +// // empty collection if no TableCell values are available. +// func (trs *TableRows) TableCells() []*TableCell { +// if trs == nil { +// return []*TableCell{} +// } +// +// var numCells int +// for _, row := range *trs { +// for range row.Cells { +// numCells++ +// } +// } +// cells := make([]*TableCell, numCells) +// for _, row := range *trs { +// for i := range row.Cells { +// cells = append(cells, &row.Cells[i]) +// } +// } +// +// return cells +// } + +// Validate asserts that fields have valid values. +func (tr TableRow) Validate() error { + v := validator.Validator{} + + v.FieldHasSpecificValueIfFieldNotEmpty( + tr.Type, + "type", + TypeTableRow, + "table row", + ErrInvalidType, + ) + + v.InListIfFieldValNotEmpty( + tr.Style, + "Style", + TypeTableRow, + supportedContainerStyleValues(), + ErrInvalidFieldValue, + ) + + v.InListIfFieldValNotEmpty( + tr.VerticalCellContentAlignment, + "VerticalCellContentAlignment", + TypeTableRow, + supportedVerticalContentAlignmentValues(), + ErrInvalidFieldValue, + ) + + v.InListIfFieldValNotEmpty( + tr.HorizontalCellContentAlignment, + "HorizontalCellContentAlignment", + TypeTableRow, + supportedHorizontalAlignmentValues(), + ErrInvalidFieldValue, + ) + + // Validate collection by using "wrapper" type. + v.SelfValidate(TableCells(tr.Cells)) + + return v.Err() +} + +// Validate asserts that the collection of TableCell values are all valid. +func (tcs TableCells) Validate() error { + for _, cell := range tcs { + if err := cell.Validate(); err != nil { + return err + } + } + + return nil +} + +// AddElement adds one or many Element value pointers to a TableCell. An error +// is returned if any Element value fails validation. +func (tr *TableCell) AddElement(elements ...*Element) error { + if len(elements) == 0 { + return fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + for _, cell := range elements { + if cell == nil { + return fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + if err := cell.Validate(); err != nil { + return err + } + } + + tr.Items = append(tr.Items, elements...) + + return nil +} + +// Validate asserts that fields have valid values. +func (tr TableCell) Validate() error { + v := validator.Validator{} + + v.FieldHasSpecificValueIfFieldNotEmpty( + tr.Type, + "type", + TypeTableCell, + "table cell", + ErrInvalidType, + ) + + v.InListIfFieldValNotEmpty( + tr.Style, + "Style", + TypeTableCell, + supportedContainerStyleValues(), + ErrInvalidFieldValue, + ) + + v.SuccessfulFuncCall( + func() error { + return assertValidPixelSizeOrEmptyValue(tr.MinHeight) + }, + ) + + v.InListIfFieldValNotEmpty( + tr.VerticalContentAlignment, + "VerticalContentAlignment", + TypeTableCell, + supportedVerticalContentAlignmentValues(), + ErrInvalidFieldValue, + ) + + v.NotEmptyCollection( + "TableCellItems", + TypeTableCell, + ErrMissingValue, + tr.Items, + ) + + v.NoNilValuesInCollection( + "TableCellItems", + TypeTableCell, + ErrMissingValue, + tr.Items, + ) + + for _, item := range tr.Items { + v.SelfValidate(item) + } + + return v.Err() +} + +// AddSelectAction adds a given Action or ISelectAction value to the +// associated Column. This action will be invoked when the Column is +// tapped or selected. +// +// An error is returned if the given Action or ISelectAction value fails +// validation or if a value other than an Action or ISelectAction is provided. +func (c *Column) AddSelectAction(action interface{}) error { + switch v := action.(type) { + case Action: + // Perform manual conversion to the supported type. + selectAction := ISelectAction{ + Type: v.Type, + ID: v.ID, + Title: v.Title, + URL: v.URL, + Fallback: v.Fallback, + } + + // Don't touch the new TargetElements field unless the provided Action + // has specified values. + if len(v.TargetElements) > 0 { + selectAction.TargetElements = append( + selectAction.TargetElements, + v.TargetElements..., + ) + } + + c.SelectAction = &selectAction + + case ISelectAction: + c.SelectAction = &v + + // unsupported value provided + default: + return fmt.Errorf( + "error: unsupported value provided; "+ + " only Action or ISelectAction values are supported: %w", + ErrInvalidFieldValue, + ) + } + + return nil +} + +// Validate asserts that fields have valid values. +func (c Column) Validate() error { + v := validator.Validator{} + + v.FieldHasSpecificValue( + c.Type, + "type", + TypeColumn, + "column", + ErrInvalidType, + ) + + v.SuccessfulFuncCall( + func() error { return assertColumnWidthValidValues(c) }, + ) + + // Assert that the collection does not contain nil items. + v.NoNilValuesInCollection("Items", c.Type, ErrMissingValue, c.Items) + + // Convert []*Element to ColumnItems so that we can use its Validate() + // method to handle cases where nil values could be present in the + // collection. + v.SelfValidate(ColumnItems(c.Items)) + + if c.SelectAction != nil { + v.SelfValidate(c.SelectAction) + } + + return v.Err() +} + +// Validate asserts that the collection of Fact values are all valid. +func (f Facts) Validate() error { + for _, fact := range f { + if err := fact.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that fields have valid values. +func (f Fact) Validate() error { + v := validator.Validator{} + + v.NotEmptyValue(f.Title, "Title", "Fact", ErrMissingValue) + v.NotEmptyValue(f.Value, "Value", "Fact", ErrMissingValue) + + return v.Err() +} + +// Validate asserts that fields have valid values. +func (m MSTeams) Validate() error { + v := validator.Validator{} + + // If an optional width value is set, assert that it is a valid value. + v.InListIfFieldValNotEmpty( + m.Width, + "Width", + "MSTeams", + supportedMSTeamsWidthValues(), + ErrInvalidFieldValue, + ) + + v.SelfValidate(Mentions(m.Entities)) + + return v.Err() +} + +// Validate asserts that fields have valid values. +func (i ISelectAction) Validate() error { + supportedISelectActionValues := supportedISelectActionValues(AdaptiveCardMaxVersion) + fallbackValues := supportedActionFallbackValues(AdaptiveCardMaxVersion) + + v := validator.Validator{} + + // Some supportedISelectActionValues are restricted to later Adaptive Card + // schema versions. + v.InList( + i.Type, + "Type", + "ISelectAction", + supportedISelectActionValues, + ErrInvalidType, + ) + + v.InListIfFieldValNotEmpty( + i.Fallback, + "Fallback", + "ISelectAction", + supportedISelectActionFallbackValues(AdaptiveCardMaxVersion), + ErrInvalidFieldValue, + ) + + // See also: Action.Validate() logic. + switch { + case i.Type == TypeActionOpenURL: + v.NotEmptyValue(i.URL, "URL", i.Type, ErrMissingValue) + + case i.Fallback != "": + v.InList(i.Fallback, "Fallback", "action", fallbackValues, ErrInvalidFieldValue) + + case i.Type == TypeActionToggleVisibility: + v.NotEmptyCollection("TargetElements", i.Type, ErrMissingValue, i.TargetElements) + } + + return v.Err() +} + +// Validate asserts that the collection of Action values are all valid. +func (a Actions) Validate() error { + for _, action := range a { + if err := action.Validate(); err != nil { + return err + } + } + + return nil +} + +// AddTargetElement records the IDs from the given Elements in new +// TargetElement values. The specified visibility setting is used for the new +// TargetElement values. +// +// - If true, always show target Element. +// - If false, always hide target Element. +// - If nil, allow toggling target Element's visibility. +// +// If the given visibility setting is nil, then the visibility setting for the +// TargetElement values is omitted. This enables toggling visibility for the +// target Elements (e.g., toggle button behavior). +func (a *Action) AddTargetElement(visible *bool, elements ...Element) error { + elementIDs := make([]string, 0, len(elements)) + for _, e := range elements { + if strings.TrimSpace(e.ID) == "" { + return fmt.Errorf( + "given Element has empty ID value: %w", + ErrInvalidFieldValue, + ) + } + + elementIDs = append(elementIDs, e.ID) + } + + return a.AddTargetElementID(visible, elementIDs...) +} + +// AddVisibleTargetElement records the Element IDs from the given Elements in +// new TargetElement values. All new TargetElement values are explicitly set +// as visible. +func (a *Action) AddVisibleTargetElement(elements ...Element) error { + visible := true + + return a.AddTargetElement(&visible, elements...) +} + +// AddHiddenTargetElement records the Element IDs from the given Elements in +// new TargetElement values. All new TargetElement values are explicitly set +// as not visible. +func (a *Action) AddHiddenTargetElement(elements ...Element) error { + visible := false + + return a.AddTargetElement(&visible, elements...) +} + +// AddTargetElementID records the given Element ID values in the TargetElements +// collection. A non-empty ID value is required, but the Adaptive Card "tree" +// is not searched for a valid match; it is up to the caller to ensure that +// the given ID value is valid. +// +// The specified visibility setting is used for the new TargetElement values. +// +// - If true, always show target Element. +// - If false, always hide target Element. +// - If nil, allow toggling target Element's visibility. +// +// If the given visibility setting is nil, then the visibility setting for the +// TargetElement values is omitted. This enables toggling visibility for the +// target Elements (e.g., toggle button behavior). +func (a *Action) AddTargetElementID(visible *bool, elementIDs ...string) error { + for _, id := range elementIDs { + if strings.TrimSpace(id) == "" { + return fmt.Errorf( + "received empty Element ID value: %w", + ErrMissingValue, + ) + } + + existingElementIDs := func() []string { + ids := make([]string, 0, len(a.TargetElements)) + for _, targetElement := range a.TargetElements { + ids = append(ids, targetElement.ElementID) + } + + return ids + }() + + // Assert that the ID is not already in the collection. + if goteamsnotify.InList(id, existingElementIDs, false) { + return fmt.Errorf( + "received duplicate Element ID value %q: %w", + id, + ErrInvalidFieldValue, + ) + } + + a.TargetElements = append( + a.TargetElements, + TargetElement{ + ElementID: id, + Visible: visible, + }, + ) + } + + return nil +} + +// Validate asserts that fields have valid values. +func (a Action) Validate() error { + actionValues := supportedActionValues(AdaptiveCardMaxVersion) + fallbackValues := supportedActionFallbackValues(AdaptiveCardMaxVersion) + + v := validator.Validator{} + + // Some Actions are restricted to later Adaptive Card schema versions. + v.InList(a.Type, "Type", "action", actionValues, ErrInvalidType) + + switch { + case a.Type == TypeActionOpenURL: + v.NotEmptyValue(a.URL, "URL", a.Type, ErrMissingValue) + + case a.Fallback != "": + v.InList(a.Fallback, "Fallback", "action", fallbackValues, ErrInvalidFieldValue) + + case a.Type == TypeActionToggleVisibility: + v.NotEmptyCollection("TargetElements", a.Type, ErrMissingValue, a.TargetElements) + + // Optional, but only supported by the Action.ShowCard type. + case a.Card != nil: + v.FieldHasSpecificValue(a.Type, "type", TypeActionShowCard, "type", ErrInvalidType) + } + + // Return the last recorded validation error, or nil if no validation + // errors occurred. + return v.Err() +} + +// Validate asserts that the collection of Mention values are all valid. +func (m Mentions) Validate() error { + for _, mention := range m { + if err := mention.Validate(); err != nil { + return err + } + } + + return nil +} + +// Validate asserts that fields have valid values. +// +// Element.Validate() asserts that required Mention.Text content is found for +// each recorded user mention the Card.. +func (m Mention) Validate() error { + if m.Type != TypeMention { + return fmt.Errorf( + "invalid Mention type %q; expected %q: %w", + m.Type, + TypeMention, + ErrInvalidType, + ) + } + + if m.Text == "" { + return fmt.Errorf( + "required field Text is empty for Mention: %w", + ErrMissingValue, + ) + } + + return nil +} + +// Validate asserts that fields have valid values. +func (m Mentioned) Validate() error { + if m.ID == "" { + return fmt.Errorf( + "required field ID is empty: %w", + ErrMissingValue, + ) + } + + if m.Name == "" { + return fmt.Errorf( + "required field Name is empty: %w", + ErrMissingValue, + ) + } + + return nil +} + +// Mention uses the provided display name, ID and text values to add a new +// user Mention and TextBlock element to the first Card in the Message. +// +// If no Cards are yet attached to the Message, a new card is created using +// the Mention and TextBlock element. If specified, the new TextBlock element +// is added as the first element of the Card, otherwise it is added last. An +// error is returned if insufficient values are provided. +func (m *Message) Mention(prependElement bool, displayName string, id string, msgText string) error { + // NOTE: Rely on called functions to validate given arguments. + + switch { + // If no existing cards, add a new one. + case len(m.Attachments) == 0: + mentionCard, err := NewMentionCard(displayName, id, msgText) + if err != nil { + return err + } + + if err := m.Attach(mentionCard); err != nil { + return err + } + + // We have at least one Card already, use it. + default: + + // Build mention. + mention, err := NewMention(displayName, id) + if err != nil { + return fmt.Errorf( + "add new Mention to Message: %w", + err, + ) + } + + textBlock := Element{ + Type: TypeElementTextBlock, + + // TODO: Any issues caused by enabling wrapping? The goal is to + // prevent the Mention.Text content from pushing user specified + // text off of the Card, out of sight. + Wrap: true, + + // The text block contains the mention text string (required) and + // user-specified message text string. Use the mention text as a + // "greeting" or lead-in for the user-specified message text. + Text: mention.Text + " " + msgText, + } + + switch { + case prependElement: + m.Attachments[0].Content.Body = append( + []Element{textBlock}, + m.Attachments[0].Content.Body..., + ) + default: + m.Attachments[0].Content.Body = append( + m.Attachments[0].Content.Body, + textBlock, + ) + } + + m.Attachments[0].Content.MSTeams.Entities = append( + m.Attachments[0].Content.MSTeams.Entities, + mention, + ) + } + + return nil +} + +// Mention uses the given display name, ID and message text to add a new user +// Mention and TextBlock element to the Card. If specified, the new TextBlock +// element is added as the first element of the Card, otherwise it is added +// last. An error is returned if provided values are insufficient to create +// the user mention. +func (c *Card) Mention(displayName string, id string, msgText string, prependElement bool) error { + if msgText == "" { + return fmt.Errorf( + "required msgText argument is empty: %w", + ErrMissingValue, + ) + } + + // Rely on this called function to validate the other arguments. + mention, err := NewMention(displayName, id) + if err != nil { + return err + } + + textBlock := Element{ + Type: TypeElementTextBlock, + + // TODO: Any issues caused by enabling wrapping? The goal is to + // prevent the Mention.Text content from pushing user specified text + // off of the Card, out of sight. + Wrap: true, + Text: mention.Text + " " + msgText, + } + + switch { + case prependElement: + c.Body = append(c.Body, textBlock) + default: + c.Body = append([]Element{textBlock}, c.Body...) + } + + return nil +} + +// AddMention adds one or more provided user mentions to the associated Card +// along with a new TextBlock element. The Text field for the new TextBlock +// element is updated with the Mention Text. +// +// If specified, the new TextBlock element is inserted as the first element in +// the Card body. This effectively creates a dedicated TextBlock that acts as +// a "lead-in" or "announcement block" for other elements in the Card. If +// false, the newly created TextBlock is appended to the Card, effectively +// creating a "CC" list commonly found at the end of an email message. +// +// An error is returned if specified Mention values fail validation. +func (c *Card) AddMention(prepend bool, mentions ...Mention) error { + textBlock := Element{ + Type: TypeElementTextBlock, + + // The goal is to prevent the Mention.Text from extending off of the + // Card, out of sight. + Wrap: true, + } + + // Whether the mention text is prepended or appended doesn't matter since + // the TextBlock element we are adding is empty. Likewise, the separator + // chosen doesn't really matter either as there isn't any existing text + // that we need to separate from the mention text. + // + // NOTE: WE rely on this function to apply validation of user mention + // values instead of duplicating that logic here. + err := AddMention(c, &textBlock, true, defaultMentionTextSeparator, mentions...) + if err != nil { + return err + } + + switch prepend { + case true: + c.Body = append([]Element{textBlock}, c.Body...) + case false: + c.Body = append(c.Body, textBlock) + } + + return nil +} + +// AddElement adds one or more provided Elements to the Body of the associated +// Card. If specified, the Element values are prepended to the Card Body (as a +// contiguous set retaining current order), otherwise appended to the Card +// Body. +// +// An error is returned if specified Element values fail validation. +func (c *Card) AddElement(prepend bool, elements ...Element) error { + if len(elements) == 0 { + return fmt.Errorf( + "received empty collection of elements: %w", + ErrMissingValue, + ) + } + + // Validate first before adding to Card Body. + for _, element := range elements { + if err := element.Validate(); err != nil { + return err + } + } + + switch prepend { + case true: + c.Body = append(elements, c.Body...) + case false: + c.Body = append(c.Body, elements...) + } + + return nil +} + +// AddAction adds one or more provided Actions to the associated Card. If +// specified, the Action values are prepended to the Card (as a collection +// retaining current order), otherwise appended. +// +// NOTE: The max display limit for a Card's actions array has been observed to +// be a fixed value for web/desktop app and a matching value as an initial +// display limit for mobile app with the option to expand remaining actions in +// a list. +// +// This value is recorded in this package as "TeamsActionsDisplayLimit". +// +// Consider adding Action values to one or more ActionSet elements as needed +// and include within the Card.Body directly or within a Container to +// workaround this limit. +// +// An error is returned if specified Action values fail validation. +func (c *Card) AddAction(prepend bool, actions ...Action) error { + if len(actions) == 0 { + return fmt.Errorf( + "received empty collection of actions: %w", + ErrMissingValue, + ) + } + + for _, action := range actions { + if err := action.Validate(); err != nil { + return err + } + } + + switch prepend { + case true: + c.Actions = append(actions, c.Actions...) + case false: + c.Actions = append(c.Actions, actions...) + } + + return nil +} + +// GetElement searches all Element values attached to the Card for the +// specified ID (case sensitive). If found, a pointer to the Element is +// returned, otherwise an error is returned. +func (c *Card) GetElement(id string) (*Element, error) { + if id == "" { + return nil, fmt.Errorf( + "empty ID value specified: %w", + ErrMissingValue, + ) + } + + for _, element := range c.Body { + if element.ID == id { + return &element, nil + } + + // If the Element is a Container, we need to evaluate its collection + // of Elements. + for _, item := range element.Items { + if item.ID == id { + return &element, nil + } + } + } + + return nil, fmt.Errorf( + "unable to retrieve element id: %w", + ErrValueNotFound, + ) +} + +// AddFactSet adds one or more provided FactSet elements to the Body of the +// associated Card. If specified, the FactSet values are prepended to the Card +// Body (as a contiguous set retaining current order), otherwise appended to +// the Card Body. +// +// An error is returned if specified FactSet values fail validation. +// +// TODO: Is this needed? Should we even have a separate FactSet type that is +// so difficult to work with? +func (c *Card) AddFactSet(prepend bool, factsets ...FactSet) error { + if len(factsets) == 0 { + return fmt.Errorf( + "received empty collection of factsets: %w", + ErrMissingValue, + ) + } + + // Convert to base Element type + factsetElements := make([]Element, 0, len(factsets)) + for _, factset := range factsets { + element := Element(factset) + factsetElements = append(factsetElements, element) + } + + // Validate first before adding to Card Body. + for _, element := range factsetElements { + if err := element.Validate(); err != nil { + return err + } + } + + switch prepend { + case true: + c.Body = append(factsetElements, c.Body...) + case false: + c.Body = append(c.Body, factsetElements...) + } + + return nil +} + +// SetFullWidth enables full width display for the Card. +func (c *Card) SetFullWidth() { + c.MSTeams.Width = MSTeamsWidthFull +} + +// NewMention uses the given display name and ID to create a user Mention +// value for inclusion in a Card. An error is returned if provided values are +// insufficient to create the user mention. +func NewMention(displayName string, id string) (Mention, error) { + switch { + case displayName == "": + return Mention{}, fmt.Errorf( + "required name argument is empty: %w", + ErrMissingValue, + ) + + case id == "": + return Mention{}, fmt.Errorf( + "required id argument is empty: %w", + ErrMissingValue, + ) + + default: + + // Build mention. + mention := Mention{ + Type: TypeMention, + Text: fmt.Sprintf(MentionTextFormatTemplate, displayName), + Mentioned: Mentioned{ + ID: id, + Name: displayName, + }, + } + + return mention, nil + } +} + +// AddMention adds one or more provided user mentions to the specified Card. +// The Text field for the specified TextBlock element is updated with the +// Mention Text. If specified, the Mention Text is prepended, otherwise +// appended. If specified, a custom separator is used between the Mention Text +// and the TextBlock Text field, otherwise the default separator is used. +// +// NOTE: This function "registers" the specified Mention values with the Card +// and updates the specified textBlock element, however the caller is +// responsible for ensuring that the specified textBlock element is added to +// the Card. +// +// An error is returned if specified Mention values fail validation, or one of +// Card or Element pointers are null. +func AddMention(card *Card, textBlock *Element, prependText bool, separator string, mentions ...Mention) error { + if card == nil { + return fmt.Errorf( + "specified pointer to Card is nil: %w", + ErrMissingValue, + ) + } + + if textBlock == nil { + return fmt.Errorf( + "specified pointer to TextBlock element is nil: %w", + ErrMissingValue, + ) + } + + if textBlock.Type != TypeElementTextBlock { + return fmt.Errorf( + "invalid element type %q; expected %q: %w", + textBlock.Type, + TypeElementTextBlock, + ErrInvalidType, + ) + } + + if len(mentions) == 0 { + return fmt.Errorf( + "received empty collection of mentions: %w", + ErrMissingValue, + ) + } + + // Validate all user mentions before modifying Card or Element. + for _, mention := range mentions { + if err := mention.Validate(); err != nil { + return err + } + } + + if separator == "" { + separator = defaultMentionTextSeparator + } + + mentionsText := make([]string, 0, len(mentions)) + + // Record user mentions in the Card and collect all required user mention + // text values. + for _, mention := range mentions { + mentionsText = append(mentionsText, mention.Text) + card.MSTeams.Entities = append(card.MSTeams.Entities, mention) + } + + // Update TextBlock element text with required user mention text string. + switch prependText { + case true: + textBlock.Text = strings.Join(mentionsText, " ") + separator + textBlock.Text + case false: + textBlock.Text = textBlock.Text + separator + strings.Join(mentionsText, " ") + } + + // The original text may have been sufficiently short to not be truncated, + // but once we add the user mention text it is more likely that truncation + // could occur. Indicate that the text should be wrapped to avoid this. + textBlock.Wrap = true + + return nil +} + +// NewMentionMessage creates a new simple Message. Using the given message +// text, displayName and ID, a user Mention is also created and added to the +// new Message. An error is returned if provided values are insufficient to +// create the user mention. +func NewMentionMessage(displayName string, id string, msgText string) (*Message, error) { + msg := Message{ + Type: TypeMessage, + } + + // Rely on function to apply validation instead of duplicating it here. + mentionCard, err := NewMentionCard(displayName, id, msgText) + if err != nil { + return nil, err + } + + if err := msg.Attach(mentionCard); err != nil { + return nil, err + } + + return &msg, nil +} + +// NewMentionCard creates a new Card with user Mention using the given +// displayName, ID and message text. An error is returned if provided values +// are insufficient to create the user mention. +func NewMentionCard(displayName string, id string, msgText string) (Card, error) { + if msgText == "" { + return Card{}, fmt.Errorf( + "required msgText argument is empty: %w", + ErrMissingValue, + ) + } + + // Build mention. + mention, err := NewMention(displayName, id) + if err != nil { + return Card{}, err + } + + // Create basic card. + textCard, err := NewTextBlockCard(msgText, "", true) + if err != nil { + return Card{}, err + } + + // Update the text block so that it contains the mention text string + // (required) and user-specified message text string. Use the mention + // text as a "greeting" or lead-in for the user-specified message + // text. + textCard.Body[0].Text = mention.Text + + " " + textCard.Body[0].Text + + textCard.MSTeams.Entities = append( + textCard.MSTeams.Entities, + mention, + ) + + return textCard, nil +} + +// NewMessageFromCard is a helper function for creating a new Message based +// off of an existing Card value. +func NewMessageFromCard(card Card) (*Message, error) { + msg := Message{ + Type: TypeMessage, + } + + if err := msg.Attach(card); err != nil { + return nil, err + } + + return &msg, nil +} + +// NewContainer creates an empty Container. +func NewContainer() Container { + container := Container{ + Type: TypeElementContainer, + } + + return container +} + +// NewHiddenContainer creates an empty Container whose initial state is +// set as hidden from view. +func NewHiddenContainer() Container { + visible := false + container := Container{ + Type: TypeElementContainer, + Visible: &visible, + } + + return container +} + +// NewColumn creates an empty Column. +func NewColumn() Column { + column := Column{ + Type: TypeColumn, + } + + return column +} + +// NewColumnSet creates an empty Element of type ColumnSet. +func NewColumnSet() Element { + columnSet := Element{ + Type: TypeElementColumnSet, + } + + return columnSet +} + +// NewActionSet creates an empty ActionSet. +// +// TODO: Should we create a type alias for ActionSet, or keep it as a "base" +// Element type? +func NewActionSet() Element { + actionSet := Element{ + Type: TypeElementActionSet, + } + + return actionSet +} + +// NewTextBlock creates a new TextBlock element using the optional user +// specified Text. If specified, text wrapping is enabled. +func NewTextBlock(text string, wrap bool) Element { + textBlock := Element{ + Type: TypeElementTextBlock, + Wrap: wrap, + Text: text, + } + + return textBlock +} + +// NewHiddenTextBlock creates a new TextBlock element using the optional user +// specified Text. If specified, text wrapping is enabled. +// +// The new TextBlock is explicitly hidden from view. To view this Element, the +// caller should set an ID value and then allow toggling visibility by +// referencing this TextBlock's ID from a TargetElement associated with a +// ToggleVisibility Action. +func NewHiddenTextBlock(text string, wrap bool) Element { + isVisible := false + textBlock := Element{ + Type: TypeElementTextBlock, + Wrap: wrap, + Text: text, + Visible: &isVisible, + } + + return textBlock +} + +// NewTitleTextBlock uses the specified text to create a new TextBlock +// formatted as a "header" or "title" element. If specified, the TextBlock has +// text wrapping enabled. The effect is meant to emulate the visual effects of +// setting a MessageCard.Title field. +func NewTitleTextBlock(title string, wrap bool) Element { + return Element{ + Type: TypeElementTextBlock, + Wrap: wrap, + Text: title, + Style: TextBlockStyleHeading, + Size: SizeLarge, + Weight: WeightBolder, + } +} + +// NewTableCellsWithTextBlock accepts a collection of items that can be converted +// to string values and returns a collection of TableCells, each populated +// with a single TextBlock containing one of the given items. +// +// Example usage: +// +// vals := []int{1, 2, 3} +// items := make([]interface{}, len(vals)) +// +// for i := range vals { +// items[i] = vals[i] +// } +// +// tableCells := NewTextBlockTableCells(items) +func NewTableCellsWithTextBlock(items []interface{}) (TableCells, error) { + if len(items) == 0 { + return TableCells{}, fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + cells := make(TableCells, len(items)) + for i, item := range items { + switch { + // If an input item is nil, insert an empty table cell in its place. + case item == nil: + cell := TableCell{ + Type: TypeTableCell, + } + cells[i] = cell + default: + block := Element{ + Type: TypeElementTextBlock, + Text: fmt.Sprintf("%v", item), + } + cell := TableCell{ + Type: TypeTableCell, + Items: []*Element{&block}, + } + cells[i] = cell + } + } + + return cells, nil +} + +// NewTableRowFromCells accepts a collection of TableCell values and returns a +// TableRow populated with those TableCells. +func NewTableRowFromCells(cells ...TableCell) (TableRow, error) { + if len(cells) == 0 { + return TableRow{}, fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + if err := TableCells(cells).Validate(); err != nil { + return TableRow{}, err + } + + row := TableRow{ + Type: TypeTableRow, + Cells: cells, + } + + return row, nil +} + +// NewTable creates an empty Element of Table type. +func NewTable() Element { + table := Element{ + Type: TypeElementTable, + } + + return table +} + +// NewTableCellFromElement accepts an Element value and returns a TableCell +// populated with that Element. +func NewTableCellFromElement(element Element) (TableCell, error) { + if err := element.Validate(); err != nil { + return TableCell{}, err + } + + cell := TableCell{ + Type: TypeTableCell, + Items: []*Element{&element}, + } + + return cell, nil +} + +// NewTableCellFromElements accepts a collection of Element values and returns +// a TableCell populated with those Elements. +func NewTableCellFromElements(elements ...Element) (TableCell, error) { + if len(elements) == 0 { + return TableCell{}, fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + if err := Elements(elements).Validate(); err != nil { + return TableCell{}, err + } + + cellItems := make([]*Element, len(elements)) + for i := range elements { + cellItems[i] = &elements[i] + } + + cell := TableCell{ + Type: TypeTableCell, + Items: cellItems, + } + + return cell, nil +} + +// NewTableWithGridFromTableCells accepts a collection of TableCell values and +// the number of cells that should be inserted per table row. Header values +// are not inserted. +func NewTableWithGridFromTableCells(cells []TableCell, perRow int) (Element, error) { + switch { + case len(cells) == 0: + return Element{}, fmt.Errorf("no data provided: %w", ErrMissingValue) + + case perRow < 0: + return Element{}, fmt.Errorf("invalid per row value %d provided", perRow) + } + + if err := TableCells(cells).Validate(); err != nil { + return Element{}, err + } + + neededRows := func() int { + // d := float64(len(cells)) / float64(perRow) + // return int(math.Ceil(d)) + + d := len(cells) / perRow + + // Round up if the per row count doesn't divide evenly into the number + // of cells. This will leave us with a ragged, but valid number of + // cells per row. + if len(cells)%perRow > 0 { + d++ + } + return d + } + + table := Element{ + Type: TypeElementTable, + GridStyle: ContainerStyleAccent, + ShowGridLines: func() *bool { hasGridLines := true; return &hasGridLines }(), + FirstRowAsHeaders: func() *bool { hasHeaders := false; return &hasHeaders }(), + } + + // Add columns to table. + for i := 0; i < perRow; i++ { + c := Column{ + Type: TypeTableColumnDefinition, + Width: 1, + HorizontalCellContentAlignment: HorizontalAlignmentCenter, + VerticalCellContentAlignment: VerticalAlignmentCenter, + } + table.Columns = append(table.Columns, c) + } + + tableRows := make(TableRows, 0, neededRows()) + + // cellsChan := make(chan TableCell) + // go func() { + // for _, cell := range cells { + // cellsChan <- cell + // } + // close(cellsChan) + // }() + // + // for i := 0; i < neededRows(); i++ { + // tableCells := make([]TableCell, 0, perRow) + // for j := 0; j < perRow; j++ { + // cell := <-cellsChan + // tableCells = append(tableCells, cell) + // } + // + // tableRow := TableRow{ + // Type: TypeTableRow, + // Cells: tableCells, + // } + // + // tableRows = append(tableRows, tableRow) + // } + + // Opt for non-channel/non-goroutine implementation. + var cellCtr int + for i := 0; i < neededRows(); i++ { + tableCells := make([]TableCell, 0, perRow) + for j := 0; j < perRow; j++ { + cell := cells[cellCtr] + cellCtr++ + + tableCells = append(tableCells, cell) + } + + tableRow := TableRow{ + Type: TypeTableRow, + Cells: tableCells, + } + + tableRows = append(tableRows, tableRow) + } + + table.Rows = tableRows + + return table, nil +} + +// NewTableFromTableCells accepts a multidimensional collection of TableCell +// values, the number of columns that the table should have, a boolean value +// indicating whether the first row should be treated as a header row and +// another boolean value indicating whether grid lines should be displayed for +// the table. +// +// If the specified number of columns is zero then the number of columns will +// be calculated using the number of values in the first row. +// +// The outer slice is the collection of rows and the inner slice is the +// collection of values. The number of cells per row is determined by the +// number of cell values in that row. If a collection of values for a row is +// empty, an empty row is inserted into the generated table. +func NewTableFromTableCells(cells [][]TableCell, numColumns int, firstRowIsHeaders bool, showGridLines bool) (Element, error) { + if len(cells) == 0 { + return Element{}, fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + for _, row := range cells { + if err := TableCells(row).Validate(); err != nil { + return Element{}, err + } + } + + neededRows := len(cells) + neededColumns := func() int { + switch { + case numColumns == 0: + return len(cells[0]) + default: + return numColumns + } + } + + table := Element{ + Type: TypeElementTable, + GridStyle: ContainerStyleAccent, + ShowGridLines: &showGridLines, + FirstRowAsHeaders: &firstRowIsHeaders, + } + + // Add columns to table equal to the number of values in the first row. + for i := 0; i < neededColumns(); i++ { + c := Column{ + Type: TypeTableColumnDefinition, + Width: 1, + HorizontalCellContentAlignment: HorizontalAlignmentCenter, + VerticalCellContentAlignment: VerticalAlignmentCenter, + } + table.Columns = append(table.Columns, c) + } + + tableRows := make(TableRows, 0, neededRows) + for _, row := range cells { + var tableRow TableRow + // If our input row is empty, insert a cell with empty TextBlock in + // its place. + switch { + case len(row) == 0: + block := Element{ + Type: TypeElementTextBlock, + Text: "", + } + cell := TableCell{ + Type: TypeTableCell, + Items: []*Element{&block}, + } + tableRow = TableRow{ + Type: TypeTableRow, + Cells: []TableCell{cell}, + } + default: + tableRow = TableRow{ + Type: TypeTableRow, + Cells: row, + } + } + + tableRows = append(tableRows, tableRow) + } + + table.Rows = tableRows + + return table, nil +} + +// NewFactSet creates an empty FactSet. +func NewFactSet() FactSet { + factSet := FactSet{ + Type: TypeElementFactSet, + } + + return factSet +} + +// AddFact adds one or many Fact values to a FactSet. An error is returned if +// the Fact fails validation or if AddFact is called on an unsupported Element +// type. +func (fs *FactSet) AddFact(facts ...Fact) error { + // Fail early if called on the wrong Element type. + if fs.Type != TypeElementFactSet { + return fmt.Errorf( + "unsupported element type %s; expected %s: %w", + fs.Type, + TypeElementFactSet, + ErrInvalidType, + ) + } + + if len(facts) == 0 { + return fmt.Errorf( + "received empty collection of facts: %w", + ErrMissingValue, + ) + } + + // Validate all Fact values before adding them to the collection. + for _, fact := range facts { + if err := fact.Validate(); err != nil { + return err + } + } + + fs.Facts = append(fs.Facts, facts...) + + return nil +} + +// HasMentionText asserts that a supported Element type contains the required +// Mention text string necessary to link a user mention to a specific Element. +func (e Element) HasMentionText(m Mention) bool { + switch { + case e.Type == TypeElementTextBlock: + if strings.Contains(e.Text, m.Text) { + return true + } + return false + + case e.Type == TypeElementFactSet: + for _, fact := range e.Facts { + if strings.Contains(fact.Title, m.Text) || + strings.Contains(fact.Value, m.Text) { + + return true + } + } + return false + + default: + return false + } +} + +// AddTableRow adds one or many TableRow values to an Element of Table type. +// An error is returned if a TableRow value fails validation or if AddRow is +// called on any Element type other than a Table. +func (e *Element) AddTableRow(rows ...TableRow) error { + if e.Type != TypeElementTable { + return fmt.Errorf( + "unsupported element type %s; expected %s: %w", + e.Type, + TypeElementTable, + ErrInvalidType, + ) + } + + if len(rows) == 0 { + return fmt.Errorf("no data provided: %w", ErrMissingValue) + } + + e.Rows = append(e.Rows, rows...) + + return nil +} + +// NewActionOpenURL creates a new Action.OpenURL value using the provided URL +// and title. An error is returned if invalid values are supplied. +func NewActionOpenURL(url string, title string) (Action, error) { + // Accept the user-specified values as-is, use Validate() method to do the + // heavy lifting. + action := Action{ + Type: TypeActionOpenURL, + Title: title, + URL: url, + } + + err := action.Validate() + if err != nil { + return Action{}, err + } + + return action, nil +} + +// NewActionToggleVisibility creates a new Action.ToggleVisibility value using +// the (optionally) provided title text. +// +// NOTE: The caller is responsible for adding required TargetElement values to +// meet validation requirements. +func NewActionToggleVisibility(title string) Action { + return Action{ + Type: TypeActionToggleVisibility, + Title: title, + } +} + +// NewActionSetsFromActions creates a new ActionSet for every +// TeamsActionsDisplayLimit count of Actions given. An error is returned if +// the specified Actions do not pass validation. +func NewActionSetsFromActions(actions ...Action) ([]Element, error) { + if len(actions) == 0 { + return nil, fmt.Errorf( + "received empty collection of actions to create ActionSet: %w", + ErrMissingValue, + ) + } + + for _, action := range actions { + if err := action.Validate(); err != nil { + return nil, err + } + } + + // Create a new ActionSet for every TeamsActionsDisplayLimit count of + // Actions given. + actionSetsNeeded := int(math.Ceil(float64(len(actions)) / float64(TeamsActionsDisplayLimit))) + actionSets := make([]Element, 0, actionSetsNeeded) + + stride := TeamsActionsDisplayLimit + for i := 0; i < len(actions); i += stride { + // Ensure that we don't stride past the end of the actions slice. + if stride > len(actions)-i { + stride = len(actions) - i + } + + actionSetItems := actions[i : i+stride] + actionSet := Element{ + Type: TypeElementActionSet, + Actions: actionSetItems, + } + + actionSets = append(actionSets, actionSet) + } + + return actionSets, nil +} + +// AddElement adds the given Element to the collection of Element values in +// the container. If specified, the Element is inserted at the beginning of +// the collection, otherwise appended to the end. +func (c *Container) AddElement(prepend bool, element Element) error { + if err := element.Validate(); err != nil { + return err + } + + switch prepend { + case true: + c.Items = append([]Element{element}, c.Items...) + case false: + c.Items = append(c.Items, element) + } + + return nil +} + +// AddAction adds one or more provided Action values to the associated +// Container as one or more new ActionSets. The number of actions in each +// newly created ActionSet is limited to the number specified by +// TeamsActionsDisplayLimit. +// +// If specified, the newly created ActionSets are inserted before other +// Elements in the Container, otherwise appended. +// +// If adding an action to be used when the Container is tapped or selected use +// AddSelectAction() instead. +// +// An error is returned if specified Action values fail validation. +func (c *Container) AddAction(prepend bool, actions ...Action) error { + // Rely on function to apply validation instead of duplicating it here. + actionSets, err := NewActionSetsFromActions(actions...) + if err != nil { + return err + } + + switch prepend { + case true: + c.Items = append(actionSets, c.Items...) + case false: + c.Items = append(c.Items, actionSets...) + } + + return nil +} + +// AddSelectAction adds a given Action or ISelectAction value to the +// associated Container. This action will be invoked when the Container is +// tapped or selected. +// +// An error is returned if the given Action or ISelectAction value fails +// validation or if a value other than an Action or ISelectAction is provided. +func (c *Container) AddSelectAction(action interface{}) error { + switch v := action.(type) { + case Action: + // Perform manual conversion to the supported type. + selectAction := ISelectAction{ + Type: v.Type, + ID: v.ID, + Title: v.Title, + URL: v.URL, + Fallback: v.Fallback, + } + + // Don't touch the new TargetElements field unless the provided Action + // has specified values. + if len(v.TargetElements) > 0 { + selectAction.TargetElements = append( + selectAction.TargetElements, + v.TargetElements..., + ) + } + + c.SelectAction = &selectAction + + case ISelectAction: + c.SelectAction = &v + + // unsupported value provided + default: + return fmt.Errorf( + "error: unsupported value provided; "+ + " only Action or ISelectAction values are supported: %w", + ErrInvalidFieldValue, + ) + } + + return nil +} + +// AddContainer adds the given Container Element to the collection of Element +// values for the Card. If specified, the Container Element is inserted at the +// beginning of the collection, otherwise appended to the end. +func (c *Card) AddContainer(prepend bool, container Container) error { + element := Element(container) + + if err := element.Validate(); err != nil { + return err + } + + switch prepend { + case true: + c.Body = append([]Element{element}, c.Body...) + case false: + c.Body = append(c.Body, element) + } + + return nil +} + +// NewCodeBlock creates a new CodeBlock element with snippet, language, and +// optional firstLine. This is an MSTeams extension element. +// +// Supported languages include: +// +// - Bash +// - C +// - C# +// - C++ +// - CSS +// - DOS +// - Go +// - GraphQL +// - HTML +// - Java +// - JavaScript +// - JSON +// - Perl +// - PHP +// - PlainText +// - PowerShell +// - Python +// - SQL +// - TypeScript +// - Verilog +// - VHDL +// - Visual Basic +// - XML +// +// See +// https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format +// for additional languages that may be supported. +func NewCodeBlock(snippet string, language string, firstLine int) Element { + codeBlock := Element{ + Type: TypeElementMSTeamsCodeBlock, + CodeSnippet: snippet, + Language: language, + StartLineNumber: firstLine, + } + return codeBlock +} + +// cardBodyHasMention indicates whether an Adaptive Card body contains all +// specified Mention values. For every user mention, we require at least one +// match in an applicable Element in the Card Body. +func cardBodyHasMention(body []Element, mentions []Mention) bool { + // If the card body is empty, it cannot contain the required Mention values. + if body == nil { + return false + } + + elementsHaveMention := func(elements []Element, m Mention) bool { + for _, element := range elements { + if element.HasMentionText(m) { + return true + } + } + return false + } + + for _, mention := range mentions { + if !elementsHaveMention(body, mention) { + return false + } + } + + return true +} + +// assertHeightAlignmentFieldsSetWhenRequired asserts verticalContentAlignment +// is set when minHeight is set; while both are optional fields, both have to +// be set when the other is. +func assertHeightAlignmentFieldsSetWhenRequired(minHeight string, verticalContentAlignment string) error { + if minHeight != "" && verticalContentAlignment == "" { + return fmt.Errorf( + "field MinHeight is set, VerticalContentAlignment is not;"+ + " field VerticalContentAlignment is only optional when MinHeight"+ + " is not set: %w", + ErrMissingValue, + ) + } + + return nil +} + +// assertCardBodyHasMention asserts that if there are recorded user mentions, +// then Mention.Text is contained (substring match) within an applicable field +// of a supported Element of the Card Body. +// +// At present, this includes the Text field of a TextBlock Element or +// the Title or Value fields of a Fact from a FactSet. +// +// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#mention-support-within-adaptive-cards +func assertCardBodyHasMention(elements []Element, mentions []Mention) error { + // User mentions recorded, but no elements in Card Body to potentially + // contain required text string. + if len(mentions) > 0 && len(elements) == 0 { + return fmt.Errorf( + "user mention text not found in empty Card Body: %w", + ErrMissingValue, + ) + } + + // For every user mention, we require at least one match in an applicable + // Element in the Card Body. + if len(mentions) > 0 && !cardBodyHasMention(elements, mentions) { + return fmt.Errorf( + "user mention text not found in elements of Card Body: %w", + ErrMissingValue, + ) + } + + return nil +} + +func assertColumnWidthValidValues(c Column) error { + switch v := c.Width.(type) { + // Nothing to see here. + case nil: + + // Assert specific fixed keyword values, empty string or valid pixel + // width; all other values are invalid. + case string: + v = strings.TrimSpace(v) + + switch { + case v == ColumnWidthAuto: + case v == ColumnWidthStretch: + default: + if err := assertValidPixelSizeOrEmptyValue(v); err != nil { + return err + } + } + + // Number representing relative width of the column. + case int: + + // Unsupported value. + default: + return fmt.Errorf( + "invalid pixel width %q; "+ + "expected one of keywords %q, int value (e.g., %d) "+ + "or specific pixel width (e.g., %s): %w", + v, + strings.Join([]string{ + ColumnWidthAuto, + ColumnWidthStretch, + }, ","), + 1, + PixelSizeExample, + ErrInvalidFieldValue, + ) + } + + return nil +} + +func assertTableColumnDefinitionWidthValidValues(tcd TableColumnDefinition) error { + switch v := tcd.Width.(type) { + // Nothing to see here. + case nil: + + // Assert valid pixel width or empty string; all other values are invalid. + case string: + if err := assertValidPixelSizeOrEmptyValue(v); err != nil { + return err + } + + // Number representing relative width of the column. + case int: + + // Unsupported value. + default: + return fmt.Errorf( + "invalid pixel width %q; "+ + "expected int value (e.g., %d) "+ + "or specific pixel width (e.g., %s): %w", + v, + 1, + PixelSizeExample, + ErrInvalidFieldValue, + ) + } + + return nil +} + +func assertValidPixelSizeOrEmptyValue(val string) error { + val = strings.TrimSpace(val) + + // An empty string is a special case and is permitted to honor "optional" + // field value requirement. + if val == "" { + return nil + } + + matched, _ := regexp.MatchString(PixelSizeRegex, val) + + if !matched { + return fmt.Errorf( + "invalid pixel width %q; expected value in format %s: %w", + val, + PixelSizeExample, + ErrInvalidFieldValue, + ) + } + + // TODO: Apply validation to ensure that 0 is not given as a pixel size? + + return nil +} + +func assertValidVersionFieldValue(val string) error { + switch { + case strings.TrimSpace(val) == "": + return fmt.Errorf( + "required field Version is empty for top-level Card: %w", + ErrMissingValue, + ) + default: + // Assert that Version value can be converted to the expected format. + versionNum, err := strconv.ParseFloat(val, 64) + if err != nil { + return fmt.Errorf( + "value %q incompatible with Version field: %w", + val, + ErrInvalidFieldValue, + ) + } + + // This is a high confidence validation failure. + if versionNum < AdaptiveCardMinVersion { + return fmt.Errorf( + "unsupported version %q;"+ + " expected minimum value of %0.1f: %w", + val, + AdaptiveCardMinVersion, + ErrInvalidFieldValue, + ) + } + + // This is *NOT* a high confidence validation failure; it is likely + // that Microsoft Teams will gain support for future versions of the + // Adaptive Card greater than the current recorded max configured + // schema version. Because the max value constant is subject to fall + // out of sync (at least briefly), this is a risky assertion to make. + // + // if versionNum < AdaptiveCardMinVersion || versionNum > AdaptiveCardMaxVersion { + // return fmt.Errorf( + // "unsupported version %q;"+ + // " expected value between %0.1f and %0.1f: %w", + // tc.Version, + // AdaptiveCardMinVersion, + // AdaptiveCardMaxVersion, + // ErrInvalidFieldValue, + // ) + // } + } + + return nil +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/doc.go b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/doc.go new file mode 100644 index 000000000..1ad6ee10f --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/doc.go @@ -0,0 +1,31 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +/* +Package adaptivecard provides support for generating Microsoft Teams messages +using the Adaptive Card format. + +See the provided examples in this repo, the Godoc generated documentation at +https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2 and the following +resources for more information: + + - https://adaptivecards.io/explorer + - https://docs.microsoft.com/en-us/adaptive-cards/ + - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/getting-started + - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features + - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model + - https://docs.microsoft.com/en-us/adaptive-cards/getting-started/bots + - https://docs.microsoft.com/en-us/adaptive-cards/resources/principles + - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format + - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#mention-support-within-adaptive-cards + - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards + - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/what-are-cards + - https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using + - https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using#send-adaptive-cards-using-an-incoming-webhook + - https://stackoverflow.com/questions/50753072/microsoft-teams-webhook-generating-400-for-adaptive-card +*/ +package adaptivecard diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/format.go b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/format.go new file mode 100644 index 000000000..2a8c69677 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/format.go @@ -0,0 +1,73 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package adaptivecard + +import "strings" + +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#newlines-for-adaptive-cards +// - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features + +// Newline and break statement patterns stripped out of text content sent to +// Microsoft Teams (by request). +const ( + // CR LF \r\n (windows) + windowsEOLActual = "\r\n" + windowsEOLEscaped = `\r\n` + + // CF \r (mac) + macEOLActual = "\r" + macEOLEscaped = `\r` + + // LF \n (unix) + unixEOLActual = "\n" + unixEOLEscaped = `\n` + + // Used with MessageCard format to emulate newlines, incompatible with + // Adaptive Card format (displays as literal values). + breakStatement = "
" +) + +// ConvertEOL converts \r\n (windows), \r (mac) and \n (unix) into \n\n. +// +// This function is intended for processing text for use in an Adaptive Card +// TextBlock element. The goal is to provide spacing in rendered text display +// comparable to native display. +// +// NOTE: There are known discrepancies in the way that Microsoft Teams renders +// text in desktop, web and mobile, so even with using this helper function +// some differences are to be expected. +// +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#newlines-for-adaptive-cards +// - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features +func ConvertEOL(s string) string { + s = strings.ReplaceAll(s, windowsEOLEscaped, unixEOLActual+unixEOLActual) + s = strings.ReplaceAll(s, windowsEOLActual, unixEOLActual+unixEOLActual) + s = strings.ReplaceAll(s, macEOLActual, unixEOLActual+unixEOLActual) + s = strings.ReplaceAll(s, macEOLEscaped, unixEOLActual+unixEOLActual) + s = strings.ReplaceAll(s, unixEOLEscaped, unixEOLActual+unixEOLActual) + + return s +} + +// ConvertBreakToEOL converts
statements into \n\n to provide comparable +// spacing in Adaptive Card TextBlock elements. +// +// This function is intended for processing text for use in an Adaptive Card +// TextBlock element. The goal is to provide spacing in rendered text display +// comparable to native display. +// +// The primary use case of this function is to process text that was +// previously formatted in preparation for use in a MessageCard; the +// MessageCard format supports
statements for text spacing/formatting +// where the Adaptive Card format does not. +// +// - https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#newlines-for-adaptive-cards +// - https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features +func ConvertBreakToEOL(s string) string { + return strings.ReplaceAll(s, breakStatement, unixEOLActual+unixEOLActual) +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/getters.go b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/getters.go new file mode 100644 index 000000000..dbf56a6a4 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/getters.go @@ -0,0 +1,340 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package adaptivecard + +// supportedElementTypes returns a list of valid types for an Adaptive Card +// element used in Microsoft Teams messages. This list is intended to be used +// for validation and display purposes. +func supportedElementTypes() []string { + // TODO: Confirm whether all types are supported. + // + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards + // https://adaptivecards.io/explorer/AdaptiveCard.html + return []string{ + TypeElementActionSet, + TypeElementColumnSet, + TypeElementContainer, + TypeElementFactSet, + TypeElementImage, + TypeElementImageSet, + TypeElementInputChoiceSet, + TypeElementInputDate, + TypeElementInputNumber, + TypeElementInputText, + TypeElementInputTime, + TypeElementInputToggle, + TypeElementMedia, // Introduced in version 1.1 (TODO: Is this supported in Teams message?) + TypeElementRichTextBlock, + TypeElementTable, // Introduced in version 1.5 + TypeElementTextBlock, + TypeElementTextRun, + TypeElementMSTeamsCodeBlock, + } +} + +// supportedSizeValues returns a list of valid Size values for applicable +// Element types. This list is intended to be used for validation and display +// purposes. +func supportedSizeValues() []string { + // https://adaptivecards.io/explorer/TextBlock.html + return []string{ + SizeSmall, + SizeDefault, + SizeMedium, + SizeLarge, + SizeExtraLarge, + } +} + +// supportedWeightValues returns a list of valid Weight values for text in +// applicable Element types. This list is intended to be used for validation +// and display purposes. +func supportedWeightValues() []string { + // https://adaptivecards.io/explorer/TextBlock.html + return []string{ + WeightBolder, + WeightLighter, + WeightDefault, + } +} + +// supportedColorValues returns a list of valid Color values for text in +// applicable Element types. This list is intended to be used for validation +// and display purposes. +func supportedColorValues() []string { + // https://adaptivecards.io/explorer/TextBlock.html + return []string{ + ColorDefault, + ColorDark, + ColorLight, + ColorAccent, + ColorGood, + ColorWarning, + ColorAttention, + } +} + +// supportedSpacingValues returns a list of valid Spacing values for Element +// types. This list is intended to be used for validation and display +// purposes. +func supportedSpacingValues() []string { + // https://adaptivecards.io/explorer/TextBlock.html + return []string{ + SpacingDefault, + SpacingNone, + SpacingSmall, + SpacingMedium, + SpacingLarge, + SpacingExtraLarge, + SpacingPadding, + } +} + +// supportedHorizontalAlignmentValues returns a list of valid horizontal +// alignment values for supported container and text types. This list is +// intended to be used for validation and display purposes. +func supportedHorizontalAlignmentValues() []string { + // https://adaptivecards.io/explorer/Table.html + // https://adaptivecards.io/explorer/TextBlock.html + // https://adaptivecards.io/schemas/adaptive-card.json + return []string{ + HorizontalAlignmentLeft, + HorizontalAlignmentCenter, + HorizontalAlignmentRight, + } +} + +// supportedVerticalAlignmentValues returns a list of valid vertical content +// alignment values for supported container types. This list is intended to be +// used for validation and display purposes. +func supportedVerticalContentAlignmentValues() []string { + // https://adaptivecards.io/explorer/Table.html + // https://adaptivecards.io/schemas/adaptive-card.json + return []string{ + VerticalAlignmentTop, + VerticalAlignmentCenter, + VerticalAlignmentBottom, + } +} + +// supportedActionValues accepts a value indicating the maximum Adaptive Card +// schema version supported and returns a list of valid Action types. This +// list is intended to be used for validation and display purposes. +// +// NOTE: See also the supportedISelectActionValues() function. See ref links +// for unsupported Action types. +func supportedActionValues(version float64) []string { + // https://adaptivecards.io/explorer/AdaptiveCard.html + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + supportedValues := []string{ + TypeActionOpenURL, + TypeActionShowCard, + TypeActionToggleVisibility, + + // Action.Submit is not supported for Adaptive Cards in Incoming + // Webhooks. + // + // TypeActionSubmit, + } + + // Version 1.4 is when Action.Execute was introduced. + // + // Per this doc: + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + // + // the "Action.Execute" action is supported: + // + // "For Adaptive Cards in Incoming Webhooks, all native Adaptive Card + // schema elements, except Action.Submit, are fully supported. The + // supported actions are Action.OpenURL, Action.ShowCard, + // Action.ToggleVisibility, and Action.Execute." + if version >= ActionExecuteMinCardVersionRequired { + supportedValues = append(supportedValues, TypeActionExecute) + } + + return supportedValues +} + +// supportedISelectActionValues accepts a value indicating the maximum +// Adaptive Card schema version supported and returns a list of valid +// ISelectAction types. This list is intended to be used for validation and +// display purposes. +// +// NOTE: See also the supportedActionValues() function. See ref links for +// unsupported Action types. +func supportedISelectActionValues(version float64) []string { + // https://adaptivecards.io/explorer/Column.html + // https://adaptivecards.io/explorer/TableCell.html + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + supportedValues := []string{ + TypeActionOpenURL, + TypeActionToggleVisibility, + + // Action.Submit is not supported for Adaptive Cards in Incoming + // Webhooks. + // + // TypeActionSubmit, + + // Action.ShowCard is not a supported Action for selectAction fields + // (ISelectAction). + // + // TypeActionShowCard, + } + + // Version 1.4 is when Action.Execute was introduced. + // + // Per this doc: + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + // + // the "Action.Execute" action is supported: + // + // "For Adaptive Cards in Incoming Webhooks, all native Adaptive Card + // schema elements, except Action.Submit, are fully supported. The + // supported actions are Action.OpenURL, Action.ShowCard, + // Action.ToggleVisibility, and Action.Execute." + if version >= ActionExecuteMinCardVersionRequired { + supportedValues = append(supportedValues, TypeActionExecute) + } + + return supportedValues +} + +// supportedAttachmentLayoutValues returns a list of valid AttachmentLayout +// values for Message type. This list is intended to be used for validation +// and display purposes. +// +// NOTE: See also the supportedActionValues() function. +func supportedAttachmentLayoutValues() []string { + return []string{ + AttachmentLayoutList, + AttachmentLayoutCarousel, + } +} + +// supportedStyleValues returns a list of valid Style field values for the +// specified element type. This list is intended to be used for validation and +// display purposes. +func supportedStyleValues(elementType string) []string { + switch elementType { + case TypeElementColumnSet: + return supportedContainerStyleValues() + case TypeElementContainer: + return supportedContainerStyleValues() + case TypeElementTable: + return supportedContainerStyleValues() + case TypeElementImage: + return supportedImageStyleValues() + case TypeElementInputChoiceSet: + return supportedChoiceInputStyleValues() + case TypeElementInputText: + return supportedTextInputStyleValues() + case TypeElementTextBlock: + return supportedTextBlockStyleValues() + + // Unsupported element types are indicated by an explicit empty list. + default: + return []string{} + } +} + +// supportedImageStyleValues returns a list of valid Style field values for +// the Image element type. This list is intended to be used for validation and +// display purposes. +func supportedImageStyleValues() []string { + return []string{ + ImageStyleDefault, + ImageStylePerson, + } +} + +// supportedChoiceInputStyleValues returns a list of valid Style field values +// for ChoiceInput related element types (e.g., Input.ChoiceSet) This list is +// intended to be used for validation and display purposes. +func supportedChoiceInputStyleValues() []string { + return []string{ + ChoiceInputStyleCompact, + ChoiceInputStyleExpanded, + ChoiceInputStyleFiltered, + } +} + +// supportedTextInputStyleValues returns a list of valid Style field values +// for TextInput related element types (e.g., Input.Text) This list is +// intended to be used for validation and display purposes. +func supportedTextInputStyleValues() []string { + return []string{ + TextInputStyleText, + TextInputStyleTel, + TextInputStyleURL, + TextInputStyleEmail, + TextInputStylePassword, + } +} + +// supportedTextBlockStyleValues returns a list of valid Style field values +// for the TextBlock element type. This list is intended to be used for +// validation and display purposes. +func supportedTextBlockStyleValues() []string { + return []string{ + TextBlockStyleDefault, + TextBlockStyleHeading, + } +} + +// supportedContainerStyleValues returns a list of valid Style field values +// for Container types (e.g., Column, ColumnSet, Container). This list is +// intended to be used for validation and display purposes. +func supportedContainerStyleValues() []string { + return []string{ + ContainerStyleDefault, + ContainerStyleEmphasis, + ContainerStyleGood, + ContainerStyleAttention, + ContainerStyleWarning, + ContainerStyleAccent, + } +} + +// supportedMSTeamsWidthValues returns a list of valid Width field values for +// MSTeams type. This list is intended to be used for validation and display +// purposes. +func supportedMSTeamsWidthValues() []string { + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#full-width-adaptive-card + return []string{ + MSTeamsWidthFull, + } +} + +// supportedActionFallbackValues accepts a value indicating the maximum +// Adaptive Card schema version supported and returns a list of valid Action +// Fallback types. This list is intended to be used for validation and display +// purposes. +func supportedActionFallbackValues(version float64) []string { + // https://adaptivecards.io/explorer/Action.OpenUrl.html + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + supportedValues := supportedActionValues(version) + supportedValues = append(supportedValues, TypeFallbackOptionDrop) + + return supportedValues +} + +// supportedISelectActionFallbackValues accepts a value indicating the maximum +// Adaptive Card schema version supported and returns a list of valid +// ISelectAction Fallback types. This list is intended to be used for +// validation and display purposes. +func supportedISelectActionFallbackValues(version float64) []string { + // https://adaptivecards.io/explorer/Action.OpenUrl.html + // https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model + // https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference + supportedValues := supportedISelectActionValues(version) + supportedValues = append(supportedValues, TypeFallbackOptionDrop) + + return supportedValues +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/nullstring.go b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/nullstring.go new file mode 100644 index 000000000..57e644949 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/adaptivecard/nullstring.go @@ -0,0 +1,63 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package adaptivecard + +import ( + "encoding/json" + "strings" +) + +// Credit: +// +// These resources were used while developing the json.Marshaler and +// json.Unmarshler interface implementations used in this file: +// +// https://stackoverflow.com/questions/31048557/assigning-null-to-json-fields-instead-of-empty-strings +// https://stackoverflow.com/questions/25087960/json-unmarshal-time-that-isnt-in-rfc-3339-format/ + +// Add an "implements assertion" to fail the build if the json.Unmarshaler +// implementation isn't correct. +// +// This resolves the unparam linter error: +// (*NullString).UnmarshalJSON - result 0 (error) is always nil (unparam) +// +// https://github.com/mvdan/unparam/issues/52 +var _ json.Unmarshaler = (*NullString)(nil) + +// Perform similar "implements assertion" for the json.Marshaler interface. +var _ json.Marshaler = (*NullString)(nil) + +// NullString represents a string value used in component fields that may +// potentially be null in the input JSON feed. +type NullString string + +// MarshalJSON implements the json.Marshaler interface. This compliments the +// custom Unmarshaler implementation to handle potentially null component +// description field value. +func (ns NullString) MarshalJSON() ([]byte, error) { + if len(string(ns)) == 0 { + return []byte("null"), nil + } + + // NOTE: If we fail to convert the type, an infinite loop will occur. + return json.Marshal(string(ns)) +} + +// UnmarshalJSON implements the json.Unmarshaler interface to handle +// potentially null component description field value. +func (ns *NullString) UnmarshalJSON(data []byte) error { + str := string(data) + if str == "null" { + *ns = "" + return nil + } + + *ns = NullString(strings.Trim(str, "\"")) + + return nil +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/doc.go b/vendor/github.com/atc0005/go-teams-notify/v2/doc.go new file mode 100644 index 000000000..9d7d2048b --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/doc.go @@ -0,0 +1,39 @@ +// Copyright 2021 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +/* +Package goteamsnotify is used to send messages to a Microsoft Teams channel. + +# Project Home + +See our GitHub repo (https://github.com/atc0005/go-teams-notify) for the +latest code, to file an issue or submit improvements for review and potential +inclusion into the project. + +# Purpose + +Send messages to a Microsoft Teams channel. + +# Features + + - Submit messages to Microsoft Teams consisting of one or more sections, + Facts (key/value pairs), Actions or images (hosted externally) + - Support for MessageCard and Adaptive Card messages + - Support for Actions, allowing users to take quick actions within Microsoft + Teams + - Support for user mentions + - Configurable validation + - Configurable timeouts + - Configurable retry support + - Support for overriding the default http.Client + - Support for overriding the default project-specific user agent + +# Usage + +See our main README for supported settings and examples. +*/ +package goteamsnotify diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/format.go b/vendor/github.com/atc0005/go-teams-notify/v2/format.go new file mode 100644 index 000000000..d39371118 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/format.go @@ -0,0 +1,253 @@ +// Copyright 2021 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package goteamsnotify + +import ( + "bytes" + "encoding/json" + "errors" + "strings" +) + +///////////////////////////////////////////////////////////////////////// +// NOTE: The contents of this file are deprecated. See the Deprecated +// indicators in this file for intended replacements. +// +// Please submit a bug report if you find exported code in this file which +// does *not* already have a replacement elsewhere in this library. +///////////////////////////////////////////////////////////////////////// + +// Newline patterns stripped out of text content sent to Microsoft Teams (by +// request) and replacement break value used to provide equivalent formatting +// for MessageCard payloads in Microsoft Teams. +const ( + + // CR LF \r\n (windows) + windowsEOLActual = "\r\n" + windowsEOLEscaped = `\r\n` + + // CF \r (mac) + macEOLActual = "\r" + macEOLEscaped = `\r` + + // LF \n (unix) + unixEOLActual = "\n" + unixEOLEscaped = `\n` + + // Used by Teams to separate lines + breakStatement = "
" +) + +// Even though Microsoft Teams doesn't show the additional newlines, +// https://messagecardplayground.azurewebsites.net/ DOES show the results +// as a formatted code block. Including the newlines now is an attempt at +// "future proofing" the codeblock support in MessageCard values sent to +// Microsoft Teams. +const ( + + // msTeamsCodeBlockSubmissionPrefix is the prefix appended to text input + // to indicate that the text should be displayed as a codeblock by + // Microsoft Teams for MessageCard payloads. + msTeamsCodeBlockSubmissionPrefix string = "\n```\n" + // msTeamsCodeBlockSubmissionPrefix string = "```" + + // msTeamsCodeBlockSubmissionSuffix is the suffix appended to text input + // to indicate that the text should be displayed as a codeblock by + // Microsoft Teams for MessageCard payloads. + msTeamsCodeBlockSubmissionSuffix string = "```\n" + // msTeamsCodeBlockSubmissionSuffix string = "```" + + // msTeamsCodeSnippetSubmissionPrefix is the prefix appended to text input + // to indicate that the text should be displayed as a code formatted + // string of text by Microsoft Teams for MessageCard payloads. + msTeamsCodeSnippetSubmissionPrefix string = "`" + + // msTeamsCodeSnippetSubmissionSuffix is the suffix appended to text input + // to indicate that the text should be displayed as a code formatted + // string of text by Microsoft Teams for MessageCard payloads. + msTeamsCodeSnippetSubmissionSuffix string = "`" +) + +// TryToFormatAsCodeBlock acts as a wrapper for FormatAsCodeBlock. If an +// error is encountered in the FormatAsCodeBlock function, this function will +// return the original string, otherwise if no errors occur the newly formatted +// string will be returned. +// +// This function is intended for processing text intended for a MessageCard. +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +// +// Deprecated: use messagecard.TryToFormatAsCodeBlock instead. +func TryToFormatAsCodeBlock(input string) string { + result, err := FormatAsCodeBlock(input) + if err != nil { + logger.Printf("TryToFormatAsCodeBlock: error occurred when calling FormatAsCodeBlock: %v\n", err) + logger.Println("TryToFormatAsCodeBlock: returning original string") + return input + } + + logger.Println("TryToFormatAsCodeBlock: no errors occurred when calling FormatAsCodeBlock") + return result +} + +// TryToFormatAsCodeSnippet acts as a wrapper for FormatAsCodeSnippet. If an +// error is encountered in the FormatAsCodeSnippet function, this function +// will return the original string, otherwise if no errors occur the newly +// formatted string will be returned. +// +// This function is intended for processing text intended for a MessageCard. +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +// +// Deprecated: use messagecard.TryToFormatAsCodeSnippet instead. +func TryToFormatAsCodeSnippet(input string) string { + result, err := FormatAsCodeSnippet(input) + if err != nil { + logger.Printf("TryToFormatAsCodeSnippet: error occurred when calling FormatAsCodeBlock: %v\n", err) + logger.Println("TryToFormatAsCodeSnippet: returning original string") + return input + } + + logger.Println("TryToFormatAsCodeSnippet: no errors occurred when calling FormatAsCodeSnippet") + return result +} + +// FormatAsCodeBlock accepts an arbitrary string, quoted or not, and calls a +// helper function which attempts to format as a valid Markdown code block for +// submission to Microsoft Teams. +// +// This function is intended for processing text intended for a MessageCard. +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +// +// Deprecated: use messagecard.FormatAsCodeBlock instead. +func FormatAsCodeBlock(input string) (string, error) { + if input == "" { + return "", errors.New("received empty string, refusing to format") + } + + result, err := formatAsCode( + input, + msTeamsCodeBlockSubmissionPrefix, + msTeamsCodeBlockSubmissionSuffix, + ) + + return result, err +} + +// FormatAsCodeSnippet accepts an arbitrary string, quoted or not, and calls a +// helper function which attempts to format as a single-line valid Markdown +// code snippet for submission to Microsoft Teams. +// +// This function is intended for processing text intended for a MessageCard. +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +// +// Deprecated: use messagecard.FormatAsCodeSnippet instead. +func FormatAsCodeSnippet(input string) (string, error) { + if input == "" { + return "", errors.New("received empty string, refusing to format") + } + + result, err := formatAsCode( + input, + msTeamsCodeSnippetSubmissionPrefix, + msTeamsCodeSnippetSubmissionSuffix, + ) + + return result, err +} + +// formatAsCode is a helper function which accepts an arbitrary string, quoted +// or not, a desired prefix and a suffix for the string and attempts to format +// as a valid Markdown formatted code sample for submission to Microsoft +// Teams. This helper function is intended for processing text intended for a +// MessageCard. +// +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +func formatAsCode(input string, prefix string, suffix string) (string, error) { + var err error + var byteSlice []byte + + switch { + // required; protects against slice out of range panics + case input == "": + return "", errors.New("received empty string, refusing to format as code block") + + // If the input string is already valid JSON, don't double-encode and + // escape the content + case json.Valid([]byte(input)): + logger.Printf("formatAsCode: input string already valid JSON; input: %+v", input) + logger.Printf("formatAsCode: Calling json.RawMessage([]byte(input)); input: %+v", input) + + // FIXME: Is json.RawMessage() really needed if the input string is + // *already* JSON? https://golang.org/pkg/encoding/json/#RawMessage + // seems to imply a different use case. + byteSlice = json.RawMessage([]byte(input)) + // + // From light testing, it appears to not be necessary: + // + // logger.Printf("formatAsCode: Skipping json.RawMessage, converting string directly to byte slice; input: %+v", input) + // byteSlice = []byte(input) + + default: + logger.Printf("formatAsCode: input string not valid JSON; input: %+v", input) + logger.Printf("formatAsCode: Calling json.Marshal(input); input: %+v", input) + byteSlice, err = json.Marshal(input) + if err != nil { + return "", err + } + } + + logger.Println("formatAsCode: byteSlice as string:", string(byteSlice)) + + var prettyJSON bytes.Buffer + + logger.Println("formatAsCode: calling json.Indent") + err = json.Indent(&prettyJSON, byteSlice, "", "\t") + if err != nil { + return "", err + } + formattedJSON := prettyJSON.String() + + logger.Println("formatAsCode: Formatted JSON:", formattedJSON) + + // handle both cases: where the formatted JSON string was not wrapped with + // double-quotes and when it was + codeContentForSubmission := prefix + strings.Trim(formattedJSON, "\"") + suffix + + logger.Printf("formatAsCode: formatted JSON as-is:\n%s\n\n", formattedJSON) + logger.Printf("formatAsCode: formatted JSON wrapped with code prefix/suffix: \n%s\n\n", codeContentForSubmission) + + // err should be nil if everything worked as expected + return codeContentForSubmission, err +} + +// ConvertEOLToBreak converts \r\n (windows), \r (mac) and \n (unix) into
+// statements. +// +// This function is intended for processing text intended for a MessageCard. +// Using this helper function for text intended for an Adaptive Card is +// unsupported and unlikely to produce the desired results. +// +// Deprecated: use messagecard.ConvertEOLToBreak instead. +func ConvertEOLToBreak(s string) string { + logger.Printf("ConvertEOLToBreak: Received %#v", s) + + s = strings.ReplaceAll(s, windowsEOLActual, breakStatement) + s = strings.ReplaceAll(s, windowsEOLEscaped, breakStatement) + s = strings.ReplaceAll(s, macEOLActual, breakStatement) + s = strings.ReplaceAll(s, macEOLEscaped, breakStatement) + s = strings.ReplaceAll(s, unixEOLActual, breakStatement) + s = strings.ReplaceAll(s, unixEOLEscaped, breakStatement) + + logger.Printf("ConvertEOLToBreak: Returning %#v", s) + + return s +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/doc.go b/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/doc.go new file mode 100644 index 000000000..08e58013d --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/doc.go @@ -0,0 +1,18 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +/* +Package validator provides logic to assist with validation tasks. The logic is +designed so that each subsequent validation step short-circuits after the +first validation failure; only the first validation failure is reported. + +Credit to Fabrizio Milo for sharing the original implementation: + +- https://stackoverflow.com/a/23960293/903870 +- https://github.com/Mistobaan +*/ +package validator diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/validator.go b/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/validator.go new file mode 100644 index 000000000..0ed6f974b --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/internal/validator/validator.go @@ -0,0 +1,495 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package validator + +import ( + "fmt" + + goteamsnotify "github.com/atc0005/go-teams-notify/v2" +) + +// Validater is the interface shared by all supported types which provide +// validation of their fields. +type Validater interface { + Validate() error +} + +// Validator is used to perform validation of given values. Each validation +// method for this type is designed to exit early in order to preserve any +// prior validation failure. If a previous validation check failure occurred, +// the most recent validation check result will +// +// After performing a validation check, the caller is responsible for checking +// the result to determine if further validation checks should be performed. +// +// Heavily inspired by: https://stackoverflow.com/a/23960293/903870 +type Validator struct { + err error +} + +// hasNilValues is a helper function used to determine whether any items in +// the given collection are nil. +func hasNilValues(items []interface{}) bool { + for _, item := range items { + if item == nil { + return true + } + } + return false +} + +// SelfValidate asserts that each given item can self-validate. +// +// A true value is returned if the validation step passed. A false value is +// returned if this or a prior validation step failed. +func (v *Validator) SelfValidate(items ...Validater) bool { + if v.err != nil { + return false + } + for _, item := range items { + if err := item.Validate(); err != nil { + v.err = err + return false + } + } + return true +} + +// SelfValidateIfXEqualsY asserts that each given item can self-validate if +// value x is equal to y. +// +// A true value is returned if the validation step passed. A false value is +// returned false if this or a prior validation step failed. +func (v *Validator) SelfValidateIfXEqualsY(x string, y string, items ...Validater) bool { + if v.err != nil { + return false + } + + if x == y { + v.SelfValidate(items...) + } + + return true +} + +// FieldHasSpecificValue asserts that fieldVal is reqVal. fieldValDesc +// describes the field value being validated (e.g., "Type") and typeDesc +// describes the specific struct or value type whose field we are validating +// (e.g., "Element"). +// +// A true value is returned if the validation step passed. A false value is +// returned if this or a prior validation step failed. +func (v *Validator) FieldHasSpecificValue( + fieldVal string, + fieldValDesc string, + reqVal string, + typeDesc string, + baseErr error, +) bool { + + switch { + case v.err != nil: + return false + + case fieldVal != reqVal: + v.err = fmt.Errorf( + // "required %s is empty for %s: %w", + // "invalid card type %q; expected %q: %w", + "invalid %s %q for %s; expected %q: %w", + fieldValDesc, + fieldVal, + typeDesc, + reqVal, + baseErr, + ) + return false + + default: + return true + } +} + +// FieldHasSpecificValueIfFieldNotEmpty asserts that fieldVal is reqVal unless +// fieldVal is empty. fieldValDesc describes the field value being validated +// (e.g., "Type") and typeDesc describes the specific struct or value type +// whose field we are validating (e.g., "Element"). +// +// A true value is returned if the validation step passed. A false value is +// returned if this or a prior validation step failed. +func (v *Validator) FieldHasSpecificValueIfFieldNotEmpty( + fieldVal string, + fieldValDesc string, + reqVal string, + typeDesc string, + baseErr error, +) bool { + + switch { + case v.err != nil: + return false + + case fieldVal != "": + return v.FieldHasSpecificValue( + fieldVal, + fieldValDesc, + reqVal, + typeDesc, + baseErr, + ) + + default: + return true + } +} + +// NotEmptyValue asserts that fieldVal is not empty. fieldValDesc describes +// the field value being validated (e.g., "Type") and typeDesc describes the +// specific struct or value type whose field we are validating (e.g., +// "Element"). +// +// A true value is returned if the validation step passed. A false value is +// returned if this or a prior validation step failed. +func (v *Validator) NotEmptyValue(fieldVal string, fieldValDesc string, typeDesc string, baseErr error) bool { + if v.err != nil { + return false + } + if fieldVal == "" { + v.err = fmt.Errorf( + "required %s is empty for %s: %w", + fieldValDesc, + typeDesc, + baseErr, + ) + return false + } + return true +} + +// InList reports whether fieldVal is in validVals. fieldValDesc describes the +// field value being validated (e.g., "Type") and typeDesc describes the +// specific struct or value type whose field we are validating (e.g., +// "Element"). +// +// A true value is returned if fieldVal is is in validVals. +// +// A false value is returned if any of: +// - a prior validation step failed +// - fieldVal is empty +// - fieldVal is non-empty and not in validVals +// - the validVals collection to compare against is empty +func (v *Validator) InList(fieldVal string, fieldValDesc string, typeDesc string, validVals []string, baseErr error) bool { + switch { + case v.err != nil: + return false + + case fieldVal == "": + return false + + case !goteamsnotify.InList(fieldVal, validVals, false): + switch { + case len(validVals) == 0 && baseErr != nil: + v.err = fmt.Errorf( + "invalid %s %q for %s; empty list of valid values: %w", + fieldValDesc, + fieldVal, + typeDesc, + baseErr, + ) + case len(validVals) == 0: + v.err = fmt.Errorf( + "invalid %s %q for %s; no known valid values", + fieldValDesc, + fieldVal, + typeDesc, + ) + case baseErr != nil: + v.err = fmt.Errorf( + "invalid %s %q for %s; expected one of %v: %w", + fieldValDesc, + fieldVal, + typeDesc, + validVals, + baseErr, + ) + default: + v.err = fmt.Errorf( + "invalid %s %q for %s; expected one of %v", + fieldValDesc, + fieldVal, + typeDesc, + validVals, + ) + } + + return false + + // Validation is good. + default: + return true + } +} + +// InListIfFieldValNotEmpty reports whether fieldVal is in validVals if +// fieldVal is not empty. fieldValDesc describes the field value being +// validated (e.g., "Type") and typeDesc describes the specific struct or +// value type whose field we are validating (e.g., "Element"). +// +// A true value is returned if fieldVal is empty or is in validVals. +// +// A false value is returned if any of: +// - a prior validation step failed +// - fieldVal is not empty and is not in validVals +// - the validVals collection to compare against is empty +func (v *Validator) InListIfFieldValNotEmpty(fieldVal string, fieldValDesc string, typeDesc string, validVals []string, baseErr error) bool { + switch { + case v.err != nil: + return false + + case fieldVal != "" && !goteamsnotify.InList(fieldVal, validVals, false): + switch { + case len(validVals) == 0 && baseErr != nil: + v.err = fmt.Errorf( + "invalid %s %q for %s; empty list of valid values: %w", + fieldValDesc, + fieldVal, + typeDesc, + baseErr, + ) + case len(validVals) == 0: + v.err = fmt.Errorf( + "invalid %s %q for %s; no known valid values", + fieldValDesc, + fieldVal, + typeDesc, + ) + case baseErr != nil: + v.err = fmt.Errorf( + "invalid %s %q for %s; expected one of %v: %w", + fieldValDesc, + fieldVal, + typeDesc, + validVals, + baseErr, + ) + default: + v.err = fmt.Errorf( + "invalid %s %q for %s; expected one of %v", + fieldValDesc, + fieldVal, + typeDesc, + validVals, + ) + } + + return false + + // Validation is good. + default: + return true + } +} + +// FieldInListIfTypeValIs reports whether fieldVal is in validVals if fieldVal +// is not empty. fieldValDesc describes the field value being validated (e.g., +// "Type") and typeDesc describes the specific struct or value type whose +// field we are validating (e.g., "Element"). +// +// A true value is returned if fieldVal is empty or is in validVals. A false +// value is returned if a prior validation step failed or if fieldVal is not +// empty and is not in validVals. +// func (v *Validator) FieldInListIfTypeValIs( +// fieldVal string, +// fieldDesc string, +// typeVal string, +// typeDesc string, +// validVals []string, +// baseErr error, +// ) bool { +// switch { +// case v.err != nil: +// return false +// +// case fieldVal != "" && !goteamsnotify.InList(fieldVal, validVals, false): +// v.err = fmt.Errorf( +// "invalid %s %q for %s; expected one of %v", +// fieldValDesc, +// fieldVal, +// typeDesc, +// validVals, +// ) +// +// if baseErr != nil { +// v.err = fmt.Errorf( +// "invalid %s %q for %s; expected one of %v: %w", +// fieldValDesc, +// fieldVal, +// typeDesc, +// validVals, +// baseErr, +// ) +// } +// +// return false +// +// // Validation is good. +// default: +// return true +// } +// } + +// NotEmptyCollection asserts that the specified items collection is not +// empty. fieldValueDesc describes the field for this collection being +// validated (e.g., "Facts") and typeDesc describes the specific struct or +// value type whose field we are validating (e.g., "Element"). +// +// A true value is returned if the collection is not empty. A false value is +// returned if a prior validation step failed or if the items collection is +// empty. +func (v *Validator) NotEmptyCollection(fieldValueDesc string, typeDesc string, baseErr error, items ...interface{}) bool { + if v.err != nil { + return false + } + if len(items) == 0 { + switch { + case baseErr != nil: + v.err = fmt.Errorf( + "required %s collection is empty for %s: %w", + fieldValueDesc, + typeDesc, + baseErr, + ) + default: + v.err = fmt.Errorf( + "required %s collection is empty for %s", + fieldValueDesc, + typeDesc, + ) + } + + return false + } + return true +} + +// NoNilValuesInCollection asserts that the specified items collection does +// not contain any nil values. fieldValueDesc describes the field for this +// collection being validated (e.g., "Facts") and typeDesc describes the +// specific struct or value type whose field we are validating (e.g., +// "Element"). +// +// A true value is returned if the collection does not contain any nil values +// (even if the collection itself has no values). A false value is returned if +// a prior validation step failed or if any items in the collection are nil. +func (v *Validator) NoNilValuesInCollection(fieldValueDesc string, typeDesc string, baseErr error, items ...interface{}) bool { + if v.err != nil { + return false + } + + switch { + case hasNilValues(items): + switch { + case baseErr != nil: + v.err = fmt.Errorf( + "required %s collection contains nil values for %s: %w", + fieldValueDesc, + typeDesc, + baseErr, + ) + default: + v.err = fmt.Errorf( + "required %s collection contains nil values for for %s", + fieldValueDesc, + typeDesc, + ) + } + + return false + + default: + return true + } +} + +// NotEmptyCollectionIfFieldValNotEmpty asserts that the specified items +// collection is not empty if fieldVal is not empty. fieldValueDesc describes +// the field for this collection being validated (e.g., "Facts") and typeDesc +// describes the specific struct or value type whose field we are validating +// (e.g., "Element"). +// +// A true value is returned if the collection is not empty. A false value is +// returned if a prior validation step failed or if the items collection is +// empty. +func (v *Validator) NotEmptyCollectionIfFieldValNotEmpty( + fieldVal string, + fieldValueDesc string, + typeDesc string, + baseErr error, + items ...interface{}, +) bool { + + switch { + case v.err != nil: + return false + + case fieldVal != "" && len(items) == 0: + switch { + case baseErr != nil: + v.err = fmt.Errorf( + "required %s collection is empty for %s: %w", + fieldValueDesc, + typeDesc, + baseErr, + ) + default: + v.err = fmt.Errorf( + "required %s collection is empty for %s", + fieldValueDesc, + typeDesc, + ) + } + + return false + + default: + return true + } +} + +// SuccessfulFuncCall accepts fn, a function that returns an error. fn is +// called in order to determine validation results. +// +// A true value is returned if fn was successful. A false value is returned if +// a prior validation step failed or if fn returned an error. +func (v *Validator) SuccessfulFuncCall(fn func() error) bool { + if v.err != nil { + return false + } + + if err := fn(); err != nil { + v.err = err + return false + } + + return true +} + +// IsValid indicates whether validation checks performed thus far have all +// passed. +func (v *Validator) IsValid() bool { + return v.err != nil +} + +// Error returns the error string from the last recorded validation error. +func (v *Validator) Error() string { + return v.err.Error() +} + +// Err returns the last recorded validation error. +func (v *Validator) Err() error { + return v.err +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/messagecard.go b/vendor/github.com/atc0005/go-teams-notify/v2/messagecard.go new file mode 100644 index 000000000..52e0febe5 --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/messagecard.go @@ -0,0 +1,858 @@ +// Copyright 2020 Enrico Hoffmann +// Copyright 2021 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package goteamsnotify + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "strings" +) + +///////////////////////////////////////////////////////////////////////// +// NOTE: The contents of this file are deprecated. See the Deprecated +// indicators in this file for intended replacements. +// +// Please submit a bug report if you find exported code in this file which +// does *not* already have a replacement elsewhere in this library. +///////////////////////////////////////////////////////////////////////// + +const ( + // PotentialActionOpenURIType is the type that must be used for OpenUri + // potential action. + // + // Deprecated: use messagecard.PotentialActionOpenURIType instead. + PotentialActionOpenURIType = "OpenUri" + + // PotentialActionHTTPPostType is the type that must be used for HttpPOST + // potential action. + // + // Deprecated: use messagecard.PotentialActionHTTPPostType instead. + PotentialActionHTTPPostType = "HttpPOST" + + // PotentialActionActionCardType is the type that must be used for + // ActionCard potential action. + // + // Deprecated: use messagecard.PotentialActionActionCardType instead. + PotentialActionActionCardType = "ActionCard" + + // PotentialActionInvokeAddInCommandType is the type that must be used for + // InvokeAddInCommand potential action. + // + // Deprecated: use messagecard.PotentialActionInvokeAddInCommandType + // instead. + PotentialActionInvokeAddInCommandType = "InvokeAddInCommand" + + // PotentialActionActionCardInputTextInputType is the type that must be + // used for ActionCard TextInput type. + // + // Deprecated: use messagecard.PotentialActionActionCardInputTextInputType + // instead. + PotentialActionActionCardInputTextInputType = "TextInput" + + // PotentialActionActionCardInputDateInputType is the type that must be + // used for ActionCard DateInput type. + // + // Deprecated: use messagecard.PotentialActionActionCardInputDateInputType + // instead. + PotentialActionActionCardInputDateInputType = "DateInput" + + // PotentialActionActionCardInputMultichoiceInput is the type that must be + // used for ActionCard MultichoiceInput type. + // + // Deprecated: use + // messagecard.PotentialActionActionCardInputMultichoiceInputType instead. + PotentialActionActionCardInputMultichoiceInput = "MultichoiceInput" +) + +// PotentialActionMaxSupported is the maximum number of actions allowed in a +// MessageCardPotentialAction collection. +// +// https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference#actions +// +// Deprecated: use messagecard.PotentialActionMaxSupported instead. +const PotentialActionMaxSupported = 4 + +// ErrPotentialActionsLimitReached indicates that the maximum supported number +// of potentialAction collection values has been reached for either a +// MessageCard or a MessageCardSection. +// +// Deprecated: use messagecard.ErrPotentialActionsLimitReached instead. +var ErrPotentialActionsLimitReached = errors.New("potential actions collection limit reached") + +// MessageCardPotentialAction represents potential actions an user can do in a +// message card. See [Legacy actionable message card reference > Actions] for +// more information. +// +// Deprecated: use messagecard.PotentialAction instead. +// +// [Legacy actionable message card reference > Actions]: https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference#actions +type MessageCardPotentialAction struct { + // Type of the potential action. Can be OpenUri, HttpPOST, ActionCard or + // InvokeAddInCommand. + Type string `json:"@type"` + + // Name property defines the text that will be displayed on screen for the + // action. + Name string `json:"name"` + + // MessageCardPotentialActionOpenURI is a set of options for openUri + // potential action. + MessageCardPotentialActionOpenURI + + // MessageCardPotentialActionHTTPPOST is a set of options for httpPOST + // potential action. + MessageCardPotentialActionHTTPPOST + + // MessageCardPotentialActionActionCard is a set of options for actionCard + // potential action. + MessageCardPotentialActionActionCard + + // MessageCardPotentialActionInvokeAddInCommand is a set of options for + // invokeAddInCommand potential action. + MessageCardPotentialActionInvokeAddInCommand +} + +// MessageCardPotentialActionOpenURI represents a OpenUri potential action. +// +// Deprecated: use messagecard.PotentialActionOpenURI instead. +type MessageCardPotentialActionOpenURI struct { + // Targets is a collection of name/value pairs that defines one URI per + // target operating system. Only used for OpenUri action type. + Targets []MessageCardPotentialActionOpenURITarget `json:"targets,omitempty"` +} + +// MessageCardPotentialActionHTTPPOST represents a HttpPOST potential action. +// +// Deprecated: use messagecard.PotentialActionHTTPPOST instead. +type MessageCardPotentialActionHTTPPOST struct { + // Target defines the URL endpoint of the service that implements the + // action. Only used for HttpPOST action type. + Target string `json:"target,omitempty"` + + // Headers is a collection of MessageCardPotentialActionHeader objects + // representing a set of HTTP headers that will be emitted when sending + // the POST request to the target URL. Only used for HttpPOST action type. + Headers []MessageCardPotentialActionHTTPPOSTHeader `json:"headers,omitempty"` + + // Body is the body of the POST request. Only used for HttpPOST action + // type. + Body string `json:"body,omitempty"` + + // BodyContentType is optional and specifies the MIME type of the body in + // the POST request. Only used for HttpPOST action type. + BodyContentType string `json:"bodyContentType,omitempty"` +} + +// MessageCardPotentialActionActionCard represents an actionCard potential +// action. +// +// Deprecated: use messagecard.PotentialActionActionCard instead. +type MessageCardPotentialActionActionCard struct { + // Inputs is a collection of inputs an user can provide before processing + // the actions. Only used for ActionCard action type. Three types of + // inputs are available: TextInput, DateInput and MultichoiceInput + Inputs []MessageCardPotentialActionActionCardInput `json:"inputs,omitempty"` + + // Actions are the available actions. Only used for ActionCard action + // type. + Actions []MessageCardPotentialActionActionCardAction `json:"actions,omitempty"` +} + +// MessageCardPotentialActionActionCardAction is used for configuring +// ActionCard actions. +// +// Deprecated: use messagecard.PotentialActionActionCardAction +// instead. +type MessageCardPotentialActionActionCardAction struct { + // Type of the action. Can be OpenUri, HttpPOST, ActionCard or + // InvokeAddInCommand. + Type string `json:"@type"` + + // Name property defines the text that will be displayed on screen for the + // action. + Name string `json:"name"` + + // MessageCardPotentialActionOpenURI is used to specify a openUri action + // card's action. + MessageCardPotentialActionOpenURI + + // MessageCardPotentialActionHTTPPOST is used to specify a httpPOST action + // card's action. + MessageCardPotentialActionHTTPPOST +} + +// MessageCardPotentialActionInvokeAddInCommand represents an +// invokeAddInCommand potential action. +// +// Deprecated: use messagecard.PotentialActionInvokeAddInCommand +// instead. +type MessageCardPotentialActionInvokeAddInCommand struct { + // AddInID specifies the add-in ID of the required add-in. Only used for + // InvokeAddInCommand action type. + AddInID string `json:"addInId,omitempty"` + + // DesktopCommandID specifies the ID of the add-in command button that + // opens the required task pane. Only used for InvokeAddInCommand action + // type. + DesktopCommandID string `json:"desktopCommandId,omitempty"` + + // InitializationContext is an optional field which provides developers a + // way to specify any valid JSON object. The value is serialized into a + // string and made available to the add-in when the action is executed. + // This allows the action to pass initialization data to the add-in. Only + // used for InvokeAddInCommand action type. + InitializationContext interface{} `json:"initializationContext,omitempty"` +} + +// MessageCardPotentialActionOpenURITarget is used for OpenUri action type. +// It defines one URI per target operating system. +// +// Deprecated: use messagecard.PotentialActionOpenURITarget +// instead. +type MessageCardPotentialActionOpenURITarget struct { + // OS defines the operating system the target uri refers to. Supported + // operating system values are default, windows, iOS and android. The + // default operating system will in most cases simply open the URI in a + // web browser, regardless of the actual operating system. + OS string `json:"os,omitempty"` + + // URI defines the URI being called. + URI string `json:"uri,omitempty"` +} + +// MessageCardPotentialActionHTTPPOSTHeader defines a HTTP header used for +// HttpPOST action type. +// +// Deprecated: use messagecard.PotentialActionHTTPPOSTHeader +// instead. +type MessageCardPotentialActionHTTPPOSTHeader struct { + // Name is the header name. + Name string `json:"name,omitempty"` + + // Value is the header value. + Value string `json:"value,omitempty"` +} + +// MessageCardPotentialActionActionCardInput represents an ActionCard input. +// +// Deprecated: use messagecard.PotentialActionActionCardInput +// instead. +type MessageCardPotentialActionActionCardInput struct { + // Type of the ActionCard input. + // Must be either TextInput, DateInput or MultichoiceInput + Type string `json:"@type"` + + // ID uniquely identifies the input so it is possible to reference it in + // the URL or body of an HttpPOST action. + ID string `json:"id,omitempty"` + + // Title defines a title for the input. + Title string `json:"title,omitempty"` + + // Value defines the initial value of the input. For multi-choice inputs, + // value must be equal to the value property of one of the input's + // choices. + Value string `json:"value,omitempty"` + + // MessageCardPotentialActionInputMultichoiceInput must be defined for + // MultichoiceInput input type. + MessageCardPotentialActionActionCardInputMultichoiceInput + + // MessageCardPotentialActionInputTextInput must be defined for InputText + // input type. + MessageCardPotentialActionActionCardInputTextInput + + // MessageCardPotentialActionInputDateInput must be defined for DateInput + // input type. + MessageCardPotentialActionActionCardInputDateInput + + // IsRequired indicates whether users are required to type a value before + // they are able to take an action that would take the value of the input + // as a parameter. + IsRequired bool `json:"isRequired,omitempty"` +} + +// MessageCardPotentialActionActionCardInputTextInput represents a TextInput +// input used for potential action. +// +// Deprecated: use messagecard.PotentialActionActionCardInputTextInput +// instead. +type MessageCardPotentialActionActionCardInputTextInput struct { + // MaxLength indicates the maximum number of characters that can be + // entered. + MaxLength int `json:"maxLength,omitempty"` + + // IsMultiline indicates whether the text input should accept multiple + // lines of text. + IsMultiline bool `json:"isMultiline,omitempty"` +} + +// MessageCardPotentialActionActionCardInputMultichoiceInput represents a +// MultichoiceInput input used for potential action. +// +// Deprecated: use messagecard.PotentialActionActionCardInputMultichoiceInput +// instead. +type MessageCardPotentialActionActionCardInputMultichoiceInput struct { + // Choices defines the values that can be selected for the multichoice + // input. + Choices []struct { + Display string `json:"display,omitempty"` + Value string `json:"value,omitempty"` + } `json:"choices,omitempty"` + + // Style defines the style of the input. When IsMultiSelect is false, + // setting the style property to expanded will instruct the host + // application to try and display all choices on the screen, typically + // using a set of radio buttons. + Style string `json:"style,omitempty"` + + // IsMultiSelect indicates whether or not the user can select more than + // one choice. The specified choices will be displayed as a list of + // checkboxes. Default value is false. + IsMultiSelect bool `json:"isMultiSelect,omitempty"` +} + +// MessageCardPotentialActionActionCardInputDateInput represents a DateInput +// input used for potential action. +// +// Deprecated: use messagecard.PotentialActionActionCardInputDateInput +// instead. +type MessageCardPotentialActionActionCardInputDateInput struct { + // IncludeTime indicates whether the date input should allow for the + // selection of a time in addition to the date. + IncludeTime bool `json:"includeTime,omitempty"` +} + +// MessageCardSectionFact represents a section fact entry that is usually +// displayed in a two-column key/value format. +// +// Deprecated: use messagecard.SectionFact instead. +type MessageCardSectionFact struct { + + // Name is the key for an associated value in a key/value pair + Name string `json:"name"` + + // Value is the value for an associated key in a key/value pair + Value string `json:"value"` +} + +// MessageCardSectionImage represents an image as used by the heroImage and +// images properties of a section. +// +// Deprecated: use messagecard.SectionImage instead. +type MessageCardSectionImage struct { + + // Image is the URL to the image. + Image string `json:"image"` + + // Title is a short description of the image. Typically, this description + // is displayed in a tooltip as the user hovers their mouse over the + // image. + Title string `json:"title"` +} + +// MessageCardSection represents a section to include in a message card. +// +// Deprecated: use messagecard.Section instead. +type MessageCardSection struct { + // Title is the title property of a section. This property is displayed + // in a font that stands out, while not as prominent as the card's title. + // It is meant to introduce the section and summarize its content, + // similarly to how the card's title property is meant to summarize the + // whole card. + Title string `json:"title,omitempty"` + + // Text is the section's text property. This property is very similar to + // the text property of the card. It can be used for the same purpose. + Text string `json:"text,omitempty"` + + // ActivityImage is a property used to display a picture associated with + // the subject of a message card. For example, this might be the portrait + // of a person who performed an activity that the message card is + // associated with. + ActivityImage string `json:"activityImage,omitempty"` + + // ActivityTitle is a property used to summarize the activity associated + // with a message card. + ActivityTitle string `json:"activityTitle,omitempty"` + + // ActivitySubtitle is a property used to show brief, but extended + // information about an activity associated with a message card. Examples + // include the date and time the associated activity was taken or the + // handle of a person associated with the activity. + ActivitySubtitle string `json:"activitySubtitle,omitempty"` + + // ActivityText is a property used to provide details about the activity. + // For example, if the message card is used to deliver updates about a + // topic, then this property would be used to hold the bulk of the content + // for the update notification. + ActivityText string `json:"activityText,omitempty"` + + // HeroImage is a property that allows for setting an image as the + // centerpiece of a message card. This property can also be used to add a + // banner to the message card. + // Note: heroImage is not currently supported by Microsoft Teams + // https://stackoverflow.com/a/45389789 + // We use a pointer to this type in order to have the json package + // properly omit this field if not explicitly set. + // https://github.com/golang/go/issues/11939 + // https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go + // https://stackoverflow.com/questions/33447334/golang-json-marshal-how-to-omit-empty-nested-struct + HeroImage *MessageCardSectionImage `json:"heroImage,omitempty"` + + // Facts is a collection of MessageCardSectionFact values. A section entry + // usually is displayed in a two-column key/value format. + Facts []MessageCardSectionFact `json:"facts,omitempty"` + + // Images is a property that allows for the inclusion of a photo gallery + // inside a section. + // We use a slice of pointers to this type in order to have the json + // package properly omit this field if not explicitly set. + // https://github.com/golang/go/issues/11939 + // https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go + // https://stackoverflow.com/questions/33447334/golang-json-marshal-how-to-omit-empty-nested-struct + Images []*MessageCardSectionImage `json:"images,omitempty"` + + // PotentialActions is a collection of actions for a MessageCardSection. + // This is separate from the actions collection for the MessageCard. + PotentialActions []*MessageCardPotentialAction `json:"potentialAction,omitempty"` + + // Markdown represents a toggle to enable or disable Markdown formatting. + // By default, all text fields in a card and its sections can be formatted + // using basic Markdown. + Markdown bool `json:"markdown,omitempty"` + + // StartGroup is the section's startGroup property. This property marks + // the start of a logical group of information. Typically, sections with + // startGroup set to true will be visually separated from previous card + // elements. + StartGroup bool `json:"startGroup,omitempty"` +} + +// MessageCard represents a legacy actionable message card used via Office 365 +// or Microsoft Teams connectors. +// +// Deprecated: use messagecard.MessageCard instead. +type MessageCard struct { + // Required; must be set to "MessageCard" + Type string `json:"@type"` + + // Required; must be set to "https://schema.org/extensions" + Context string `json:"@context"` + + // Summary is required if the card does not contain a text property, + // otherwise optional. The summary property is typically displayed in the + // list view in Outlook, as a way to quickly determine what the card is + // all about. Summary appears to only be used when there are sections defined + Summary string `json:"summary,omitempty"` + + // Title is the title property of a card. is meant to be rendered in a + // prominent way, at the very top of the card. Use it to introduce the + // content of the card in such a way users will immediately know what to + // expect. + Title string `json:"title,omitempty"` + + // Text is required if the card does not contain a summary property, + // otherwise optional. The text property is meant to be displayed in a + // normal font below the card's title. Use it to display content, such as + // the description of the entity being referenced, or an abstract of a + // news article. + Text string `json:"text,omitempty"` + + // Specifies a custom brand color for the card. The color will be + // displayed in a non-obtrusive manner. + ThemeColor string `json:"themeColor,omitempty"` + + // ValidateFunc is a validation function that validates a MessageCard + ValidateFunc func() error `json:"-"` + + // Sections is a collection of sections to include in the card. + Sections []*MessageCardSection `json:"sections,omitempty"` + + // PotentialActions is a collection of actions for a MessageCard. + PotentialActions []*MessageCardPotentialAction `json:"potentialAction,omitempty"` + + // payload is a prepared MessageCard in JSON format for submission or + // pretty printing. + payload *bytes.Buffer `json:"-"` +} + +// validatePotentialAction inspects the given *MessageCardPotentialAction +// and returns an error if a value is missing or not known. +func validatePotentialAction(pa *MessageCardPotentialAction) error { + if pa == nil { + return fmt.Errorf("nil MessageCardPotentialAction received") + } + + switch pa.Type { + case PotentialActionOpenURIType, + PotentialActionHTTPPostType, + PotentialActionActionCardType, + PotentialActionInvokeAddInCommandType: + + default: + return fmt.Errorf("unknown type %s for potential action %s", pa.Type, pa.Name) + } + + if pa.Name == "" { + return fmt.Errorf("missing name value for MessageCardPotentialAction") + } + + return nil +} + +// addPotentialAction adds one or many MessageCardPotentialAction values to a +// PotentialActions collection. +func addPotentialAction(collection *[]*MessageCardPotentialAction, actions ...*MessageCardPotentialAction) error { + for _, a := range actions { + logger.Printf("addPotentialAction: MessageCardPotentialAction received: %+v\n", a) + + if err := validatePotentialAction(a); err != nil { + logger.Printf("addPotentialAction: validation failed: %v", err) + + return err + } + + if len(*collection) > PotentialActionMaxSupported { + logger.Printf("addPotentialAction: failed to add potential action: %v", ErrPotentialActionsLimitReached.Error()) + + return fmt.Errorf("func addPotentialAction: failed to add potential action: %w", ErrPotentialActionsLimitReached) + } + + *collection = append(*collection, a) + } + + return nil +} + +// AddSection adds one or many additional MessageCardSection values to a +// MessageCard. Validation is performed to reject invalid values with an error +// message. +// +// Deprecated: use (messagecard.MessageCard).AddSection instead. +func (mc *MessageCard) AddSection(section ...*MessageCardSection) error { + for _, s := range section { + logger.Printf("AddSection: MessageCardSection received: %+v\n", s) + + // bail if a completely nil section provided + if s == nil { + return fmt.Errorf("func AddSection: nil MessageCardSection received") + } + + // Perform validation of all MessageCardSection fields in an effort to + // avoid adding a MessageCardSection with zero value fields. This is + // done to avoid generating an empty sections JSON array since the + // Sections slice for the MessageCard type would technically not be at + // a zero value state. Due to this non-zero value state, the + // encoding/json package would end up including the Sections struct + // field in the output JSON. + // See also https://github.com/golang/go/issues/11939 + switch { + // If any of these cases trigger, skip over the `default` case + // statement and add the section. + case s.Images != nil: + case s.Facts != nil: + case s.HeroImage != nil: + case s.StartGroup: + case s.Markdown: + case s.ActivityText != "": + case s.ActivitySubtitle != "": + case s.ActivityTitle != "": + case s.ActivityImage != "": + case s.Text != "": + case s.Title != "": + + default: + logger.Println("AddSection: No cases matched, all fields assumed to be at zero-value, skipping section") + return fmt.Errorf("all fields found to be at zero-value, skipping section") + } + + logger.Println("AddSection: section contains at least one non-zero value, adding section") + mc.Sections = append(mc.Sections, s) + } + + return nil +} + +// AddPotentialAction adds one or many MessageCardPotentialAction values to a +// PotentialActions collection on a MessageCard. +// +// Deprecated: use (messagecard.MessageCard).AddPotentialAction instead. +func (mc *MessageCard) AddPotentialAction(actions ...*MessageCardPotentialAction) error { + return addPotentialAction(&mc.PotentialActions, actions...) +} + +// Validate validates a MessageCard calling ValidateFunc if defined, +// otherwise, a default validation occurs. +// +// Deprecated: use (messagecard.MessageCard).Validate instead. +func (mc *MessageCard) Validate() error { + if mc.ValidateFunc != nil { + return mc.ValidateFunc() + } + + // Falling back to a default implementation + if (mc.Text == "") && (mc.Summary == "") { + // This scenario results in: + // 400 Bad Request + // Summary or Text is required. + return fmt.Errorf("invalid message card: summary or text field is required") + } + + return nil +} + +// Prepare handles tasks needed to construct a payload from a MessageCard for +// delivery to an endpoint. +// +// Deprecated: use (messagecard.MessageCard).Prepare instead. +func (mc *MessageCard) Prepare() error { + jsonMessage, err := json.Marshal(mc) + if err != nil { + return fmt.Errorf( + "error marshalling MessageCard to JSON: %w", + err, + ) + } + + switch { + case mc.payload == nil: + mc.payload = &bytes.Buffer{} + default: + mc.payload.Reset() + } + + _, err = mc.payload.Write(jsonMessage) + if err != nil { + return fmt.Errorf( + "error updating JSON payload for MessageCard: %w", + err, + ) + } + + return nil +} + +// Payload returns the prepared MessageCard payload. The caller should call +// Prepare() prior to calling this method, results are undefined otherwise. +// +// Deprecated: use (messagecard.MessageCard).Payload instead. +func (mc *MessageCard) Payload() io.Reader { + return mc.payload +} + +// PrettyPrint returns a formatted JSON payload of the MessageCard if the +// Prepare() method has been called, or an empty string otherwise. +// +// Deprecated: use (messagecard.MessageCard).PrettyPrint instead. +func (mc *MessageCard) PrettyPrint() string { + if mc.payload != nil { + var prettyJSON bytes.Buffer + _ = json.Indent(&prettyJSON, mc.payload.Bytes(), "", "\t") + + return prettyJSON.String() + } + + return "" +} + +// AddFact adds one or many additional MessageCardSectionFact values to a +// MessageCardSection. +// +// Deprecated: use (messagecard.Section).AddFact instead. +func (mcs *MessageCardSection) AddFact(fact ...MessageCardSectionFact) error { + for _, f := range fact { + logger.Printf("AddFact: MessageCardSectionFact received: %+v\n", f) + + if f.Name == "" { + return fmt.Errorf("empty Name field received for new fact: %+v", f) + } + + if f.Value == "" { + return fmt.Errorf("empty Value field received for new fact: %+v", f) + } + } + + logger.Println("AddFact: section fact contains at least one non-zero value, adding section fact") + mcs.Facts = append(mcs.Facts, fact...) + + return nil +} + +// AddFactFromKeyValue accepts a key and slice of values and converts them to +// MessageCardSectionFact values. +// +// Deprecated: use (messagecard.Section).AddFactFromKeyValue +// instead. +func (mcs *MessageCardSection) AddFactFromKeyValue(key string, values ...string) error { + // validate arguments + + if key == "" { + return errors.New("empty key received for new fact") + } + + if len(values) < 1 { + return errors.New("no values received for new fact") + } + + fact := MessageCardSectionFact{ + Name: key, + Value: strings.Join(values, ", "), + } + // TODO: Explicitly define or use constructor? + // fact := NewMessageCardSectionFact() + // fact.Name = key + // fact.Value = strings.Join(values, ", ") + + mcs.Facts = append(mcs.Facts, fact) + + // if we made it this far then all should be well + return nil +} + +// AddPotentialAction adds one or many MessageCardPotentialAction values to a +// PotentialActions collection on a MessageCardSection. This is separate from +// the actions collection for the MessageCard. +// +// Deprecated: use (messagecard.Section).AddPotentialAction +// instead. +func (mcs *MessageCardSection) AddPotentialAction(actions ...*MessageCardPotentialAction) error { + return addPotentialAction(&mcs.PotentialActions, actions...) +} + +// AddImage adds an image to a MessageCard section. These images are used to +// provide a photo gallery inside a MessageCard section. +// +// Deprecated: use (messagecard.Section).AddImage instead. +func (mcs *MessageCardSection) AddImage(sectionImage ...MessageCardSectionImage) error { + for i := range sectionImage { + if sectionImage[i].Image == "" { + return fmt.Errorf("cannot add empty image URL") + } + + if sectionImage[i].Title == "" { + return fmt.Errorf("cannot add empty image title") + } + + mcs.Images = append(mcs.Images, §ionImage[i]) + } + + return nil +} + +// AddHeroImageStr adds a Hero Image to a MessageCard section using string +// arguments. This image is used as the centerpiece or banner of a message +// card. +// +// Deprecated: use (messagecard.Section).AddHeroImageStr instead. +func (mcs *MessageCardSection) AddHeroImageStr(imageURL string, imageTitle string) error { + if imageURL == "" { + return fmt.Errorf("cannot add empty hero image URL") + } + + if imageTitle == "" { + return fmt.Errorf("cannot add empty hero image title") + } + + heroImage := MessageCardSectionImage{ + Image: imageURL, + Title: imageTitle, + } + // TODO: Explicitly define or use constructor? + // heroImage := NewMessageCardSectionImage() + // heroImage.Image = imageURL + // heroImage.Title = imageTitle + + mcs.HeroImage = &heroImage + + // our validation checks didn't find any problems + return nil +} + +// AddHeroImage adds a Hero Image to a MessageCard section using a +// MessageCardSectionImage argument. This image is used as the centerpiece or +// banner of a message card. +// +// Deprecated: use (messagecard.Section).AddHeroImage instead. +func (mcs *MessageCardSection) AddHeroImage(heroImage MessageCardSectionImage) error { + if heroImage.Image == "" { + return fmt.Errorf("cannot add empty hero image URL") + } + + if heroImage.Title == "" { + return fmt.Errorf("cannot add empty hero image title") + } + + mcs.HeroImage = &heroImage + + // our validation checks didn't find any problems + return nil +} + +// NewMessageCard creates a new message card with fields required by the +// legacy message card format already predefined. +// +// Deprecated: use messagecard.NewMessageCard instead. +func NewMessageCard() MessageCard { + // define expected values to meet Office 365 Connector card requirements + // https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference#card-fields + msgCard := MessageCard{ + Type: "MessageCard", + Context: "https://schema.org/extensions", + } + + return msgCard +} + +// NewMessageCardSection creates an empty message card section. +// +// Deprecated: use messagecard.NewMessageCardSection instead. +func NewMessageCardSection() *MessageCardSection { + msgCardSection := MessageCardSection{} + return &msgCardSection +} + +// NewMessageCardSectionFact creates an empty message card section fact. +// +// Deprecated: use messagecard.NewMessageCardSectionFact instead. +func NewMessageCardSectionFact() MessageCardSectionFact { + msgCardSectionFact := MessageCardSectionFact{} + return msgCardSectionFact +} + +// NewMessageCardSectionImage creates an empty image for use with message card +// section. +// +// Deprecated: use messagecard.NewMessageCardSectionImage instead. +func NewMessageCardSectionImage() MessageCardSectionImage { + msgCardSectionImage := MessageCardSectionImage{} + return msgCardSectionImage +} + +// NewMessageCardPotentialAction creates a new MessageCardPotentialAction +// using the provided potential action type and name. The name value defines +// the text that will be displayed on screen for the action. An error is +// returned if invalid values are supplied. +// +// Deprecated: use messagecard.NewMessageCardPotentialAction instead. +func NewMessageCardPotentialAction(potentialActionType string, name string) (*MessageCardPotentialAction, error) { + pa := MessageCardPotentialAction{ + Type: potentialActionType, + Name: name, + } + + if err := validatePotentialAction(&pa); err != nil { + return nil, err + } + + return &pa, nil +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/send.go b/vendor/github.com/atc0005/go-teams-notify/v2/send.go new file mode 100644 index 000000000..abea4d87d --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/send.go @@ -0,0 +1,665 @@ +// Copyright 2020 Enrico Hoffmann +// Copyright 2021 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package goteamsnotify + +import ( + "context" + "errors" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "os" + "regexp" + "strings" + "time" +) + +// logger is a package logger that can be enabled from client code to allow +// logging output from this package when desired/needed for troubleshooting +var logger *log.Logger + +// Known webhook URL prefixes for submitting messages to Microsoft Teams +const ( + WebhookURLOfficecomPrefix = "https://outlook.office.com" + WebhookURLOffice365Prefix = "https://outlook.office365.com" + WebhookURLOrgWebhookPrefix = "https://example.webhook.office.com" +) + +// Known Workflow URL patterns for submitting messages to Microsoft Teams. +const ( + WorkflowURLBaseDomain = `^https:\/\/(?:.*)(:?\.azure-api|logic\.azure|api\.powerplatform)\.(?:com|net)` +) + +// DisableWebhookURLValidation is a special keyword used to indicate to +// validation function(s) that webhook URL validation should be disabled. +// +// Deprecated: prefer using API.SkipWebhookURLValidationOnSend(bool) method instead +const DisableWebhookURLValidation string = "DISABLE_WEBHOOK_URL_VALIDATION" + +// Regular Expression related constants that we can use to validate incoming +// webhook URLs provided by the user. +const ( + + // DefaultWebhookURLValidationPattern is a minimal regex for matching known valid + // webhook URL prefix patterns. + DefaultWebhookURLValidationPattern = `^https:\/\/(?:.*\.webhook|outlook)\.office(?:365)?\.com` + + // Note: The regex allows for capital letters in the GUID patterns. This is + // allowed based on light testing which shows that mixed case works and the + // assumption that since Teams and Office 365 are Microsoft products case + // would be ignored (e.g., Windows, IIS do not consider 'A' and 'a' to be + // different). + // webhookURLRegex = `^https:\/\/(?:.*\.webhook|outlook)\.office(?:365)?\.com\/webhook(?:b2)?\/[-a-zA-Z0-9]{36}@[-a-zA-Z0-9]{36}\/IncomingWebhook\/[-a-zA-Z0-9]{32}\/[-a-zA-Z0-9]{36}$` + + // webhookURLSubURIWebhookPrefix = "webhook" + // webhookURLSubURIWebhookb2Prefix = "webhookb2" + // webhookURLOfficialDocsSampleURI = "a1269812-6d10-44b1-abc5-b84f93580ba0@9e7b80c7-d1eb-4b52-8582-76f921e416d9/IncomingWebhook/3fdd6767bae44ac58e5995547d66a4e4/f332c8d9-3397-4ac5-957b-b8e3fc465a8c" +) + +// ExpectedWebhookURLResponseText represents the expected response text +// provided by the remote webhook endpoint when submitting messages. +const ExpectedWebhookURLResponseText string = "1" + +// DefaultWebhookSendTimeout specifies how long the message operation may take +// before it times out and is cancelled. +const DefaultWebhookSendTimeout = 5 * time.Second + +// DefaultUserAgent is the project-specific user agent used when submitting +// messages unless overridden by client code. This replaces the Go default +// user agent value of "Go-http-client/1.1". +// +// The major.minor numbers reflect when this project first diverged from the +// "upstream" or parent project. +const DefaultUserAgent string = "go-teams-notify/2.2" + +// ErrWebhookURLUnexpected is returned when a provided webhook URL does +// not match a set of confirmed webhook URL patterns. +var ErrWebhookURLUnexpected = errors.New("webhook URL does not match one of expected patterns") + +// ErrWebhookURLUnexpectedPrefix is returned when a provided webhook URL does +// not match a set of confirmed webhook URL prefixes. +// +// Deprecated: Use ErrWebhookURLUnexpected instead. +var ErrWebhookURLUnexpectedPrefix = ErrWebhookURLUnexpected + +// ErrInvalidWebhookURLResponseText is returned when the remote webhook +// endpoint indicates via response text that a message submission was +// unsuccessful. +var ErrInvalidWebhookURLResponseText = errors.New("invalid webhook URL response text") + +// API is the legacy interface representing a client used to submit messages +// to a Microsoft Teams channel. +type API interface { + Send(webhookURL string, webhookMessage MessageCard) error + SendWithContext(ctx context.Context, webhookURL string, webhookMessage MessageCard) error + SendWithRetry(ctx context.Context, webhookURL string, webhookMessage MessageCard, retries int, retriesDelay int) error + SkipWebhookURLValidationOnSend(skip bool) API + AddWebhookURLValidationPatterns(patterns ...string) API + ValidateWebhook(webhookURL string) error +} + +// MessageSender describes the behavior of a baseline Microsoft Teams client. +// +// An unexported method is used to prevent client code from implementing this +// interface in order to support future changes (and not violate backwards +// compatibility). +type MessageSender interface { + HTTPClient() *http.Client + UserAgent() string + ValidateWebhook(webhookURL string) error + + // A private method to prevent client code from implementing the interface + // so that any future changes to it will not violate backwards + // compatibility. + private() +} + +// messagePreparer is a message type that supports marshaling its fields +// as preparation for delivery to an endpoint. +type messagePreparer interface { + Prepare() error +} + +// messageValidator is a message type that provides validation of its format. +type messageValidator interface { + Validate() error +} + +// TeamsMessage is the interface shared by all supported message formats for +// submission to a Microsoft Teams channel. +type TeamsMessage interface { + messagePreparer + messageValidator + + Payload() io.Reader +} + +// teamsClient is the legacy client used for submitting messages to a +// Microsoft Teams channel. +type teamsClient struct { + httpClient *http.Client + userAgent string + webhookURLValidationPatterns []string + skipWebhookURLValidation bool +} + +// TeamsClient provides functionality for submitting messages to a Microsoft +// Teams channel. +type TeamsClient struct { + httpClient *http.Client + userAgent string + webhookURLValidationPatterns []string + skipWebhookURLValidation bool +} + +func init() { + // Disable logging output by default unless client code explicitly + // requests it + logger = log.New(os.Stderr, "[goteamsnotify] ", 0) + logger.SetOutput(ioutil.Discard) +} + +// EnableLogging enables logging output from this package. Output is muted by +// default unless explicitly requested (by calling this function). +func EnableLogging() { + logger.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) + logger.SetOutput(os.Stderr) +} + +// DisableLogging reapplies default package-level logging settings of muting +// all logging output. +func DisableLogging() { + logger.SetFlags(0) + logger.SetOutput(ioutil.Discard) +} + +// NewClient - create a brand new client for MS Teams notify +// +// Deprecated: use NewTeamsClient() function instead. +func NewClient() API { + client := teamsClient{ + httpClient: &http.Client{ + // We're using a context instead of setting this directly + // Timeout: DefaultWebhookSendTimeout, + }, + skipWebhookURLValidation: false, + } + return &client +} + +// NewTeamsClient constructs a minimal client for submitting messages to a +// Microsoft Teams channel. +func NewTeamsClient() *TeamsClient { + client := TeamsClient{ + httpClient: &http.Client{ + // We're using a context instead of setting this directly + // Timeout: DefaultWebhookSendTimeout, + }, + skipWebhookURLValidation: false, + } + return &client +} + +// private prevents client code from implementing the MessageSender interface +// so that any future changes to it will not violate backwards compatibility. +func (c *teamsClient) private() {} + +// private prevents client code from implementing the MessageSender interface +// so that any future changes to it will not violate backwards compatibility. +func (c *TeamsClient) private() {} + +// SetHTTPClient accepts a custom http.Client value which replaces the +// existing default http.Client. +func (c *TeamsClient) SetHTTPClient(httpClient *http.Client) *TeamsClient { + c.httpClient = httpClient + + return c +} + +// SetUserAgent accepts a custom user agent string. This custom user agent is +// used when submitting messages to Microsoft Teams. +func (c *TeamsClient) SetUserAgent(userAgent string) *TeamsClient { + c.userAgent = userAgent + + return c +} + +// UserAgent returns the configured user agent string for the client. If a +// custom value is not set the default package user agent is returned. +// +// Deprecated: use TeamsClient.UserAgent() method instead. +func (c *teamsClient) UserAgent() string { + switch { + case c.userAgent != "": + return c.userAgent + default: + return DefaultUserAgent + } +} + +// UserAgent returns the configured user agent string for the client. If a +// custom value is not set the default package user agent is returned. +func (c *TeamsClient) UserAgent() string { + switch { + case c.userAgent != "": + return c.userAgent + default: + return DefaultUserAgent + } +} + +// AddWebhookURLValidationPatterns collects given patterns for validation of +// the webhook URL. +// +// Deprecated: use TeamsClient.AddWebhookURLValidationPatterns() method instead. +func (c *teamsClient) AddWebhookURLValidationPatterns(patterns ...string) API { + c.webhookURLValidationPatterns = append(c.webhookURLValidationPatterns, patterns...) + return c +} + +// AddWebhookURLValidationPatterns collects given patterns for validation of +// the webhook URL. +func (c *TeamsClient) AddWebhookURLValidationPatterns(patterns ...string) *TeamsClient { + c.webhookURLValidationPatterns = append(c.webhookURLValidationPatterns, patterns...) + return c +} + +// HTTPClient returns the internal pointer to an http.Client. This can be used +// to further modify specific http.Client field values. +// +// Deprecated: use TeamsClient.HTTPClient() method instead. +func (c *teamsClient) HTTPClient() *http.Client { + return c.httpClient +} + +// HTTPClient returns the internal pointer to an http.Client. This can be used +// to further modify specific http.Client field values. +func (c *TeamsClient) HTTPClient() *http.Client { + return c.httpClient +} + +// Send is a wrapper function around the SendWithContext method in order to +// provide backwards compatibility. +// +// Deprecated: use TeamsClient.Send() method instead. +func (c *teamsClient) Send(webhookURL string, webhookMessage MessageCard) error { + // Create context that can be used to emulate existing timeout behavior. + ctx, cancel := context.WithTimeout(context.Background(), DefaultWebhookSendTimeout) + defer cancel() + + return sendWithContext(ctx, c, webhookURL, &webhookMessage) +} + +// Send is a wrapper function around the SendWithContext method in order to +// provide backwards compatibility. +func (c *TeamsClient) Send(webhookURL string, message TeamsMessage) error { + // Create context that can be used to emulate existing timeout behavior. + ctx, cancel := context.WithTimeout(context.Background(), DefaultWebhookSendTimeout) + defer cancel() + + return sendWithContext(ctx, c, webhookURL, message) +} + +// SendWithContext submits a given message to a Microsoft Teams channel using +// the provided webhook URL. The http client request honors the cancellation +// or timeout of the provided context. +// +// Deprecated: use TeamsClient.SendWithContext() method instead. +func (c *teamsClient) SendWithContext(ctx context.Context, webhookURL string, webhookMessage MessageCard) error { + return sendWithContext(ctx, c, webhookURL, &webhookMessage) +} + +// SendWithContext submits a given message to a Microsoft Teams channel using +// the provided webhook URL. The http client request honors the cancellation +// or timeout of the provided context. +func (c *TeamsClient) SendWithContext(ctx context.Context, webhookURL string, message TeamsMessage) error { + return sendWithContext(ctx, c, webhookURL, message) +} + +// SendWithRetry provides message retry support when submitting messages to a +// Microsoft Teams channel. The caller is responsible for providing the +// desired context timeout, the number of retries and retries delay. +// +// Deprecated: use TeamsClient.SendWithRetry() method instead. +func (c *teamsClient) SendWithRetry(ctx context.Context, webhookURL string, webhookMessage MessageCard, retries int, retriesDelay int) error { + return sendWithRetry(ctx, c, webhookURL, &webhookMessage, retries, retriesDelay) +} + +// SendWithRetry provides message retry support when submitting messages to a +// Microsoft Teams channel. The caller is responsible for providing the +// desired context timeout, the number of retries and retries delay. +func (c *TeamsClient) SendWithRetry(ctx context.Context, webhookURL string, message TeamsMessage, retries int, retriesDelay int) error { + return sendWithRetry(ctx, c, webhookURL, message, retries, retriesDelay) +} + +// SkipWebhookURLValidationOnSend allows the caller to optionally disable +// webhook URL validation. +// +// Deprecated: use TeamsClient.SkipWebhookURLValidationOnSend() method instead. +func (c *teamsClient) SkipWebhookURLValidationOnSend(skip bool) API { + c.skipWebhookURLValidation = skip + return c +} + +// SkipWebhookURLValidationOnSend allows the caller to optionally disable +// webhook URL validation. +func (c *TeamsClient) SkipWebhookURLValidationOnSend(skip bool) *TeamsClient { + c.skipWebhookURLValidation = skip + return c +} + +// prepareRequest is a helper function that prepares a http.Request (including +// all desired headers) in order to submit a given prepared message to an +// endpoint. +func prepareRequest(ctx context.Context, userAgent string, webhookURL string, preparedMessage io.Reader) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, preparedMessage) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", "application/json;charset=utf-8") + req.Header.Set("User-Agent", userAgent) + + return req, nil +} + +// processResponse is a helper function responsible for validating a response +// from an endpoint after submitting a message. +func processResponse(response *http.Response) (string, error) { + // Get the response body, then convert to string for use with extended + // error messages + responseData, err := ioutil.ReadAll(response.Body) + if err != nil { + logger.Println(err) + + return "", err + } + responseString := string(responseData) + + // TODO: Refactor for v3 series once O365 connector support is dropped. + switch { + // 400 Bad Response is likely an indicator that we failed to provide a + // required field in our JSON payload. For example, when leaving out the + // top level MessageCard Summary or Text field, the remote API returns + // "Summary or Text is required." as a text string. We include that + // response text in the error message that we return to the caller. + case response.StatusCode >= 299: + err = fmt.Errorf("error on notification: %v, %q", response.Status, responseString) + + logger.Println(err) + + return "", err + + case response.StatusCode == 202: + // 202 Accepted response is expected for Workflow connector URL + // submissions. + + logger.Println("202 Accepted response received as expected for workflow connector") + + return responseString, nil + + // DEPRECATED + // + // See https://github.com/atc0005/go-teams-notify/issues/262 + // + // Microsoft Teams developers have indicated that receiving a 200 status + // code when submitting payloads to O365 connectors is insufficient to + // confirm that a message was successfully submitted. + // + // Instead, clients should ensure that a specific response string was also + // returned along with a 200 status code to confirm that a message was + // sent successfully. Because there is a chance that unintentional + // whitespace could be included, we explicitly strip it out. + // + // See atc0005/go-teams-notify#59 for more information. + case responseString != strings.TrimSpace(ExpectedWebhookURLResponseText): + logger.Printf( + "StatusCode: %v, Status: %v\n", response.StatusCode, response.Status, + ) + logger.Printf("ResponseString: %v\n", responseString) + + err = fmt.Errorf( + "got %q, expected %q: %w", + responseString, + ExpectedWebhookURLResponseText, + ErrInvalidWebhookURLResponseText, + ) + + logger.Println(err) + + return "", err + + default: + return responseString, nil + } +} + +// validateWebhook applies webhook URL validation unless explicitly disabled. +func validateWebhook(webhookURL string, skipWebhookValidation bool, patterns []string) error { + if skipWebhookValidation || webhookURL == DisableWebhookURLValidation { + logger.Printf("validateWebhook: Webhook URL will not be validated: %#v\n", webhookURL) + + return nil + } + + u, err := url.Parse(webhookURL) + if err != nil { + return fmt.Errorf("unable to parse webhook URL %q: %w", webhookURL, err) + } + + if len(patterns) == 0 { + patterns = []string{ + DefaultWebhookURLValidationPattern, + WorkflowURLBaseDomain, + } + } + + // Indicate passing validation if at least one pattern matches. + for _, pat := range patterns { + matched, err := regexp.MatchString(pat, webhookURL) + if err != nil { + return err + } + if matched { + logger.Printf("Pattern %v matched", pat) + + return nil + } + } + + return fmt.Errorf( + "%w; got: %q, patterns: %s", + ErrWebhookURLUnexpected, + u.String(), + strings.Join(patterns, ","), + ) +} + +// ValidateWebhook applies webhook URL validation unless explicitly disabled. +// +// Deprecated: use TeamsClient.ValidateWebhook() method instead. +func (c *teamsClient) ValidateWebhook(webhookURL string) error { + return validateWebhook(webhookURL, c.skipWebhookURLValidation, c.webhookURLValidationPatterns) +} + +// ValidateWebhook applies webhook URL validation unless explicitly disabled. +func (c *TeamsClient) ValidateWebhook(webhookURL string) error { + return validateWebhook(webhookURL, c.skipWebhookURLValidation, c.webhookURLValidationPatterns) +} + +// sendWithContext submits a given message to a Microsoft Teams channel using +// the provided webhook URL and client. The http client request honors the +// cancellation or timeout of the provided context. +func sendWithContext(ctx context.Context, client MessageSender, webhookURL string, message TeamsMessage) error { + logger.Printf("sendWithContext: Webhook message received: %#v\n", message) + + if err := client.ValidateWebhook(webhookURL); err != nil { + return fmt.Errorf( + "failed to validate webhook URL: %w", + err, + ) + } + + if err := message.Validate(); err != nil { + return fmt.Errorf( + "failed to validate message: %w", + err, + ) + } + + if err := message.Prepare(); err != nil { + return fmt.Errorf( + "failed to prepare message: %w", + err, + ) + } + + req, err := prepareRequest(ctx, client.UserAgent(), webhookURL, message.Payload()) + if err != nil { + return fmt.Errorf( + "failed to prepare request: %w", + err, + ) + } + + // Submit message to endpoint. + res, err := client.HTTPClient().Do(req) + if err != nil { + return fmt.Errorf( + "failed to submit message: %w", + err, + ) + } + + // Make sure that we close the response body once we're done with it + defer func() { + if err := res.Body.Close(); err != nil { + log.Printf("error closing response body: %v", err) + } + }() + + responseText, err := processResponse(res) + if err != nil { + return fmt.Errorf( + "failed to process response: %w", + err, + ) + } + + logger.Printf("sendWithContext: Response string from Microsoft Teams API: %v\n", responseText) + + return nil +} + +// sendWithRetry provides message retry support when submitting messages to a +// Microsoft Teams channel. The caller is responsible for providing the +// desired context timeout, the number of retries and retries delay. +func sendWithRetry(ctx context.Context, client MessageSender, webhookURL string, message TeamsMessage, retries int, retriesDelay int) error { + var result error + + // initial attempt + number of specified retries + attemptsAllowed := 1 + retries + + // attempt to send message to Microsoft Teams, retry specified number of + // times before giving up + for attempt := 1; attempt <= attemptsAllowed; attempt++ { + // the result from the last attempt is returned to the caller + result = sendWithContext(ctx, client, webhookURL, message) + + switch { + case result != nil: + + logger.Printf( + "sendWithRetry: Attempt %d of %d to send message failed: %v", + attempt, + attemptsAllowed, + result, + ) + + if ctx.Err() != nil { + errMsg := fmt.Errorf( + "sendWithRetry: context cancelled or expired: %v; "+ + "aborting message submission after %d of %d attempts: %w", + ctx.Err().Error(), + attempt, + attemptsAllowed, + result, + ) + + logger.Println(errMsg) + + return errMsg + } + + ourRetryDelay := time.Duration(retriesDelay) * time.Second + + logger.Printf( + "sendWithRetry: Context not cancelled yet, applying retry delay of %v", + ourRetryDelay, + ) + time.Sleep(ourRetryDelay) + + default: + logger.Printf( + "sendWithRetry: successfully sent message after %d of %d attempts\n", + attempt, + attemptsAllowed, + ) + + // No further retries needed + return nil + } + } + + return result +} + +// old deprecated helper functions -------------------------------------------------------------------------------------------------------------- + +// IsValidInput is a validation "wrapper" function. This function is intended +// to run current validation checks and offer easy extensibility for future +// validation requirements. +// +// Deprecated: use API.ValidateWebhook() and MessageCard.Validate() +// methods instead. +func IsValidInput(webhookMessage MessageCard, webhookURL string) (bool, error) { + // validate url + if valid, err := IsValidWebhookURL(webhookURL); !valid { + return false, err + } + + // validate message + if valid, err := IsValidMessageCard(webhookMessage); !valid { + return false, err + } + + return true, nil +} + +// IsValidWebhookURL performs validation checks on the webhook URL used to +// submit messages to Microsoft Teams. +// +// Deprecated: use API.ValidateWebhook() method instead. +func IsValidWebhookURL(webhookURL string) (bool, error) { + c := teamsClient{} + err := c.ValidateWebhook(webhookURL) + return err == nil, err +} + +// IsValidMessageCard performs validation/checks for known issues with +// MessardCard values. +// +// Deprecated: use MessageCard.Validate() instead. +func IsValidMessageCard(webhookMessage MessageCard) (bool, error) { + err := webhookMessage.Validate() + return err == nil, err +} diff --git a/vendor/github.com/atc0005/go-teams-notify/v2/textutils.go b/vendor/github.com/atc0005/go-teams-notify/v2/textutils.go new file mode 100644 index 000000000..c8722669c --- /dev/null +++ b/vendor/github.com/atc0005/go-teams-notify/v2/textutils.go @@ -0,0 +1,29 @@ +// Copyright 2022 Adam Chalkley +// +// https://github.com/atc0005/go-teams-notify +// +// Licensed under the MIT License. See LICENSE file in the project root for +// full license information. + +package goteamsnotify + +import ( + "strings" +) + +// InList is a helper function to emulate Python's `if "x" in list:` +// functionality. The caller can optionally ignore case of compared items. +func InList(needle string, haystack []string, ignoreCase bool) bool { + for _, item := range haystack { + if ignoreCase { + if strings.EqualFold(item, needle) { + return true + } + } + + if item == needle { + return true + } + } + return false +} diff --git a/vendor/github.com/bwmarrin/discordgo/.gitignore b/vendor/github.com/bwmarrin/discordgo/.gitignore new file mode 100644 index 000000000..681a96b19 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/.gitignore @@ -0,0 +1,5 @@ +# IDE-specific metadata +.idea/ + +# Environment variables. Useful for examples. +.env diff --git a/vendor/github.com/bwmarrin/discordgo/.golangci.yml b/vendor/github.com/bwmarrin/discordgo/.golangci.yml new file mode 100644 index 000000000..dd9d2e5b4 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/.golangci.yml @@ -0,0 +1,19 @@ +linters: + disable-all: true + enable: + # - staticcheck + # - unused + - golint + +linters-settings: + staticcheck: + go: "1.13" + + checks: ["all"] + + unused: + go: "1.13" + +issues: + include: + - EXC0002 diff --git a/vendor/github.com/bwmarrin/discordgo/.travis.yml b/vendor/github.com/bwmarrin/discordgo/.travis.yml new file mode 100644 index 000000000..e80d490bd --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/.travis.yml @@ -0,0 +1,19 @@ +language: go +go: + - 1.13.x + - 1.14.x + - 1.15.x + - 1.16.x + - 1.17.x + - 1.18.x +env: + - GO111MODULE=on +install: + - go get github.com/bwmarrin/discordgo + - go get -v . + - go get -v golang.org/x/lint/golint +script: + - diff <(gofmt -d .) <(echo -n) + - go vet -x ./... + - golint -set_exit_status ./... + - go test -v -race ./... diff --git a/vendor/github.com/bwmarrin/discordgo/CONTRIBUTING.md b/vendor/github.com/bwmarrin/discordgo/CONTRIBUTING.md new file mode 100644 index 000000000..85e9680cd --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/CONTRIBUTING.md @@ -0,0 +1,87 @@ +# Getting started + +To start off you can check out existing Pull Requests and Issues to get a gasp of what problems we’re currently solving and what features you can implement. + +## Issues + +Our issues are mostly used for bugs, however we welcome refactoring and conceptual issues. + +Any other conversation would belong and would be moved into “Discussions”. + +## Discussions + +We use discussions for ideas, polls, announcements and help questions. + +Don’t hesitate to ask, we always would try to help. + +## Pull Requests + +If you want to help us by improving existing or adding new features, you create what’s called a Pull Request (aka PR). It allows us to review your code, suggest changes and merge it. + +Here are some tips on how to make a good first PR: + +- When creating a PR, please consider a distinctive name and description for it, so the maintainers can understand what your PR changes / adds / removes. +- It’s always a good idea to link documentation when implementing a new feature / endpoint +- If you’re resolving an issue, don’t forget to [link it](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) in the description. +- Enable the checkbox to allow maintainers to edit your PR and make commits in the PR branch when necessary. +- We may ask for changes, usually through suggestions or pull request comments. You can apply suggestions right in the UI. Any other change needs to be done manually. +- Don’t forget to mark PR comments resolved when you’re done applying the changes. +- Be patient and don’t close and reopen your PR when no one responds, sometimes it might be held for a while. There might be a lot of reasons: release preparation, the feature is not significant, maintainers are busy, etc. + + +When your changes are still incomplete (i.e. in Work In Progress state), you can still create a PR, but consider making it a draft. +To make a draft PR, you can change the type of PR by clicking to a triangle next to the “Create Pull Request” button. + +Once you’re done, you can mark it as “Ready for review”, and we’ll get right on it. + + +# Code style + +To standardize and make things less messy we have a certain code style, that is persistent throughout the codebase. + +## Naming + +### REST methods + +When naming a REST method, while it might seem counterintuitive, we specify the entity before the action verb (for GET endpoints we don’t specify one however). Here’s an example: + +> Endpoint name: Get Channel Message +> +> Method name: `ChannelMessage` + +> Endpoint name: Edit Channel Message +> +> Method name: `ChannelMessageEdit` + +### Parameter structures + +When making a complex REST endpoint, sometimes you might need to implement a `Param` structure. This structure contains parameters for certain endpoint/set of endpoints. + +- If an endpoint/set of endpoints have mostly same parameters, it’s a good idea to use a single `Param` structure for them. Here’s an example: + + > Endpoint: `GuildMemberEdit` + > + > `Param` structure: `GuildMemberParams` +- If an endpoint/set of endpoints have differentiating parameters, `Param` structure can be named after the endpoint’s verb. Here’s an example: + + > Endpoint: `ChannelMessageSendComplex` + > + > `Param` structure: `MessageSend` + + > Endpoint: `ChannelMessageEditComplex` + > + > `Param` structure: `MessageEdit` + +### Events + +When naming an event, we follow gateway’s internal naming (which often matches with the official event name in the docs). Here’s an example: + +> Event name: Interaction Create (`INTERACTION_CREATE`) +> +> Structure name: `InteractionCreate` + +## Returns + +In our REST functions we usually favor named returns instead of regular anonymous returns. This helps readability. + +Additionally we try to avoid naked return statements for functions with a long body. Since it’s easier to loose track of the return result. diff --git a/vendor/github.com/bwmarrin/discordgo/LICENSE b/vendor/github.com/bwmarrin/discordgo/LICENSE new file mode 100644 index 000000000..8d062ea57 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2015, Bruce Marriner +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of discordgo nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/vendor/github.com/bwmarrin/discordgo/README.md b/vendor/github.com/bwmarrin/discordgo/README.md new file mode 100644 index 000000000..d6ee0cc79 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/README.md @@ -0,0 +1,103 @@ +# DiscordGo + +[![Go Reference](https://pkg.go.dev/badge/github.com/bwmarrin/discordgo.svg)](https://pkg.go.dev/github.com/bwmarrin/discordgo) [![Go Report Card](https://goreportcard.com/badge/github.com/bwmarrin/discordgo)](https://goreportcard.com/report/github.com/bwmarrin/discordgo) [![CI](https://github.com/bwmarrin/discordgo/actions/workflows/ci.yml/badge.svg)](https://github.com/bwmarrin/discordgo/actions/workflows/ci.yml) [![Discord Gophers](https://img.shields.io/badge/Discord%20Gophers-%23discordgo-blue.svg)](https://discord.gg/golang) [![Discord API](https://img.shields.io/badge/Discord%20API-%23go_discordgo-blue.svg)](https://discord.com/invite/discord-api) + +DiscordGo logo + +DiscordGo is a [Go](https://golang.org/) package that provides low level +bindings to the [Discord](https://discord.com/) chat client API. DiscordGo +has nearly complete support for all of the Discord API endpoints, websocket +interface, and voice interface. + +If you would like to help the DiscordGo package please use +[this link](https://discord.com/oauth2/authorize?client_id=173113690092994561&scope=bot) +to add the official DiscordGo test bot **dgo** to your server. This provides +indispensable help to this project. + +* See [dgVoice](https://github.com/bwmarrin/dgvoice) package for an example of +additional voice helper functions and features for DiscordGo. + +* See [dca](https://github.com/bwmarrin/dca) for an **experimental** stand alone +tool that wraps `ffmpeg` to create opus encoded audio appropriate for use with +Discord (and DiscordGo). + +**For help with this package or general Go discussion, please join the [Discord +Gophers](https://discord.gg/golang) chat server.** + +## Getting Started + +### Installing + +This assumes you already have a working Go environment, if not please see +[this page](https://golang.org/doc/install) first. + +`go get` *will always pull the latest tagged release from the master branch.* + +```sh +go get github.com/bwmarrin/discordgo +``` + +### Usage + +Import the package into your project. + +```go +import "github.com/bwmarrin/discordgo" +``` + +Construct a new Discord client which can be used to access the variety of +Discord API functions and to set callback functions for Discord events. + +```go +discord, err := discordgo.New("Bot " + "authentication token") +``` + +See Documentation and Examples below for more detailed information. + + +## Documentation + +**NOTICE**: This library and the Discord API are unfinished. +Because of that there may be major changes to library in the future. + +The DiscordGo code is fairly well documented at this point and is currently +the only documentation available. Go reference (below) presents that information in a nice format. + +- [![Go Reference](https://pkg.go.dev/badge/github.com/bwmarrin/discordgo.svg)](https://pkg.go.dev/github.com/bwmarrin/discordgo) +- Hand crafted documentation coming eventually. + + +## Examples + +Below is a list of examples and other projects using DiscordGo. Please submit +an issue if you would like your project added or removed from this list. + +- [DiscordGo Examples](https://github.com/bwmarrin/discordgo/tree/master/examples) - A collection of example programs written with DiscordGo +- [Awesome DiscordGo](https://github.com/bwmarrin/discordgo/wiki/Awesome-DiscordGo) - A curated list of high quality projects using DiscordGo + +## Troubleshooting +For help with common problems please reference the +[Troubleshooting](https://github.com/bwmarrin/discordgo/wiki/Troubleshooting) +section of the project wiki. + + +## Contributing +Contributions are very welcomed, however please follow the below guidelines. + +- First open an issue describing the bug or enhancement so it can be +discussed. +- Try to match current naming conventions as closely as possible. +- This package is intended to be a low level direct mapping of the Discord API, +so please avoid adding enhancements outside of that scope without first +discussing it. +- Create a Pull Request with your changes against the master branch. + + +## List of Discord APIs + +See [this chart](https://abal.moe/Discord/Libraries.html) for a feature +comparison and list of other Discord API libraries. + +## Special Thanks + +[Chris Rhodes](https://github.com/iopred) - For the DiscordGo logo and tons of PRs. diff --git a/vendor/github.com/bwmarrin/discordgo/components.go b/vendor/github.com/bwmarrin/discordgo/components.go new file mode 100644 index 000000000..4c418fcab --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/components.go @@ -0,0 +1,604 @@ +package discordgo + +import ( + "encoding/json" + "fmt" +) + +// ComponentType is type of component. +type ComponentType uint + +// MessageComponent types. +const ( + ActionsRowComponent ComponentType = 1 + ButtonComponent ComponentType = 2 + SelectMenuComponent ComponentType = 3 + TextInputComponent ComponentType = 4 + UserSelectMenuComponent ComponentType = 5 + RoleSelectMenuComponent ComponentType = 6 + MentionableSelectMenuComponent ComponentType = 7 + ChannelSelectMenuComponent ComponentType = 8 + SectionComponent ComponentType = 9 + TextDisplayComponent ComponentType = 10 + ThumbnailComponent ComponentType = 11 + MediaGalleryComponent ComponentType = 12 + FileComponentType ComponentType = 13 + SeparatorComponent ComponentType = 14 + ContainerComponent ComponentType = 17 +) + +// MessageComponent is a base interface for all message components. +type MessageComponent interface { + json.Marshaler + Type() ComponentType +} + +type unmarshalableMessageComponent struct { + MessageComponent +} + +// UnmarshalJSON is a helper function to unmarshal MessageComponent object. +func (umc *unmarshalableMessageComponent) UnmarshalJSON(src []byte) error { + var v struct { + Type ComponentType `json:"type"` + } + err := json.Unmarshal(src, &v) + if err != nil { + return err + } + + switch v.Type { + case ActionsRowComponent: + umc.MessageComponent = &ActionsRow{} + case ButtonComponent: + umc.MessageComponent = &Button{} + case SelectMenuComponent, ChannelSelectMenuComponent, UserSelectMenuComponent, + RoleSelectMenuComponent, MentionableSelectMenuComponent: + umc.MessageComponent = &SelectMenu{} + case TextInputComponent: + umc.MessageComponent = &TextInput{} + case SectionComponent: + umc.MessageComponent = &Section{} + case TextDisplayComponent: + umc.MessageComponent = &TextDisplay{} + case ThumbnailComponent: + umc.MessageComponent = &Thumbnail{} + case MediaGalleryComponent: + umc.MessageComponent = &MediaGallery{} + case FileComponentType: + umc.MessageComponent = &FileComponent{} + case SeparatorComponent: + umc.MessageComponent = &Separator{} + case ContainerComponent: + umc.MessageComponent = &Container{} + default: + return fmt.Errorf("unknown component type: %d", v.Type) + } + return json.Unmarshal(src, umc.MessageComponent) +} + +// MessageComponentFromJSON is a helper function for unmarshaling message components +func MessageComponentFromJSON(b []byte) (MessageComponent, error) { + var u unmarshalableMessageComponent + err := u.UnmarshalJSON(b) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal into MessageComponent: %w", err) + } + return u.MessageComponent, nil +} + +// ActionsRow is a top-level container component for displaying a row of interactive components. +type ActionsRow struct { + // Can contain Button, SelectMenu and TextInput. + // NOTE: maximum of 5. + Components []MessageComponent `json:"components"` + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` +} + +// MarshalJSON is a method for marshaling ActionsRow to a JSON object. +func (r ActionsRow) MarshalJSON() ([]byte, error) { + type actionsRow ActionsRow + + return Marshal(struct { + actionsRow + Type ComponentType `json:"type"` + }{ + actionsRow: actionsRow(r), + Type: r.Type(), + }) +} + +// UnmarshalJSON is a helper function to unmarshal Actions Row. +func (r *ActionsRow) UnmarshalJSON(data []byte) error { + type actionsRow ActionsRow + var v struct { + actionsRow + RawComponents []unmarshalableMessageComponent `json:"components"` + } + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + *r = ActionsRow(v.actionsRow) + + r.Components = make([]MessageComponent, len(v.RawComponents)) + for i, v := range v.RawComponents { + r.Components[i] = v.MessageComponent + } + + return err +} + +// Type is a method to get the type of a component. +func (r ActionsRow) Type() ComponentType { + return ActionsRowComponent +} + +// ButtonStyle is style of button. +type ButtonStyle uint + +// Button styles. +const ( + // PrimaryButton is a button with blurple color. + PrimaryButton ButtonStyle = 1 + // SecondaryButton is a button with grey color. + SecondaryButton ButtonStyle = 2 + // SuccessButton is a button with green color. + SuccessButton ButtonStyle = 3 + // DangerButton is a button with red color. + DangerButton ButtonStyle = 4 + // LinkButton is a special type of button which navigates to a URL. Has grey color. + LinkButton ButtonStyle = 5 + // PremiumButton is a special type of button with a blurple color that links to a SKU. + PremiumButton ButtonStyle = 6 +) + +// ComponentEmoji represents button emoji, if it does have one. +type ComponentEmoji struct { + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` + Animated bool `json:"animated,omitempty"` +} + +// Button represents button component. +type Button struct { + Label string `json:"label"` + Style ButtonStyle `json:"style"` + Disabled bool `json:"disabled"` + Emoji *ComponentEmoji `json:"emoji,omitempty"` + + // NOTE: Only button with LinkButton style can have link. Also, URL is mutually exclusive with CustomID. + URL string `json:"url,omitempty"` + CustomID string `json:"custom_id,omitempty"` + // Identifier for a purchasable SKU. Only available when using premium-style buttons. + SKUID string `json:"sku_id,omitempty"` + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` +} + +// MarshalJSON is a method for marshaling Button to a JSON object. +func (b Button) MarshalJSON() ([]byte, error) { + type button Button + + if b.Style == 0 { + b.Style = PrimaryButton + } + + return Marshal(struct { + button + Type ComponentType `json:"type"` + }{ + button: button(b), + Type: b.Type(), + }) +} + +// Type is a method to get the type of a component. +func (Button) Type() ComponentType { + return ButtonComponent +} + +// SelectMenuOption represents an option for a select menu. +type SelectMenuOption struct { + Label string `json:"label,omitempty"` + Value string `json:"value"` + Description string `json:"description"` + Emoji *ComponentEmoji `json:"emoji,omitempty"` + // Determines whenever option is selected by default or not. + Default bool `json:"default"` +} + +// SelectMenuDefaultValueType represents the type of an entity selected by default in auto-populated select menus. +type SelectMenuDefaultValueType string + +// SelectMenuDefaultValue types. +const ( + SelectMenuDefaultValueUser SelectMenuDefaultValueType = "user" + SelectMenuDefaultValueRole SelectMenuDefaultValueType = "role" + SelectMenuDefaultValueChannel SelectMenuDefaultValueType = "channel" +) + +// SelectMenuDefaultValue represents an entity selected by default in auto-populated select menus. +type SelectMenuDefaultValue struct { + // ID of the entity. + ID string `json:"id"` + // Type of the entity. + Type SelectMenuDefaultValueType `json:"type"` +} + +// SelectMenuType represents select menu type. +type SelectMenuType ComponentType + +// SelectMenu types. +const ( + StringSelectMenu = SelectMenuType(SelectMenuComponent) + UserSelectMenu = SelectMenuType(UserSelectMenuComponent) + RoleSelectMenu = SelectMenuType(RoleSelectMenuComponent) + MentionableSelectMenu = SelectMenuType(MentionableSelectMenuComponent) + ChannelSelectMenu = SelectMenuType(ChannelSelectMenuComponent) +) + +// SelectMenu represents select menu component. +type SelectMenu struct { + // Type of the select menu. + MenuType SelectMenuType `json:"type,omitempty"` + // CustomID is a developer-defined identifier for the select menu. + CustomID string `json:"custom_id,omitempty"` + // The text which will be shown in the menu if there's no default options or all options was deselected and component was closed. + Placeholder string `json:"placeholder"` + // This value determines the minimal amount of selected items in the menu. + MinValues *int `json:"min_values,omitempty"` + // This value determines the maximal amount of selected items in the menu. + // If MaxValues or MinValues are greater than one then the user can select multiple items in the component. + MaxValues int `json:"max_values,omitempty"` + // List of default values for auto-populated select menus. + // NOTE: Number of entries should be in the range defined by MinValues and MaxValues. + DefaultValues []SelectMenuDefaultValue `json:"default_values,omitempty"` + + Options []SelectMenuOption `json:"options,omitempty"` + Disabled bool `json:"disabled"` + + // NOTE: Can only be used in SelectMenu with Channel menu type. + ChannelTypes []ChannelType `json:"channel_types,omitempty"` + + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` +} + +// Type is a method to get the type of a component. +func (s SelectMenu) Type() ComponentType { + if s.MenuType != 0 { + return ComponentType(s.MenuType) + } + return SelectMenuComponent +} + +// MarshalJSON is a method for marshaling SelectMenu to a JSON object. +func (s SelectMenu) MarshalJSON() ([]byte, error) { + type selectMenu SelectMenu + + return Marshal(struct { + selectMenu + Type ComponentType `json:"type"` + }{ + selectMenu: selectMenu(s), + Type: s.Type(), + }) +} + +// TextInput represents text input component. +type TextInput struct { + CustomID string `json:"custom_id"` + Label string `json:"label"` + Style TextInputStyle `json:"style"` + Placeholder string `json:"placeholder,omitempty"` + Value string `json:"value,omitempty"` + Required bool `json:"required"` + MinLength int `json:"min_length,omitempty"` + MaxLength int `json:"max_length,omitempty"` + + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` +} + +// Type is a method to get the type of a component. +func (TextInput) Type() ComponentType { + return TextInputComponent +} + +// MarshalJSON is a method for marshaling TextInput to a JSON object. +func (m TextInput) MarshalJSON() ([]byte, error) { + type inputText TextInput + + return Marshal(struct { + inputText + Type ComponentType `json:"type"` + }{ + inputText: inputText(m), + Type: m.Type(), + }) +} + +// TextInputStyle is style of text in TextInput component. +type TextInputStyle uint + +// Text styles +const ( + TextInputShort TextInputStyle = 1 + TextInputParagraph TextInputStyle = 2 +) + +// Section is a top-level layout component that allows you to join text contextually with an accessory. +type Section struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + // Array of text display components; max of 3. + Components []MessageComponent `json:"components"` + // Can be Button or Thumbnail + Accessory MessageComponent `json:"accessory"` +} + +// UnmarshalJSON is a method for unmarshaling Section from JSON +func (s *Section) UnmarshalJSON(data []byte) error { + type section Section + + var v struct { + section + RawComponents []unmarshalableMessageComponent `json:"components"` + RawAccessory unmarshalableMessageComponent `json:"accessory"` + } + + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + + *s = Section(v.section) + s.Accessory = v.RawAccessory.MessageComponent + s.Components = make([]MessageComponent, len(v.RawComponents)) + for i, v := range v.RawComponents { + s.Components[i] = v.MessageComponent + } + + return nil +} + +// Type is a method to get the type of a component. +func (Section) Type() ComponentType { + return SectionComponent +} + +// MarshalJSON is a method for marshaling Section to a JSON object. +func (s Section) MarshalJSON() ([]byte, error) { + type section Section + + return Marshal(struct { + section + Type ComponentType `json:"type"` + }{ + section: section(s), + Type: s.Type(), + }) +} + +// TextDisplay is a top-level component that allows you to add markdown-formatted text to the message. +type TextDisplay struct { + Content string `json:"content"` +} + +// Type is a method to get the type of a component. +func (TextDisplay) Type() ComponentType { + return TextDisplayComponent +} + +// MarshalJSON is a method for marshaling TextDisplay to a JSON object. +func (t TextDisplay) MarshalJSON() ([]byte, error) { + type textDisplay TextDisplay + + return Marshal(struct { + textDisplay + Type ComponentType `json:"type"` + }{ + textDisplay: textDisplay(t), + Type: t.Type(), + }) +} + +// Thumbnail component can be used as an accessory for a section component. +type Thumbnail struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + Media UnfurledMediaItem `json:"media"` + Description *string `json:"description,omitempty"` + Spoiler bool `json:"spoiler,omitemoty"` +} + +// Type is a method to get the type of a component. +func (Thumbnail) Type() ComponentType { + return ThumbnailComponent +} + +// MarshalJSON is a method for marshaling Thumbnail to a JSON object. +func (t Thumbnail) MarshalJSON() ([]byte, error) { + type thumbnail Thumbnail + + return Marshal(struct { + thumbnail + Type ComponentType `json:"type"` + }{ + thumbnail: thumbnail(t), + Type: t.Type(), + }) +} + +// MediaGallery is a top-level component allows you to group images, videos or gifs into a gallery grid. +type MediaGallery struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + // Array of media gallery items; max of 10. + Items []MediaGalleryItem `json:"items"` +} + +// Type is a method to get the type of a component. +func (MediaGallery) Type() ComponentType { + return MediaGalleryComponent +} + +// MarshalJSON is a method for marshaling MediaGallery to a JSON object. +func (m MediaGallery) MarshalJSON() ([]byte, error) { + type mediaGallery MediaGallery + + return Marshal(struct { + mediaGallery + Type ComponentType `json:"type"` + }{ + mediaGallery: mediaGallery(m), + Type: m.Type(), + }) +} + +// MediaGalleryItem represents an item used in MediaGallery. +type MediaGalleryItem struct { + Media UnfurledMediaItem `json:"media"` + Description *string `json:"description,omitempty"` + Spoiler bool `json:"spoiler"` +} + +// FileComponent is a top-level component that allows you to display an uploaded file as an attachment to the message and reference it in the component. +type FileComponent struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + File UnfurledMediaItem `json:"file"` + Spoiler bool `json:"spoiler"` +} + +// Type is a method to get the type of a component. +func (FileComponent) Type() ComponentType { + return FileComponentType +} + +// MarshalJSON is a method for marshaling FileComponent to a JSON object. +func (f FileComponent) MarshalJSON() ([]byte, error) { + type fileComponent FileComponent + + return Marshal(struct { + fileComponent + Type ComponentType `json:"type"` + }{ + fileComponent: fileComponent(f), + Type: f.Type(), + }) +} + +// SeparatorSpacingSize represents spacing size around the separator. +type SeparatorSpacingSize uint + +// Separator spacing sizes. +const ( + SeparatorSpacingSizeSmall SeparatorSpacingSize = 1 + SeparatorSpacingSizeLarge SeparatorSpacingSize = 2 +) + +// Separator is a top-level layout component that adds vertical padding and visual division between other components. +type Separator struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + + Divider *bool `json:"divider,omitempty"` + Spacing *SeparatorSpacingSize `json:"spacing,omitempty"` +} + +// Type is a method to get the type of a component. +func (Separator) Type() ComponentType { + return SeparatorComponent +} + +// MarshalJSON is a method for marshaling Separator to a JSON object. +func (s Separator) MarshalJSON() ([]byte, error) { + type separator Separator + + return Marshal(struct { + separator + Type ComponentType `json:"type"` + }{ + separator: separator(s), + Type: s.Type(), + }) +} + +// Container is a top-level layout component. +// Containers are visually distinct from surrounding components and have an optional customizable color bar (similar to embeds). +type Container struct { + // Unique identifier for the component; auto populated through increment if not provided. + ID int `json:"id,omitempty"` + AccentColor *int `json:"accent_color,omitempty"` + Spoiler bool `json:"spoiler"` + Components []MessageComponent `json:"components"` +} + +// Type is a method to get the type of a component. +func (Container) Type() ComponentType { + return ContainerComponent +} + +// UnmarshalJSON is a method for unmarshaling Container from JSON +func (c *Container) UnmarshalJSON(data []byte) error { + type container Container + + var v struct { + container + RawComponents []unmarshalableMessageComponent `json:"components"` + } + + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + + *c = Container(v.container) + c.Components = make([]MessageComponent, len(v.RawComponents)) + for i, v := range v.RawComponents { + c.Components[i] = v.MessageComponent + } + + return nil +} + +// MarshalJSON is a method for marshaling Container to a JSON object. +func (c Container) MarshalJSON() ([]byte, error) { + type container Container + + return Marshal(struct { + container + Type ComponentType `json:"type"` + }{ + container: container(c), + Type: c.Type(), + }) +} + +// UnfurledMediaItem represents an unfurled media item. +type UnfurledMediaItem struct { + URL string `json:"url"` +} + +// UnfurledMediaItemLoadingState is the loading state of the unfurled media item. +type UnfurledMediaItemLoadingState uint + +// Unfurled media item loading states. +const ( + UnfurledMediaItemLoadingStateUnknown UnfurledMediaItemLoadingState = 0 + UnfurledMediaItemLoadingStateLoading UnfurledMediaItemLoadingState = 1 + UnfurledMediaItemLoadingStateLoadingSuccess UnfurledMediaItemLoadingState = 2 + UnfurledMediaItemLoadingStateLoadedNotFound UnfurledMediaItemLoadingState = 3 +) + +// ResolvedUnfurledMediaItem represents a resolved unfurled media item. +type ResolvedUnfurledMediaItem struct { + URL string `json:"url"` + ProxyURL string `json:"proxy_url"` + Width int `json:"width"` + Height int `json:"height"` + ContentType string `json:"content_type"` +} diff --git a/vendor/github.com/bwmarrin/discordgo/discord.go b/vendor/github.com/bwmarrin/discordgo/discord.go new file mode 100644 index 000000000..5d2574c36 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/discord.go @@ -0,0 +1,64 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains high level helper functions and easy entry points for the +// entire discordgo package. These functions are being developed and are very +// experimental at this point. They will most likely change so please use the +// low level functions if that's a problem. + +// Package discordgo provides Discord binding for Go +package discordgo + +import ( + "net/http" + "runtime" + "time" + + "github.com/gorilla/websocket" +) + +// VERSION of DiscordGo, follows Semantic Versioning. (http://semver.org/) +const VERSION = "0.29.0" + +// New creates a new Discord session with provided token. +// If the token is for a bot, it must be prefixed with "Bot " +// e.g. "Bot ..." +// Or if it is an OAuth2 token, it must be prefixed with "Bearer " +// e.g. "Bearer ..." +func New(token string) (s *Session, err error) { + + // Create an empty Session interface. + s = &Session{ + State: NewState(), + Ratelimiter: NewRatelimiter(), + StateEnabled: true, + Compress: true, + ShouldReconnectOnError: true, + ShouldReconnectVoiceOnSessionError: true, + ShouldRetryOnRateLimit: true, + ShardID: 0, + ShardCount: 1, + MaxRestRetries: 3, + Client: &http.Client{Timeout: (20 * time.Second)}, + Dialer: websocket.DefaultDialer, + UserAgent: "DiscordBot (https://github.com/bwmarrin/discordgo, v" + VERSION + ")", + sequence: new(int64), + LastHeartbeatAck: time.Now().UTC(), + } + + // Initialize the Identify Package with defaults + // These can be modified prior to calling Open() + s.Identify.Compress = true + s.Identify.LargeThreshold = 250 + s.Identify.Properties.OS = runtime.GOOS + s.Identify.Properties.Browser = "DiscordGo v" + VERSION + s.Identify.Intents = IntentsAllWithoutPrivileged + s.Identify.Token = token + s.Token = token + + return +} diff --git a/vendor/github.com/bwmarrin/discordgo/endpoints.go b/vendor/github.com/bwmarrin/discordgo/endpoints.go new file mode 100644 index 000000000..d0e32fede --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/endpoints.go @@ -0,0 +1,264 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains variables for all known Discord end points. All functions +// throughout the Discordgo package use these variables for all connections +// to Discord. These are all exported and you may modify them if needed. + +package discordgo + +import "strconv" + +// APIVersion is the Discord API version used for the REST and Websocket API. +var APIVersion = "9" + +// Known Discord API Endpoints. +var ( + EndpointStatus = "https://status.discord.com/api/v2/" + EndpointSm = EndpointStatus + "scheduled-maintenances/" + EndpointSmActive = EndpointSm + "active.json" + EndpointSmUpcoming = EndpointSm + "upcoming.json" + + EndpointDiscord = "https://discord.com/" + EndpointAPI = EndpointDiscord + "api/v" + APIVersion + "/" + EndpointGuilds = EndpointAPI + "guilds/" + EndpointChannels = EndpointAPI + "channels/" + EndpointUsers = EndpointAPI + "users/" + EndpointGateway = EndpointAPI + "gateway" + EndpointGatewayBot = EndpointGateway + "/bot" + EndpointWebhooks = EndpointAPI + "webhooks/" + EndpointStickers = EndpointAPI + "stickers/" + EndpointStageInstances = EndpointAPI + "stage-instances" + EndpointSKUs = EndpointAPI + "skus" + + EndpointCDN = "https://cdn.discordapp.com/" + EndpointCDNAttachments = EndpointCDN + "attachments/" + EndpointCDNAvatars = EndpointCDN + "avatars/" + EndpointCDNIcons = EndpointCDN + "icons/" + EndpointCDNSplashes = EndpointCDN + "splashes/" + EndpointCDNChannelIcons = EndpointCDN + "channel-icons/" + EndpointCDNBanners = EndpointCDN + "banners/" + EndpointCDNGuilds = EndpointCDN + "guilds/" + EndpointCDNRoleIcons = EndpointCDN + "role-icons/" + + EndpointVoice = EndpointAPI + "/voice/" + EndpointVoiceRegions = EndpointVoice + "regions" + + EndpointUser = func(uID string) string { return EndpointUsers + uID } + EndpointUserAvatar = func(uID, aID string) string { return EndpointCDNAvatars + uID + "/" + aID + ".png" } + EndpointUserAvatarAnimated = func(uID, aID string) string { return EndpointCDNAvatars + uID + "/" + aID + ".gif" } + EndpointDefaultUserAvatar = func(idx int) string { + return EndpointCDN + "embed/avatars/" + strconv.Itoa(idx) + ".png" + } + EndpointUserBanner = func(uID, cID string) string { + return EndpointCDNBanners + uID + "/" + cID + ".png" + } + EndpointUserBannerAnimated = func(uID, cID string) string { + return EndpointCDNBanners + uID + "/" + cID + ".gif" + } + + EndpointUserGuilds = func(uID string) string { return EndpointUsers + uID + "/guilds" } + EndpointUserGuild = func(uID, gID string) string { return EndpointUsers + uID + "/guilds/" + gID } + EndpointUserGuildMember = func(uID, gID string) string { return EndpointUserGuild(uID, gID) + "/member" } + EndpointUserChannels = func(uID string) string { return EndpointUsers + uID + "/channels" } + EndpointUserApplicationRoleConnection = func(aID string) string { return EndpointUsers + "@me/applications/" + aID + "/role-connection" } + EndpointUserConnections = func(uID string) string { return EndpointUsers + uID + "/connections" } + + EndpointGuild = func(gID string) string { return EndpointGuilds + gID } + EndpointGuildAutoModeration = func(gID string) string { return EndpointGuild(gID) + "/auto-moderation" } + EndpointGuildAutoModerationRules = func(gID string) string { return EndpointGuildAutoModeration(gID) + "/rules" } + EndpointGuildAutoModerationRule = func(gID, rID string) string { return EndpointGuildAutoModerationRules(gID) + "/" + rID } + EndpointGuildThreads = func(gID string) string { return EndpointGuild(gID) + "/threads" } + EndpointGuildActiveThreads = func(gID string) string { return EndpointGuildThreads(gID) + "/active" } + EndpointGuildPreview = func(gID string) string { return EndpointGuilds + gID + "/preview" } + EndpointGuildChannels = func(gID string) string { return EndpointGuilds + gID + "/channels" } + EndpointGuildMembers = func(gID string) string { return EndpointGuilds + gID + "/members" } + EndpointGuildMembersSearch = func(gID string) string { return EndpointGuildMembers(gID) + "/search" } + EndpointGuildMember = func(gID, uID string) string { return EndpointGuilds + gID + "/members/" + uID } + EndpointGuildMemberRole = func(gID, uID, rID string) string { return EndpointGuilds + gID + "/members/" + uID + "/roles/" + rID } + EndpointGuildBans = func(gID string) string { return EndpointGuilds + gID + "/bans" } + EndpointGuildBan = func(gID, uID string) string { return EndpointGuilds + gID + "/bans/" + uID } + EndpointGuildIntegrations = func(gID string) string { return EndpointGuilds + gID + "/integrations" } + EndpointGuildIntegration = func(gID, iID string) string { return EndpointGuilds + gID + "/integrations/" + iID } + EndpointGuildRoles = func(gID string) string { return EndpointGuilds + gID + "/roles" } + EndpointGuildRole = func(gID, rID string) string { return EndpointGuilds + gID + "/roles/" + rID } + EndpointGuildInvites = func(gID string) string { return EndpointGuilds + gID + "/invites" } + EndpointGuildWidget = func(gID string) string { return EndpointGuilds + gID + "/widget" } + EndpointGuildEmbed = EndpointGuildWidget + EndpointGuildPrune = func(gID string) string { return EndpointGuilds + gID + "/prune" } + EndpointGuildIcon = func(gID, hash string) string { return EndpointCDNIcons + gID + "/" + hash + ".png" } + EndpointGuildIconAnimated = func(gID, hash string) string { return EndpointCDNIcons + gID + "/" + hash + ".gif" } + EndpointGuildSplash = func(gID, hash string) string { return EndpointCDNSplashes + gID + "/" + hash + ".png" } + EndpointGuildWebhooks = func(gID string) string { return EndpointGuilds + gID + "/webhooks" } + EndpointGuildAuditLogs = func(gID string) string { return EndpointGuilds + gID + "/audit-logs" } + EndpointGuildEmojis = func(gID string) string { return EndpointGuilds + gID + "/emojis" } + EndpointGuildEmoji = func(gID, eID string) string { return EndpointGuilds + gID + "/emojis/" + eID } + EndpointGuildBanner = func(gID, hash string) string { return EndpointCDNBanners + gID + "/" + hash + ".png" } + EndpointGuildBannerAnimated = func(gID, hash string) string { return EndpointCDNBanners + gID + "/" + hash + ".gif" } + EndpointGuildStickers = func(gID string) string { return EndpointGuilds + gID + "/stickers" } + EndpointGuildSticker = func(gID, sID string) string { return EndpointGuilds + gID + "/stickers/" + sID } + EndpointStageInstance = func(cID string) string { return EndpointStageInstances + "/" + cID } + EndpointGuildScheduledEvents = func(gID string) string { return EndpointGuilds + gID + "/scheduled-events" } + EndpointGuildScheduledEvent = func(gID, eID string) string { return EndpointGuilds + gID + "/scheduled-events/" + eID } + EndpointGuildScheduledEventUsers = func(gID, eID string) string { return EndpointGuildScheduledEvent(gID, eID) + "/users" } + EndpointGuildOnboarding = func(gID string) string { return EndpointGuilds + gID + "/onboarding" } + EndpointGuildTemplate = func(tID string) string { return EndpointGuilds + "templates/" + tID } + EndpointGuildTemplates = func(gID string) string { return EndpointGuilds + gID + "/templates" } + EndpointGuildTemplateSync = func(gID, tID string) string { return EndpointGuilds + gID + "/templates/" + tID } + EndpointGuildMemberAvatar = func(gId, uID, aID string) string { + return EndpointCDNGuilds + gId + "/users/" + uID + "/avatars/" + aID + ".png" + } + EndpointGuildMemberAvatarAnimated = func(gId, uID, aID string) string { + return EndpointCDNGuilds + gId + "/users/" + uID + "/avatars/" + aID + ".gif" + } + EndpointGuildMemberBanner = func(gId, uID, hash string) string { + return EndpointCDNGuilds + gId + "/users/" + uID + "/banners/" + hash + ".png" + } + EndpointGuildMemberBannerAnimated = func(gId, uID, hash string) string { + return EndpointCDNGuilds + gId + "/users/" + uID + "/banners/" + hash + ".gif" + } + + EndpointRoleIcon = func(rID, hash string) string { + return EndpointCDNRoleIcons + rID + "/" + hash + ".png" + } + + EndpointChannel = func(cID string) string { return EndpointChannels + cID } + EndpointChannelThreads = func(cID string) string { return EndpointChannel(cID) + "/threads" } + EndpointChannelActiveThreads = func(cID string) string { return EndpointChannelThreads(cID) + "/active" } + EndpointChannelPublicArchivedThreads = func(cID string) string { return EndpointChannelThreads(cID) + "/archived/public" } + EndpointChannelPrivateArchivedThreads = func(cID string) string { return EndpointChannelThreads(cID) + "/archived/private" } + EndpointChannelJoinedPrivateArchivedThreads = func(cID string) string { return EndpointChannel(cID) + "/users/@me/threads/archived/private" } + EndpointChannelPermissions = func(cID string) string { return EndpointChannels + cID + "/permissions" } + EndpointChannelPermission = func(cID, tID string) string { return EndpointChannels + cID + "/permissions/" + tID } + EndpointChannelInvites = func(cID string) string { return EndpointChannels + cID + "/invites" } + EndpointChannelTyping = func(cID string) string { return EndpointChannels + cID + "/typing" } + EndpointChannelMessages = func(cID string) string { return EndpointChannels + cID + "/messages" } + EndpointChannelMessage = func(cID, mID string) string { return EndpointChannels + cID + "/messages/" + mID } + EndpointChannelMessageThread = func(cID, mID string) string { return EndpointChannelMessage(cID, mID) + "/threads" } + EndpointChannelMessagesBulkDelete = func(cID string) string { return EndpointChannel(cID) + "/messages/bulk-delete" } + EndpointChannelMessagesPins = func(cID string) string { return EndpointChannel(cID) + "/pins" } + EndpointChannelMessagePin = func(cID, mID string) string { return EndpointChannel(cID) + "/pins/" + mID } + EndpointChannelMessageCrosspost = func(cID, mID string) string { return EndpointChannel(cID) + "/messages/" + mID + "/crosspost" } + EndpointChannelFollow = func(cID string) string { return EndpointChannel(cID) + "/followers" } + EndpointThreadMembers = func(tID string) string { return EndpointChannel(tID) + "/thread-members" } + EndpointThreadMember = func(tID, mID string) string { return EndpointThreadMembers(tID) + "/" + mID } + + EndpointGroupIcon = func(cID, hash string) string { return EndpointCDNChannelIcons + cID + "/" + hash + ".png" } + + EndpointSticker = func(sID string) string { return EndpointStickers + sID } + EndpointNitroStickersPacks = EndpointAPI + "/sticker-packs" + + EndpointChannelWebhooks = func(cID string) string { return EndpointChannel(cID) + "/webhooks" } + EndpointWebhook = func(wID string) string { return EndpointWebhooks + wID } + EndpointWebhookToken = func(wID, token string) string { return EndpointWebhooks + wID + "/" + token } + EndpointWebhookMessage = func(wID, token, messageID string) string { + return EndpointWebhookToken(wID, token) + "/messages/" + messageID + } + + EndpointMessageReactionsAll = func(cID, mID string) string { + return EndpointChannelMessage(cID, mID) + "/reactions" + } + EndpointMessageReactions = func(cID, mID, eID string) string { + return EndpointChannelMessage(cID, mID) + "/reactions/" + eID + } + EndpointMessageReaction = func(cID, mID, eID, uID string) string { + return EndpointMessageReactions(cID, mID, eID) + "/" + uID + } + + EndpointPoll = func(cID, mID string) string { + return EndpointChannel(cID) + "/polls/" + mID + } + EndpointPollAnswerVoters = func(cID, mID string, aID int) string { + return EndpointPoll(cID, mID) + "/answers/" + strconv.Itoa(aID) + } + EndpointPollExpire = func(cID, mID string) string { + return EndpointPoll(cID, mID) + "/expire" + } + + EndpointApplicationSKUs = func(aID string) string { + return EndpointApplication(aID) + "/skus" + } + + EndpointEntitlements = func(aID string) string { + return EndpointApplication(aID) + "/entitlements" + } + EndpointEntitlement = func(aID, eID string) string { + return EndpointEntitlements(aID) + "/" + eID + } + EndpointEntitlementConsume = func(aID, eID string) string { + return EndpointEntitlement(aID, eID) + "/consume" + } + + EndpointSubscriptions = func(skuID string) string { + return EndpointSKUs + "/" + skuID + "/subscriptions" + } + EndpointSubscription = func(skuID, subID string) string { + return EndpointSubscriptions(skuID) + "/" + subID + } + + EndpointApplicationGlobalCommands = func(aID string) string { + return EndpointApplication(aID) + "/commands" + } + EndpointApplicationGlobalCommand = func(aID, cID string) string { + return EndpointApplicationGlobalCommands(aID) + "/" + cID + } + + EndpointApplicationGuildCommands = func(aID, gID string) string { + return EndpointApplication(aID) + "/guilds/" + gID + "/commands" + } + EndpointApplicationGuildCommand = func(aID, gID, cID string) string { + return EndpointApplicationGuildCommands(aID, gID) + "/" + cID + } + EndpointApplicationCommandPermissions = func(aID, gID, cID string) string { + return EndpointApplicationGuildCommand(aID, gID, cID) + "/permissions" + } + EndpointApplicationCommandsGuildPermissions = func(aID, gID string) string { + return EndpointApplicationGuildCommands(aID, gID) + "/permissions" + } + EndpointInteraction = func(aID, iToken string) string { + return EndpointAPI + "interactions/" + aID + "/" + iToken + } + EndpointInteractionResponse = func(iID, iToken string) string { + return EndpointInteraction(iID, iToken) + "/callback" + } + EndpointInteractionResponseActions = func(aID, iToken string) string { + return EndpointWebhookMessage(aID, iToken, "@original") + } + EndpointFollowupMessage = func(aID, iToken string) string { + return EndpointWebhookToken(aID, iToken) + } + EndpointFollowupMessageActions = func(aID, iToken, mID string) string { + return EndpointWebhookMessage(aID, iToken, mID) + } + + EndpointGuildCreate = EndpointAPI + "guilds" + + EndpointInvite = func(iID string) string { return EndpointAPI + "invites/" + iID } + + EndpointEmoji = func(eID string) string { return EndpointCDN + "emojis/" + eID + ".png" } + EndpointEmojiAnimated = func(eID string) string { return EndpointCDN + "emojis/" + eID + ".gif" } + + EndpointApplications = EndpointAPI + "applications" + EndpointApplication = func(aID string) string { return EndpointApplications + "/" + aID } + EndpointApplicationRoleConnectionMetadata = func(aID string) string { return EndpointApplication(aID) + "/role-connections/metadata" } + + EndpointApplicationEmojis = func(aID string) string { return EndpointApplication(aID) + "/emojis" } + EndpointApplicationEmoji = func(aID, eID string) string { return EndpointApplication(aID) + "/emojis/" + eID } + + EndpointOAuth2 = EndpointAPI + "oauth2/" + EndpointOAuth2Applications = EndpointOAuth2 + "applications" + EndpointOAuth2Application = func(aID string) string { return EndpointOAuth2Applications + "/" + aID } + EndpointOAuth2ApplicationsBot = func(aID string) string { return EndpointOAuth2Applications + "/" + aID + "/bot" } + EndpointOAuth2ApplicationAssets = func(aID string) string { return EndpointOAuth2Applications + "/" + aID + "/assets" } + + // TODO: Deprecated, remove in the next release + EndpointOauth2 = EndpointOAuth2 + EndpointOauth2Applications = EndpointOAuth2Applications + EndpointOauth2Application = EndpointOAuth2Application + EndpointOauth2ApplicationsBot = EndpointOAuth2ApplicationsBot + EndpointOauth2ApplicationAssets = EndpointOAuth2ApplicationAssets +) diff --git a/vendor/github.com/bwmarrin/discordgo/event.go b/vendor/github.com/bwmarrin/discordgo/event.go new file mode 100644 index 000000000..84dbdc7fb --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/event.go @@ -0,0 +1,247 @@ +package discordgo + +// EventHandler is an interface for Discord events. +type EventHandler interface { + // Type returns the type of event this handler belongs to. + Type() string + + // Handle is called whenever an event of Type() happens. + // It is the receivers responsibility to type assert that the interface + // is the expected struct. + Handle(*Session, interface{}) +} + +// EventInterfaceProvider is an interface for providing empty interfaces for +// Discord events. +type EventInterfaceProvider interface { + // Type is the type of event this handler belongs to. + Type() string + + // New returns a new instance of the struct this event handler handles. + // This is called once per event. + // The struct is provided to all handlers of the same Type(). + New() interface{} +} + +// interfaceEventType is the event handler type for interface{} events. +const interfaceEventType = "__INTERFACE__" + +// interfaceEventHandler is an event handler for interface{} events. +type interfaceEventHandler func(*Session, interface{}) + +// Type returns the event type for interface{} events. +func (eh interfaceEventHandler) Type() string { + return interfaceEventType +} + +// Handle is the handler for an interface{} event. +func (eh interfaceEventHandler) Handle(s *Session, i interface{}) { + eh(s, i) +} + +var registeredInterfaceProviders = map[string]EventInterfaceProvider{} + +// registerInterfaceProvider registers a provider so that DiscordGo can +// access it's New() method. +func registerInterfaceProvider(eh EventInterfaceProvider) { + if _, ok := registeredInterfaceProviders[eh.Type()]; ok { + return + // XXX: + // if we should error here, we need to do something with it. + // fmt.Errorf("event %s already registered", eh.Type()) + } + registeredInterfaceProviders[eh.Type()] = eh + return +} + +// eventHandlerInstance is a wrapper around an event handler, as functions +// cannot be compared directly. +type eventHandlerInstance struct { + eventHandler EventHandler +} + +// addEventHandler adds an event handler that will be fired anytime +// the Discord WSAPI matching eventHandler.Type() fires. +func (s *Session) addEventHandler(eventHandler EventHandler) func() { + s.handlersMu.Lock() + defer s.handlersMu.Unlock() + + if s.handlers == nil { + s.handlers = map[string][]*eventHandlerInstance{} + } + + ehi := &eventHandlerInstance{eventHandler} + s.handlers[eventHandler.Type()] = append(s.handlers[eventHandler.Type()], ehi) + + return func() { + s.removeEventHandlerInstance(eventHandler.Type(), ehi) + } +} + +// addEventHandler adds an event handler that will be fired the next time +// the Discord WSAPI matching eventHandler.Type() fires. +func (s *Session) addEventHandlerOnce(eventHandler EventHandler) func() { + s.handlersMu.Lock() + defer s.handlersMu.Unlock() + + if s.onceHandlers == nil { + s.onceHandlers = map[string][]*eventHandlerInstance{} + } + + ehi := &eventHandlerInstance{eventHandler} + s.onceHandlers[eventHandler.Type()] = append(s.onceHandlers[eventHandler.Type()], ehi) + + return func() { + s.removeEventHandlerInstance(eventHandler.Type(), ehi) + } +} + +// AddHandler allows you to add an event handler that will be fired anytime +// the Discord WSAPI event that matches the function fires. +// The first parameter is a *Session, and the second parameter is a pointer +// to a struct corresponding to the event for which you want to listen. +// +// eg: +// Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) { +// }) +// +// or: +// Session.AddHandler(func(s *discordgo.Session, m *discordgo.PresenceUpdate) { +// }) +// +// List of events can be found at this page, with corresponding names in the +// library for each event: https://discord.com/developers/docs/topics/gateway#event-names +// There are also synthetic events fired by the library internally which are +// available for handling, like Connect, Disconnect, and RateLimit. +// events.go contains all of the Discord WSAPI and synthetic events that can be handled. +// +// The return value of this method is a function, that when called will remove the +// event handler. +func (s *Session) AddHandler(handler interface{}) func() { + eh := handlerForInterface(handler) + + if eh == nil { + s.log(LogError, "Invalid handler type, handler will never be called") + return func() {} + } + + return s.addEventHandler(eh) +} + +// AddHandlerOnce allows you to add an event handler that will be fired the next time +// the Discord WSAPI event that matches the function fires. +// See AddHandler for more details. +func (s *Session) AddHandlerOnce(handler interface{}) func() { + eh := handlerForInterface(handler) + + if eh == nil { + s.log(LogError, "Invalid handler type, handler will never be called") + return func() {} + } + + return s.addEventHandlerOnce(eh) +} + +// removeEventHandler instance removes an event handler instance. +func (s *Session) removeEventHandlerInstance(t string, ehi *eventHandlerInstance) { + s.handlersMu.Lock() + defer s.handlersMu.Unlock() + + handlers := s.handlers[t] + for i := range handlers { + if handlers[i] == ehi { + s.handlers[t] = append(handlers[:i], handlers[i+1:]...) + } + } + + onceHandlers := s.onceHandlers[t] + for i := range onceHandlers { + if onceHandlers[i] == ehi { + s.onceHandlers[t] = append(onceHandlers[:i], onceHandlers[i+1:]...) + } + } +} + +// Handles calling permanent and once handlers for an event type. +func (s *Session) handle(t string, i interface{}) { + for _, eh := range s.handlers[t] { + if s.SyncEvents { + eh.eventHandler.Handle(s, i) + } else { + go eh.eventHandler.Handle(s, i) + } + } + + if len(s.onceHandlers[t]) > 0 { + for _, eh := range s.onceHandlers[t] { + if s.SyncEvents { + eh.eventHandler.Handle(s, i) + } else { + go eh.eventHandler.Handle(s, i) + } + } + s.onceHandlers[t] = nil + } +} + +// Handles an event type by calling internal methods, firing handlers and firing the +// interface{} event. +func (s *Session) handleEvent(t string, i interface{}) { + s.handlersMu.RLock() + defer s.handlersMu.RUnlock() + + // All events are dispatched internally first. + s.onInterface(i) + + // Then they are dispatched to anyone handling interface{} events. + s.handle(interfaceEventType, i) + + // Finally they are dispatched to any typed handlers. + s.handle(t, i) +} + +// setGuildIds will set the GuildID on all the members of a guild. +// This is done as event data does not have it set. +func setGuildIds(g *Guild) { + for _, c := range g.Channels { + c.GuildID = g.ID + } + + for _, m := range g.Members { + m.GuildID = g.ID + } + + for _, vs := range g.VoiceStates { + vs.GuildID = g.ID + } +} + +// onInterface handles all internal events and routes them to the appropriate internal handler. +func (s *Session) onInterface(i interface{}) { + switch t := i.(type) { + case *Ready: + for _, g := range t.Guilds { + setGuildIds(g) + } + s.onReady(t) + case *GuildCreate: + setGuildIds(t.Guild) + case *GuildUpdate: + setGuildIds(t.Guild) + case *VoiceServerUpdate: + go s.onVoiceServerUpdate(t) + case *VoiceStateUpdate: + go s.onVoiceStateUpdate(t) + } + err := s.State.OnInterface(s, i) + if err != nil { + s.log(LogDebug, "error dispatching internal event, %s", err) + } +} + +// onReady handles the ready event. +func (s *Session) onReady(r *Ready) { + + // Store the SessionID within the Session struct. + s.sessionID = r.SessionID +} diff --git a/vendor/github.com/bwmarrin/discordgo/eventhandlers.go b/vendor/github.com/bwmarrin/discordgo/eventhandlers.go new file mode 100644 index 000000000..b3569a70f --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/eventhandlers.go @@ -0,0 +1,1750 @@ +// Code generated by \"eventhandlers\"; DO NOT EDIT +// See events.go + +package discordgo + +// Following are all the event types. +// Event type values are used to match the events returned by Discord. +// EventTypes surrounded by __ are synthetic and are internal to DiscordGo. +const ( + applicationCommandPermissionsUpdateEventType = "APPLICATION_COMMAND_PERMISSIONS_UPDATE" + autoModerationActionExecutionEventType = "AUTO_MODERATION_ACTION_EXECUTION" + autoModerationRuleCreateEventType = "AUTO_MODERATION_RULE_CREATE" + autoModerationRuleDeleteEventType = "AUTO_MODERATION_RULE_DELETE" + autoModerationRuleUpdateEventType = "AUTO_MODERATION_RULE_UPDATE" + channelCreateEventType = "CHANNEL_CREATE" + channelDeleteEventType = "CHANNEL_DELETE" + channelPinsUpdateEventType = "CHANNEL_PINS_UPDATE" + channelUpdateEventType = "CHANNEL_UPDATE" + connectEventType = "__CONNECT__" + disconnectEventType = "__DISCONNECT__" + entitlementCreateEventType = "ENTITLEMENT_CREATE" + entitlementDeleteEventType = "ENTITLEMENT_DELETE" + entitlementUpdateEventType = "ENTITLEMENT_UPDATE" + eventEventType = "__EVENT__" + guildAuditLogEntryCreateEventType = "GUILD_AUDIT_LOG_ENTRY_CREATE" + guildBanAddEventType = "GUILD_BAN_ADD" + guildBanRemoveEventType = "GUILD_BAN_REMOVE" + guildCreateEventType = "GUILD_CREATE" + guildDeleteEventType = "GUILD_DELETE" + guildEmojisUpdateEventType = "GUILD_EMOJIS_UPDATE" + guildIntegrationsUpdateEventType = "GUILD_INTEGRATIONS_UPDATE" + guildMemberAddEventType = "GUILD_MEMBER_ADD" + guildMemberRemoveEventType = "GUILD_MEMBER_REMOVE" + guildMemberUpdateEventType = "GUILD_MEMBER_UPDATE" + guildMembersChunkEventType = "GUILD_MEMBERS_CHUNK" + guildRoleCreateEventType = "GUILD_ROLE_CREATE" + guildRoleDeleteEventType = "GUILD_ROLE_DELETE" + guildRoleUpdateEventType = "GUILD_ROLE_UPDATE" + guildScheduledEventCreateEventType = "GUILD_SCHEDULED_EVENT_CREATE" + guildScheduledEventDeleteEventType = "GUILD_SCHEDULED_EVENT_DELETE" + guildScheduledEventUpdateEventType = "GUILD_SCHEDULED_EVENT_UPDATE" + guildScheduledEventUserAddEventType = "GUILD_SCHEDULED_EVENT_USER_ADD" + guildScheduledEventUserRemoveEventType = "GUILD_SCHEDULED_EVENT_USER_REMOVE" + guildStickersUpdateEventType = "GUILD_STICKERS_UPDATE" + guildUpdateEventType = "GUILD_UPDATE" + integrationCreateEventType = "INTEGRATION_CREATE" + integrationDeleteEventType = "INTEGRATION_DELETE" + integrationUpdateEventType = "INTEGRATION_UPDATE" + interactionCreateEventType = "INTERACTION_CREATE" + inviteCreateEventType = "INVITE_CREATE" + inviteDeleteEventType = "INVITE_DELETE" + messageCreateEventType = "MESSAGE_CREATE" + messageDeleteEventType = "MESSAGE_DELETE" + messageDeleteBulkEventType = "MESSAGE_DELETE_BULK" + messagePollVoteAddEventType = "MESSAGE_POLL_VOTE_ADD" + messagePollVoteRemoveEventType = "MESSAGE_POLL_VOTE_REMOVE" + messageReactionAddEventType = "MESSAGE_REACTION_ADD" + messageReactionRemoveEventType = "MESSAGE_REACTION_REMOVE" + messageReactionRemoveAllEventType = "MESSAGE_REACTION_REMOVE_ALL" + messageUpdateEventType = "MESSAGE_UPDATE" + presenceUpdateEventType = "PRESENCE_UPDATE" + presencesReplaceEventType = "PRESENCES_REPLACE" + rateLimitEventType = "__RATE_LIMIT__" + readyEventType = "READY" + resumedEventType = "RESUMED" + stageInstanceEventCreateEventType = "STAGE_INSTANCE_EVENT_CREATE" + stageInstanceEventDeleteEventType = "STAGE_INSTANCE_EVENT_DELETE" + stageInstanceEventUpdateEventType = "STAGE_INSTANCE_EVENT_UPDATE" + subscriptionCreateEventType = "SUBSCRIPTION_CREATE" + subscriptionDeleteEventType = "SUBSCRIPTION_DELETE" + subscriptionUpdateEventType = "SUBSCRIPTION_UPDATE" + threadCreateEventType = "THREAD_CREATE" + threadDeleteEventType = "THREAD_DELETE" + threadListSyncEventType = "THREAD_LIST_SYNC" + threadMemberUpdateEventType = "THREAD_MEMBER_UPDATE" + threadMembersUpdateEventType = "THREAD_MEMBERS_UPDATE" + threadUpdateEventType = "THREAD_UPDATE" + typingStartEventType = "TYPING_START" + userUpdateEventType = "USER_UPDATE" + voiceServerUpdateEventType = "VOICE_SERVER_UPDATE" + voiceStateUpdateEventType = "VOICE_STATE_UPDATE" + webhooksUpdateEventType = "WEBHOOKS_UPDATE" +) + +// applicationCommandPermissionsUpdateEventHandler is an event handler for ApplicationCommandPermissionsUpdate events. +type applicationCommandPermissionsUpdateEventHandler func(*Session, *ApplicationCommandPermissionsUpdate) + +// Type returns the event type for ApplicationCommandPermissionsUpdate events. +func (eh applicationCommandPermissionsUpdateEventHandler) Type() string { + return applicationCommandPermissionsUpdateEventType +} + +// New returns a new instance of ApplicationCommandPermissionsUpdate. +func (eh applicationCommandPermissionsUpdateEventHandler) New() interface{} { + return &ApplicationCommandPermissionsUpdate{} +} + +// Handle is the handler for ApplicationCommandPermissionsUpdate events. +func (eh applicationCommandPermissionsUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ApplicationCommandPermissionsUpdate); ok { + eh(s, t) + } +} + +// autoModerationActionExecutionEventHandler is an event handler for AutoModerationActionExecution events. +type autoModerationActionExecutionEventHandler func(*Session, *AutoModerationActionExecution) + +// Type returns the event type for AutoModerationActionExecution events. +func (eh autoModerationActionExecutionEventHandler) Type() string { + return autoModerationActionExecutionEventType +} + +// New returns a new instance of AutoModerationActionExecution. +func (eh autoModerationActionExecutionEventHandler) New() interface{} { + return &AutoModerationActionExecution{} +} + +// Handle is the handler for AutoModerationActionExecution events. +func (eh autoModerationActionExecutionEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*AutoModerationActionExecution); ok { + eh(s, t) + } +} + +// autoModerationRuleCreateEventHandler is an event handler for AutoModerationRuleCreate events. +type autoModerationRuleCreateEventHandler func(*Session, *AutoModerationRuleCreate) + +// Type returns the event type for AutoModerationRuleCreate events. +func (eh autoModerationRuleCreateEventHandler) Type() string { + return autoModerationRuleCreateEventType +} + +// New returns a new instance of AutoModerationRuleCreate. +func (eh autoModerationRuleCreateEventHandler) New() interface{} { + return &AutoModerationRuleCreate{} +} + +// Handle is the handler for AutoModerationRuleCreate events. +func (eh autoModerationRuleCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*AutoModerationRuleCreate); ok { + eh(s, t) + } +} + +// autoModerationRuleDeleteEventHandler is an event handler for AutoModerationRuleDelete events. +type autoModerationRuleDeleteEventHandler func(*Session, *AutoModerationRuleDelete) + +// Type returns the event type for AutoModerationRuleDelete events. +func (eh autoModerationRuleDeleteEventHandler) Type() string { + return autoModerationRuleDeleteEventType +} + +// New returns a new instance of AutoModerationRuleDelete. +func (eh autoModerationRuleDeleteEventHandler) New() interface{} { + return &AutoModerationRuleDelete{} +} + +// Handle is the handler for AutoModerationRuleDelete events. +func (eh autoModerationRuleDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*AutoModerationRuleDelete); ok { + eh(s, t) + } +} + +// autoModerationRuleUpdateEventHandler is an event handler for AutoModerationRuleUpdate events. +type autoModerationRuleUpdateEventHandler func(*Session, *AutoModerationRuleUpdate) + +// Type returns the event type for AutoModerationRuleUpdate events. +func (eh autoModerationRuleUpdateEventHandler) Type() string { + return autoModerationRuleUpdateEventType +} + +// New returns a new instance of AutoModerationRuleUpdate. +func (eh autoModerationRuleUpdateEventHandler) New() interface{} { + return &AutoModerationRuleUpdate{} +} + +// Handle is the handler for AutoModerationRuleUpdate events. +func (eh autoModerationRuleUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*AutoModerationRuleUpdate); ok { + eh(s, t) + } +} + +// channelCreateEventHandler is an event handler for ChannelCreate events. +type channelCreateEventHandler func(*Session, *ChannelCreate) + +// Type returns the event type for ChannelCreate events. +func (eh channelCreateEventHandler) Type() string { + return channelCreateEventType +} + +// New returns a new instance of ChannelCreate. +func (eh channelCreateEventHandler) New() interface{} { + return &ChannelCreate{} +} + +// Handle is the handler for ChannelCreate events. +func (eh channelCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ChannelCreate); ok { + eh(s, t) + } +} + +// channelDeleteEventHandler is an event handler for ChannelDelete events. +type channelDeleteEventHandler func(*Session, *ChannelDelete) + +// Type returns the event type for ChannelDelete events. +func (eh channelDeleteEventHandler) Type() string { + return channelDeleteEventType +} + +// New returns a new instance of ChannelDelete. +func (eh channelDeleteEventHandler) New() interface{} { + return &ChannelDelete{} +} + +// Handle is the handler for ChannelDelete events. +func (eh channelDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ChannelDelete); ok { + eh(s, t) + } +} + +// channelPinsUpdateEventHandler is an event handler for ChannelPinsUpdate events. +type channelPinsUpdateEventHandler func(*Session, *ChannelPinsUpdate) + +// Type returns the event type for ChannelPinsUpdate events. +func (eh channelPinsUpdateEventHandler) Type() string { + return channelPinsUpdateEventType +} + +// New returns a new instance of ChannelPinsUpdate. +func (eh channelPinsUpdateEventHandler) New() interface{} { + return &ChannelPinsUpdate{} +} + +// Handle is the handler for ChannelPinsUpdate events. +func (eh channelPinsUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ChannelPinsUpdate); ok { + eh(s, t) + } +} + +// channelUpdateEventHandler is an event handler for ChannelUpdate events. +type channelUpdateEventHandler func(*Session, *ChannelUpdate) + +// Type returns the event type for ChannelUpdate events. +func (eh channelUpdateEventHandler) Type() string { + return channelUpdateEventType +} + +// New returns a new instance of ChannelUpdate. +func (eh channelUpdateEventHandler) New() interface{} { + return &ChannelUpdate{} +} + +// Handle is the handler for ChannelUpdate events. +func (eh channelUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ChannelUpdate); ok { + eh(s, t) + } +} + +// connectEventHandler is an event handler for Connect events. +type connectEventHandler func(*Session, *Connect) + +// Type returns the event type for Connect events. +func (eh connectEventHandler) Type() string { + return connectEventType +} + +// Handle is the handler for Connect events. +func (eh connectEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*Connect); ok { + eh(s, t) + } +} + +// disconnectEventHandler is an event handler for Disconnect events. +type disconnectEventHandler func(*Session, *Disconnect) + +// Type returns the event type for Disconnect events. +func (eh disconnectEventHandler) Type() string { + return disconnectEventType +} + +// Handle is the handler for Disconnect events. +func (eh disconnectEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*Disconnect); ok { + eh(s, t) + } +} + +// entitlementCreateEventHandler is an event handler for EntitlementCreate events. +type entitlementCreateEventHandler func(*Session, *EntitlementCreate) + +// Type returns the event type for EntitlementCreate events. +func (eh entitlementCreateEventHandler) Type() string { + return entitlementCreateEventType +} + +// New returns a new instance of EntitlementCreate. +func (eh entitlementCreateEventHandler) New() interface{} { + return &EntitlementCreate{} +} + +// Handle is the handler for EntitlementCreate events. +func (eh entitlementCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*EntitlementCreate); ok { + eh(s, t) + } +} + +// entitlementDeleteEventHandler is an event handler for EntitlementDelete events. +type entitlementDeleteEventHandler func(*Session, *EntitlementDelete) + +// Type returns the event type for EntitlementDelete events. +func (eh entitlementDeleteEventHandler) Type() string { + return entitlementDeleteEventType +} + +// New returns a new instance of EntitlementDelete. +func (eh entitlementDeleteEventHandler) New() interface{} { + return &EntitlementDelete{} +} + +// Handle is the handler for EntitlementDelete events. +func (eh entitlementDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*EntitlementDelete); ok { + eh(s, t) + } +} + +// entitlementUpdateEventHandler is an event handler for EntitlementUpdate events. +type entitlementUpdateEventHandler func(*Session, *EntitlementUpdate) + +// Type returns the event type for EntitlementUpdate events. +func (eh entitlementUpdateEventHandler) Type() string { + return entitlementUpdateEventType +} + +// New returns a new instance of EntitlementUpdate. +func (eh entitlementUpdateEventHandler) New() interface{} { + return &EntitlementUpdate{} +} + +// Handle is the handler for EntitlementUpdate events. +func (eh entitlementUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*EntitlementUpdate); ok { + eh(s, t) + } +} + +// eventEventHandler is an event handler for Event events. +type eventEventHandler func(*Session, *Event) + +// Type returns the event type for Event events. +func (eh eventEventHandler) Type() string { + return eventEventType +} + +// Handle is the handler for Event events. +func (eh eventEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*Event); ok { + eh(s, t) + } +} + +// guildAuditLogEntryCreateEventHandler is an event handler for GuildAuditLogEntryCreate events. +type guildAuditLogEntryCreateEventHandler func(*Session, *GuildAuditLogEntryCreate) + +// Type returns the event type for GuildAuditLogEntryCreate events. +func (eh guildAuditLogEntryCreateEventHandler) Type() string { + return guildAuditLogEntryCreateEventType +} + +// New returns a new instance of GuildAuditLogEntryCreate. +func (eh guildAuditLogEntryCreateEventHandler) New() interface{} { + return &GuildAuditLogEntryCreate{} +} + +// Handle is the handler for GuildAuditLogEntryCreate events. +func (eh guildAuditLogEntryCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildAuditLogEntryCreate); ok { + eh(s, t) + } +} + +// guildBanAddEventHandler is an event handler for GuildBanAdd events. +type guildBanAddEventHandler func(*Session, *GuildBanAdd) + +// Type returns the event type for GuildBanAdd events. +func (eh guildBanAddEventHandler) Type() string { + return guildBanAddEventType +} + +// New returns a new instance of GuildBanAdd. +func (eh guildBanAddEventHandler) New() interface{} { + return &GuildBanAdd{} +} + +// Handle is the handler for GuildBanAdd events. +func (eh guildBanAddEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildBanAdd); ok { + eh(s, t) + } +} + +// guildBanRemoveEventHandler is an event handler for GuildBanRemove events. +type guildBanRemoveEventHandler func(*Session, *GuildBanRemove) + +// Type returns the event type for GuildBanRemove events. +func (eh guildBanRemoveEventHandler) Type() string { + return guildBanRemoveEventType +} + +// New returns a new instance of GuildBanRemove. +func (eh guildBanRemoveEventHandler) New() interface{} { + return &GuildBanRemove{} +} + +// Handle is the handler for GuildBanRemove events. +func (eh guildBanRemoveEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildBanRemove); ok { + eh(s, t) + } +} + +// guildCreateEventHandler is an event handler for GuildCreate events. +type guildCreateEventHandler func(*Session, *GuildCreate) + +// Type returns the event type for GuildCreate events. +func (eh guildCreateEventHandler) Type() string { + return guildCreateEventType +} + +// New returns a new instance of GuildCreate. +func (eh guildCreateEventHandler) New() interface{} { + return &GuildCreate{} +} + +// Handle is the handler for GuildCreate events. +func (eh guildCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildCreate); ok { + eh(s, t) + } +} + +// guildDeleteEventHandler is an event handler for GuildDelete events. +type guildDeleteEventHandler func(*Session, *GuildDelete) + +// Type returns the event type for GuildDelete events. +func (eh guildDeleteEventHandler) Type() string { + return guildDeleteEventType +} + +// New returns a new instance of GuildDelete. +func (eh guildDeleteEventHandler) New() interface{} { + return &GuildDelete{} +} + +// Handle is the handler for GuildDelete events. +func (eh guildDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildDelete); ok { + eh(s, t) + } +} + +// guildEmojisUpdateEventHandler is an event handler for GuildEmojisUpdate events. +type guildEmojisUpdateEventHandler func(*Session, *GuildEmojisUpdate) + +// Type returns the event type for GuildEmojisUpdate events. +func (eh guildEmojisUpdateEventHandler) Type() string { + return guildEmojisUpdateEventType +} + +// New returns a new instance of GuildEmojisUpdate. +func (eh guildEmojisUpdateEventHandler) New() interface{} { + return &GuildEmojisUpdate{} +} + +// Handle is the handler for GuildEmojisUpdate events. +func (eh guildEmojisUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildEmojisUpdate); ok { + eh(s, t) + } +} + +// guildIntegrationsUpdateEventHandler is an event handler for GuildIntegrationsUpdate events. +type guildIntegrationsUpdateEventHandler func(*Session, *GuildIntegrationsUpdate) + +// Type returns the event type for GuildIntegrationsUpdate events. +func (eh guildIntegrationsUpdateEventHandler) Type() string { + return guildIntegrationsUpdateEventType +} + +// New returns a new instance of GuildIntegrationsUpdate. +func (eh guildIntegrationsUpdateEventHandler) New() interface{} { + return &GuildIntegrationsUpdate{} +} + +// Handle is the handler for GuildIntegrationsUpdate events. +func (eh guildIntegrationsUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildIntegrationsUpdate); ok { + eh(s, t) + } +} + +// guildMemberAddEventHandler is an event handler for GuildMemberAdd events. +type guildMemberAddEventHandler func(*Session, *GuildMemberAdd) + +// Type returns the event type for GuildMemberAdd events. +func (eh guildMemberAddEventHandler) Type() string { + return guildMemberAddEventType +} + +// New returns a new instance of GuildMemberAdd. +func (eh guildMemberAddEventHandler) New() interface{} { + return &GuildMemberAdd{} +} + +// Handle is the handler for GuildMemberAdd events. +func (eh guildMemberAddEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildMemberAdd); ok { + eh(s, t) + } +} + +// guildMemberRemoveEventHandler is an event handler for GuildMemberRemove events. +type guildMemberRemoveEventHandler func(*Session, *GuildMemberRemove) + +// Type returns the event type for GuildMemberRemove events. +func (eh guildMemberRemoveEventHandler) Type() string { + return guildMemberRemoveEventType +} + +// New returns a new instance of GuildMemberRemove. +func (eh guildMemberRemoveEventHandler) New() interface{} { + return &GuildMemberRemove{} +} + +// Handle is the handler for GuildMemberRemove events. +func (eh guildMemberRemoveEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildMemberRemove); ok { + eh(s, t) + } +} + +// guildMemberUpdateEventHandler is an event handler for GuildMemberUpdate events. +type guildMemberUpdateEventHandler func(*Session, *GuildMemberUpdate) + +// Type returns the event type for GuildMemberUpdate events. +func (eh guildMemberUpdateEventHandler) Type() string { + return guildMemberUpdateEventType +} + +// New returns a new instance of GuildMemberUpdate. +func (eh guildMemberUpdateEventHandler) New() interface{} { + return &GuildMemberUpdate{} +} + +// Handle is the handler for GuildMemberUpdate events. +func (eh guildMemberUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildMemberUpdate); ok { + eh(s, t) + } +} + +// guildMembersChunkEventHandler is an event handler for GuildMembersChunk events. +type guildMembersChunkEventHandler func(*Session, *GuildMembersChunk) + +// Type returns the event type for GuildMembersChunk events. +func (eh guildMembersChunkEventHandler) Type() string { + return guildMembersChunkEventType +} + +// New returns a new instance of GuildMembersChunk. +func (eh guildMembersChunkEventHandler) New() interface{} { + return &GuildMembersChunk{} +} + +// Handle is the handler for GuildMembersChunk events. +func (eh guildMembersChunkEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildMembersChunk); ok { + eh(s, t) + } +} + +// guildRoleCreateEventHandler is an event handler for GuildRoleCreate events. +type guildRoleCreateEventHandler func(*Session, *GuildRoleCreate) + +// Type returns the event type for GuildRoleCreate events. +func (eh guildRoleCreateEventHandler) Type() string { + return guildRoleCreateEventType +} + +// New returns a new instance of GuildRoleCreate. +func (eh guildRoleCreateEventHandler) New() interface{} { + return &GuildRoleCreate{} +} + +// Handle is the handler for GuildRoleCreate events. +func (eh guildRoleCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildRoleCreate); ok { + eh(s, t) + } +} + +// guildRoleDeleteEventHandler is an event handler for GuildRoleDelete events. +type guildRoleDeleteEventHandler func(*Session, *GuildRoleDelete) + +// Type returns the event type for GuildRoleDelete events. +func (eh guildRoleDeleteEventHandler) Type() string { + return guildRoleDeleteEventType +} + +// New returns a new instance of GuildRoleDelete. +func (eh guildRoleDeleteEventHandler) New() interface{} { + return &GuildRoleDelete{} +} + +// Handle is the handler for GuildRoleDelete events. +func (eh guildRoleDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildRoleDelete); ok { + eh(s, t) + } +} + +// guildRoleUpdateEventHandler is an event handler for GuildRoleUpdate events. +type guildRoleUpdateEventHandler func(*Session, *GuildRoleUpdate) + +// Type returns the event type for GuildRoleUpdate events. +func (eh guildRoleUpdateEventHandler) Type() string { + return guildRoleUpdateEventType +} + +// New returns a new instance of GuildRoleUpdate. +func (eh guildRoleUpdateEventHandler) New() interface{} { + return &GuildRoleUpdate{} +} + +// Handle is the handler for GuildRoleUpdate events. +func (eh guildRoleUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildRoleUpdate); ok { + eh(s, t) + } +} + +// guildScheduledEventCreateEventHandler is an event handler for GuildScheduledEventCreate events. +type guildScheduledEventCreateEventHandler func(*Session, *GuildScheduledEventCreate) + +// Type returns the event type for GuildScheduledEventCreate events. +func (eh guildScheduledEventCreateEventHandler) Type() string { + return guildScheduledEventCreateEventType +} + +// New returns a new instance of GuildScheduledEventCreate. +func (eh guildScheduledEventCreateEventHandler) New() interface{} { + return &GuildScheduledEventCreate{} +} + +// Handle is the handler for GuildScheduledEventCreate events. +func (eh guildScheduledEventCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildScheduledEventCreate); ok { + eh(s, t) + } +} + +// guildScheduledEventDeleteEventHandler is an event handler for GuildScheduledEventDelete events. +type guildScheduledEventDeleteEventHandler func(*Session, *GuildScheduledEventDelete) + +// Type returns the event type for GuildScheduledEventDelete events. +func (eh guildScheduledEventDeleteEventHandler) Type() string { + return guildScheduledEventDeleteEventType +} + +// New returns a new instance of GuildScheduledEventDelete. +func (eh guildScheduledEventDeleteEventHandler) New() interface{} { + return &GuildScheduledEventDelete{} +} + +// Handle is the handler for GuildScheduledEventDelete events. +func (eh guildScheduledEventDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildScheduledEventDelete); ok { + eh(s, t) + } +} + +// guildScheduledEventUpdateEventHandler is an event handler for GuildScheduledEventUpdate events. +type guildScheduledEventUpdateEventHandler func(*Session, *GuildScheduledEventUpdate) + +// Type returns the event type for GuildScheduledEventUpdate events. +func (eh guildScheduledEventUpdateEventHandler) Type() string { + return guildScheduledEventUpdateEventType +} + +// New returns a new instance of GuildScheduledEventUpdate. +func (eh guildScheduledEventUpdateEventHandler) New() interface{} { + return &GuildScheduledEventUpdate{} +} + +// Handle is the handler for GuildScheduledEventUpdate events. +func (eh guildScheduledEventUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildScheduledEventUpdate); ok { + eh(s, t) + } +} + +// guildScheduledEventUserAddEventHandler is an event handler for GuildScheduledEventUserAdd events. +type guildScheduledEventUserAddEventHandler func(*Session, *GuildScheduledEventUserAdd) + +// Type returns the event type for GuildScheduledEventUserAdd events. +func (eh guildScheduledEventUserAddEventHandler) Type() string { + return guildScheduledEventUserAddEventType +} + +// New returns a new instance of GuildScheduledEventUserAdd. +func (eh guildScheduledEventUserAddEventHandler) New() interface{} { + return &GuildScheduledEventUserAdd{} +} + +// Handle is the handler for GuildScheduledEventUserAdd events. +func (eh guildScheduledEventUserAddEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildScheduledEventUserAdd); ok { + eh(s, t) + } +} + +// guildScheduledEventUserRemoveEventHandler is an event handler for GuildScheduledEventUserRemove events. +type guildScheduledEventUserRemoveEventHandler func(*Session, *GuildScheduledEventUserRemove) + +// Type returns the event type for GuildScheduledEventUserRemove events. +func (eh guildScheduledEventUserRemoveEventHandler) Type() string { + return guildScheduledEventUserRemoveEventType +} + +// New returns a new instance of GuildScheduledEventUserRemove. +func (eh guildScheduledEventUserRemoveEventHandler) New() interface{} { + return &GuildScheduledEventUserRemove{} +} + +// Handle is the handler for GuildScheduledEventUserRemove events. +func (eh guildScheduledEventUserRemoveEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildScheduledEventUserRemove); ok { + eh(s, t) + } +} + +// guildStickersUpdateEventHandler is an event handler for GuildStickersUpdate events. +type guildStickersUpdateEventHandler func(*Session, *GuildStickersUpdate) + +// Type returns the event type for GuildStickersUpdate events. +func (eh guildStickersUpdateEventHandler) Type() string { + return guildStickersUpdateEventType +} + +// New returns a new instance of GuildStickersUpdate. +func (eh guildStickersUpdateEventHandler) New() interface{} { + return &GuildStickersUpdate{} +} + +// Handle is the handler for GuildStickersUpdate events. +func (eh guildStickersUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildStickersUpdate); ok { + eh(s, t) + } +} + +// guildUpdateEventHandler is an event handler for GuildUpdate events. +type guildUpdateEventHandler func(*Session, *GuildUpdate) + +// Type returns the event type for GuildUpdate events. +func (eh guildUpdateEventHandler) Type() string { + return guildUpdateEventType +} + +// New returns a new instance of GuildUpdate. +func (eh guildUpdateEventHandler) New() interface{} { + return &GuildUpdate{} +} + +// Handle is the handler for GuildUpdate events. +func (eh guildUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*GuildUpdate); ok { + eh(s, t) + } +} + +// integrationCreateEventHandler is an event handler for IntegrationCreate events. +type integrationCreateEventHandler func(*Session, *IntegrationCreate) + +// Type returns the event type for IntegrationCreate events. +func (eh integrationCreateEventHandler) Type() string { + return integrationCreateEventType +} + +// New returns a new instance of IntegrationCreate. +func (eh integrationCreateEventHandler) New() interface{} { + return &IntegrationCreate{} +} + +// Handle is the handler for IntegrationCreate events. +func (eh integrationCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*IntegrationCreate); ok { + eh(s, t) + } +} + +// integrationDeleteEventHandler is an event handler for IntegrationDelete events. +type integrationDeleteEventHandler func(*Session, *IntegrationDelete) + +// Type returns the event type for IntegrationDelete events. +func (eh integrationDeleteEventHandler) Type() string { + return integrationDeleteEventType +} + +// New returns a new instance of IntegrationDelete. +func (eh integrationDeleteEventHandler) New() interface{} { + return &IntegrationDelete{} +} + +// Handle is the handler for IntegrationDelete events. +func (eh integrationDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*IntegrationDelete); ok { + eh(s, t) + } +} + +// integrationUpdateEventHandler is an event handler for IntegrationUpdate events. +type integrationUpdateEventHandler func(*Session, *IntegrationUpdate) + +// Type returns the event type for IntegrationUpdate events. +func (eh integrationUpdateEventHandler) Type() string { + return integrationUpdateEventType +} + +// New returns a new instance of IntegrationUpdate. +func (eh integrationUpdateEventHandler) New() interface{} { + return &IntegrationUpdate{} +} + +// Handle is the handler for IntegrationUpdate events. +func (eh integrationUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*IntegrationUpdate); ok { + eh(s, t) + } +} + +// interactionCreateEventHandler is an event handler for InteractionCreate events. +type interactionCreateEventHandler func(*Session, *InteractionCreate) + +// Type returns the event type for InteractionCreate events. +func (eh interactionCreateEventHandler) Type() string { + return interactionCreateEventType +} + +// New returns a new instance of InteractionCreate. +func (eh interactionCreateEventHandler) New() interface{} { + return &InteractionCreate{} +} + +// Handle is the handler for InteractionCreate events. +func (eh interactionCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*InteractionCreate); ok { + eh(s, t) + } +} + +// inviteCreateEventHandler is an event handler for InviteCreate events. +type inviteCreateEventHandler func(*Session, *InviteCreate) + +// Type returns the event type for InviteCreate events. +func (eh inviteCreateEventHandler) Type() string { + return inviteCreateEventType +} + +// New returns a new instance of InviteCreate. +func (eh inviteCreateEventHandler) New() interface{} { + return &InviteCreate{} +} + +// Handle is the handler for InviteCreate events. +func (eh inviteCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*InviteCreate); ok { + eh(s, t) + } +} + +// inviteDeleteEventHandler is an event handler for InviteDelete events. +type inviteDeleteEventHandler func(*Session, *InviteDelete) + +// Type returns the event type for InviteDelete events. +func (eh inviteDeleteEventHandler) Type() string { + return inviteDeleteEventType +} + +// New returns a new instance of InviteDelete. +func (eh inviteDeleteEventHandler) New() interface{} { + return &InviteDelete{} +} + +// Handle is the handler for InviteDelete events. +func (eh inviteDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*InviteDelete); ok { + eh(s, t) + } +} + +// messageCreateEventHandler is an event handler for MessageCreate events. +type messageCreateEventHandler func(*Session, *MessageCreate) + +// Type returns the event type for MessageCreate events. +func (eh messageCreateEventHandler) Type() string { + return messageCreateEventType +} + +// New returns a new instance of MessageCreate. +func (eh messageCreateEventHandler) New() interface{} { + return &MessageCreate{} +} + +// Handle is the handler for MessageCreate events. +func (eh messageCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageCreate); ok { + eh(s, t) + } +} + +// messageDeleteEventHandler is an event handler for MessageDelete events. +type messageDeleteEventHandler func(*Session, *MessageDelete) + +// Type returns the event type for MessageDelete events. +func (eh messageDeleteEventHandler) Type() string { + return messageDeleteEventType +} + +// New returns a new instance of MessageDelete. +func (eh messageDeleteEventHandler) New() interface{} { + return &MessageDelete{} +} + +// Handle is the handler for MessageDelete events. +func (eh messageDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageDelete); ok { + eh(s, t) + } +} + +// messageDeleteBulkEventHandler is an event handler for MessageDeleteBulk events. +type messageDeleteBulkEventHandler func(*Session, *MessageDeleteBulk) + +// Type returns the event type for MessageDeleteBulk events. +func (eh messageDeleteBulkEventHandler) Type() string { + return messageDeleteBulkEventType +} + +// New returns a new instance of MessageDeleteBulk. +func (eh messageDeleteBulkEventHandler) New() interface{} { + return &MessageDeleteBulk{} +} + +// Handle is the handler for MessageDeleteBulk events. +func (eh messageDeleteBulkEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageDeleteBulk); ok { + eh(s, t) + } +} + +// messagePollVoteAddEventHandler is an event handler for MessagePollVoteAdd events. +type messagePollVoteAddEventHandler func(*Session, *MessagePollVoteAdd) + +// Type returns the event type for MessagePollVoteAdd events. +func (eh messagePollVoteAddEventHandler) Type() string { + return messagePollVoteAddEventType +} + +// New returns a new instance of MessagePollVoteAdd. +func (eh messagePollVoteAddEventHandler) New() interface{} { + return &MessagePollVoteAdd{} +} + +// Handle is the handler for MessagePollVoteAdd events. +func (eh messagePollVoteAddEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessagePollVoteAdd); ok { + eh(s, t) + } +} + +// messagePollVoteRemoveEventHandler is an event handler for MessagePollVoteRemove events. +type messagePollVoteRemoveEventHandler func(*Session, *MessagePollVoteRemove) + +// Type returns the event type for MessagePollVoteRemove events. +func (eh messagePollVoteRemoveEventHandler) Type() string { + return messagePollVoteRemoveEventType +} + +// New returns a new instance of MessagePollVoteRemove. +func (eh messagePollVoteRemoveEventHandler) New() interface{} { + return &MessagePollVoteRemove{} +} + +// Handle is the handler for MessagePollVoteRemove events. +func (eh messagePollVoteRemoveEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessagePollVoteRemove); ok { + eh(s, t) + } +} + +// messageReactionAddEventHandler is an event handler for MessageReactionAdd events. +type messageReactionAddEventHandler func(*Session, *MessageReactionAdd) + +// Type returns the event type for MessageReactionAdd events. +func (eh messageReactionAddEventHandler) Type() string { + return messageReactionAddEventType +} + +// New returns a new instance of MessageReactionAdd. +func (eh messageReactionAddEventHandler) New() interface{} { + return &MessageReactionAdd{} +} + +// Handle is the handler for MessageReactionAdd events. +func (eh messageReactionAddEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageReactionAdd); ok { + eh(s, t) + } +} + +// messageReactionRemoveEventHandler is an event handler for MessageReactionRemove events. +type messageReactionRemoveEventHandler func(*Session, *MessageReactionRemove) + +// Type returns the event type for MessageReactionRemove events. +func (eh messageReactionRemoveEventHandler) Type() string { + return messageReactionRemoveEventType +} + +// New returns a new instance of MessageReactionRemove. +func (eh messageReactionRemoveEventHandler) New() interface{} { + return &MessageReactionRemove{} +} + +// Handle is the handler for MessageReactionRemove events. +func (eh messageReactionRemoveEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageReactionRemove); ok { + eh(s, t) + } +} + +// messageReactionRemoveAllEventHandler is an event handler for MessageReactionRemoveAll events. +type messageReactionRemoveAllEventHandler func(*Session, *MessageReactionRemoveAll) + +// Type returns the event type for MessageReactionRemoveAll events. +func (eh messageReactionRemoveAllEventHandler) Type() string { + return messageReactionRemoveAllEventType +} + +// New returns a new instance of MessageReactionRemoveAll. +func (eh messageReactionRemoveAllEventHandler) New() interface{} { + return &MessageReactionRemoveAll{} +} + +// Handle is the handler for MessageReactionRemoveAll events. +func (eh messageReactionRemoveAllEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageReactionRemoveAll); ok { + eh(s, t) + } +} + +// messageUpdateEventHandler is an event handler for MessageUpdate events. +type messageUpdateEventHandler func(*Session, *MessageUpdate) + +// Type returns the event type for MessageUpdate events. +func (eh messageUpdateEventHandler) Type() string { + return messageUpdateEventType +} + +// New returns a new instance of MessageUpdate. +func (eh messageUpdateEventHandler) New() interface{} { + return &MessageUpdate{} +} + +// Handle is the handler for MessageUpdate events. +func (eh messageUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*MessageUpdate); ok { + eh(s, t) + } +} + +// presenceUpdateEventHandler is an event handler for PresenceUpdate events. +type presenceUpdateEventHandler func(*Session, *PresenceUpdate) + +// Type returns the event type for PresenceUpdate events. +func (eh presenceUpdateEventHandler) Type() string { + return presenceUpdateEventType +} + +// New returns a new instance of PresenceUpdate. +func (eh presenceUpdateEventHandler) New() interface{} { + return &PresenceUpdate{} +} + +// Handle is the handler for PresenceUpdate events. +func (eh presenceUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*PresenceUpdate); ok { + eh(s, t) + } +} + +// presencesReplaceEventHandler is an event handler for PresencesReplace events. +type presencesReplaceEventHandler func(*Session, *PresencesReplace) + +// Type returns the event type for PresencesReplace events. +func (eh presencesReplaceEventHandler) Type() string { + return presencesReplaceEventType +} + +// New returns a new instance of PresencesReplace. +func (eh presencesReplaceEventHandler) New() interface{} { + return &PresencesReplace{} +} + +// Handle is the handler for PresencesReplace events. +func (eh presencesReplaceEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*PresencesReplace); ok { + eh(s, t) + } +} + +// rateLimitEventHandler is an event handler for RateLimit events. +type rateLimitEventHandler func(*Session, *RateLimit) + +// Type returns the event type for RateLimit events. +func (eh rateLimitEventHandler) Type() string { + return rateLimitEventType +} + +// Handle is the handler for RateLimit events. +func (eh rateLimitEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*RateLimit); ok { + eh(s, t) + } +} + +// readyEventHandler is an event handler for Ready events. +type readyEventHandler func(*Session, *Ready) + +// Type returns the event type for Ready events. +func (eh readyEventHandler) Type() string { + return readyEventType +} + +// New returns a new instance of Ready. +func (eh readyEventHandler) New() interface{} { + return &Ready{} +} + +// Handle is the handler for Ready events. +func (eh readyEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*Ready); ok { + eh(s, t) + } +} + +// resumedEventHandler is an event handler for Resumed events. +type resumedEventHandler func(*Session, *Resumed) + +// Type returns the event type for Resumed events. +func (eh resumedEventHandler) Type() string { + return resumedEventType +} + +// New returns a new instance of Resumed. +func (eh resumedEventHandler) New() interface{} { + return &Resumed{} +} + +// Handle is the handler for Resumed events. +func (eh resumedEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*Resumed); ok { + eh(s, t) + } +} + +// stageInstanceEventCreateEventHandler is an event handler for StageInstanceEventCreate events. +type stageInstanceEventCreateEventHandler func(*Session, *StageInstanceEventCreate) + +// Type returns the event type for StageInstanceEventCreate events. +func (eh stageInstanceEventCreateEventHandler) Type() string { + return stageInstanceEventCreateEventType +} + +// New returns a new instance of StageInstanceEventCreate. +func (eh stageInstanceEventCreateEventHandler) New() interface{} { + return &StageInstanceEventCreate{} +} + +// Handle is the handler for StageInstanceEventCreate events. +func (eh stageInstanceEventCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*StageInstanceEventCreate); ok { + eh(s, t) + } +} + +// stageInstanceEventDeleteEventHandler is an event handler for StageInstanceEventDelete events. +type stageInstanceEventDeleteEventHandler func(*Session, *StageInstanceEventDelete) + +// Type returns the event type for StageInstanceEventDelete events. +func (eh stageInstanceEventDeleteEventHandler) Type() string { + return stageInstanceEventDeleteEventType +} + +// New returns a new instance of StageInstanceEventDelete. +func (eh stageInstanceEventDeleteEventHandler) New() interface{} { + return &StageInstanceEventDelete{} +} + +// Handle is the handler for StageInstanceEventDelete events. +func (eh stageInstanceEventDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*StageInstanceEventDelete); ok { + eh(s, t) + } +} + +// stageInstanceEventUpdateEventHandler is an event handler for StageInstanceEventUpdate events. +type stageInstanceEventUpdateEventHandler func(*Session, *StageInstanceEventUpdate) + +// Type returns the event type for StageInstanceEventUpdate events. +func (eh stageInstanceEventUpdateEventHandler) Type() string { + return stageInstanceEventUpdateEventType +} + +// New returns a new instance of StageInstanceEventUpdate. +func (eh stageInstanceEventUpdateEventHandler) New() interface{} { + return &StageInstanceEventUpdate{} +} + +// Handle is the handler for StageInstanceEventUpdate events. +func (eh stageInstanceEventUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*StageInstanceEventUpdate); ok { + eh(s, t) + } +} + +// subscriptionCreateEventHandler is an event handler for SubscriptionCreate events. +type subscriptionCreateEventHandler func(*Session, *SubscriptionCreate) + +// Type returns the event type for SubscriptionCreate events. +func (eh subscriptionCreateEventHandler) Type() string { + return subscriptionCreateEventType +} + +// New returns a new instance of SubscriptionCreate. +func (eh subscriptionCreateEventHandler) New() interface{} { + return &SubscriptionCreate{} +} + +// Handle is the handler for SubscriptionCreate events. +func (eh subscriptionCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*SubscriptionCreate); ok { + eh(s, t) + } +} + +// subscriptionDeleteEventHandler is an event handler for SubscriptionDelete events. +type subscriptionDeleteEventHandler func(*Session, *SubscriptionDelete) + +// Type returns the event type for SubscriptionDelete events. +func (eh subscriptionDeleteEventHandler) Type() string { + return subscriptionDeleteEventType +} + +// New returns a new instance of SubscriptionDelete. +func (eh subscriptionDeleteEventHandler) New() interface{} { + return &SubscriptionDelete{} +} + +// Handle is the handler for SubscriptionDelete events. +func (eh subscriptionDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*SubscriptionDelete); ok { + eh(s, t) + } +} + +// subscriptionUpdateEventHandler is an event handler for SubscriptionUpdate events. +type subscriptionUpdateEventHandler func(*Session, *SubscriptionUpdate) + +// Type returns the event type for SubscriptionUpdate events. +func (eh subscriptionUpdateEventHandler) Type() string { + return subscriptionUpdateEventType +} + +// New returns a new instance of SubscriptionUpdate. +func (eh subscriptionUpdateEventHandler) New() interface{} { + return &SubscriptionUpdate{} +} + +// Handle is the handler for SubscriptionUpdate events. +func (eh subscriptionUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*SubscriptionUpdate); ok { + eh(s, t) + } +} + +// threadCreateEventHandler is an event handler for ThreadCreate events. +type threadCreateEventHandler func(*Session, *ThreadCreate) + +// Type returns the event type for ThreadCreate events. +func (eh threadCreateEventHandler) Type() string { + return threadCreateEventType +} + +// New returns a new instance of ThreadCreate. +func (eh threadCreateEventHandler) New() interface{} { + return &ThreadCreate{} +} + +// Handle is the handler for ThreadCreate events. +func (eh threadCreateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadCreate); ok { + eh(s, t) + } +} + +// threadDeleteEventHandler is an event handler for ThreadDelete events. +type threadDeleteEventHandler func(*Session, *ThreadDelete) + +// Type returns the event type for ThreadDelete events. +func (eh threadDeleteEventHandler) Type() string { + return threadDeleteEventType +} + +// New returns a new instance of ThreadDelete. +func (eh threadDeleteEventHandler) New() interface{} { + return &ThreadDelete{} +} + +// Handle is the handler for ThreadDelete events. +func (eh threadDeleteEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadDelete); ok { + eh(s, t) + } +} + +// threadListSyncEventHandler is an event handler for ThreadListSync events. +type threadListSyncEventHandler func(*Session, *ThreadListSync) + +// Type returns the event type for ThreadListSync events. +func (eh threadListSyncEventHandler) Type() string { + return threadListSyncEventType +} + +// New returns a new instance of ThreadListSync. +func (eh threadListSyncEventHandler) New() interface{} { + return &ThreadListSync{} +} + +// Handle is the handler for ThreadListSync events. +func (eh threadListSyncEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadListSync); ok { + eh(s, t) + } +} + +// threadMemberUpdateEventHandler is an event handler for ThreadMemberUpdate events. +type threadMemberUpdateEventHandler func(*Session, *ThreadMemberUpdate) + +// Type returns the event type for ThreadMemberUpdate events. +func (eh threadMemberUpdateEventHandler) Type() string { + return threadMemberUpdateEventType +} + +// New returns a new instance of ThreadMemberUpdate. +func (eh threadMemberUpdateEventHandler) New() interface{} { + return &ThreadMemberUpdate{} +} + +// Handle is the handler for ThreadMemberUpdate events. +func (eh threadMemberUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadMemberUpdate); ok { + eh(s, t) + } +} + +// threadMembersUpdateEventHandler is an event handler for ThreadMembersUpdate events. +type threadMembersUpdateEventHandler func(*Session, *ThreadMembersUpdate) + +// Type returns the event type for ThreadMembersUpdate events. +func (eh threadMembersUpdateEventHandler) Type() string { + return threadMembersUpdateEventType +} + +// New returns a new instance of ThreadMembersUpdate. +func (eh threadMembersUpdateEventHandler) New() interface{} { + return &ThreadMembersUpdate{} +} + +// Handle is the handler for ThreadMembersUpdate events. +func (eh threadMembersUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadMembersUpdate); ok { + eh(s, t) + } +} + +// threadUpdateEventHandler is an event handler for ThreadUpdate events. +type threadUpdateEventHandler func(*Session, *ThreadUpdate) + +// Type returns the event type for ThreadUpdate events. +func (eh threadUpdateEventHandler) Type() string { + return threadUpdateEventType +} + +// New returns a new instance of ThreadUpdate. +func (eh threadUpdateEventHandler) New() interface{} { + return &ThreadUpdate{} +} + +// Handle is the handler for ThreadUpdate events. +func (eh threadUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*ThreadUpdate); ok { + eh(s, t) + } +} + +// typingStartEventHandler is an event handler for TypingStart events. +type typingStartEventHandler func(*Session, *TypingStart) + +// Type returns the event type for TypingStart events. +func (eh typingStartEventHandler) Type() string { + return typingStartEventType +} + +// New returns a new instance of TypingStart. +func (eh typingStartEventHandler) New() interface{} { + return &TypingStart{} +} + +// Handle is the handler for TypingStart events. +func (eh typingStartEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*TypingStart); ok { + eh(s, t) + } +} + +// userUpdateEventHandler is an event handler for UserUpdate events. +type userUpdateEventHandler func(*Session, *UserUpdate) + +// Type returns the event type for UserUpdate events. +func (eh userUpdateEventHandler) Type() string { + return userUpdateEventType +} + +// New returns a new instance of UserUpdate. +func (eh userUpdateEventHandler) New() interface{} { + return &UserUpdate{} +} + +// Handle is the handler for UserUpdate events. +func (eh userUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*UserUpdate); ok { + eh(s, t) + } +} + +// voiceServerUpdateEventHandler is an event handler for VoiceServerUpdate events. +type voiceServerUpdateEventHandler func(*Session, *VoiceServerUpdate) + +// Type returns the event type for VoiceServerUpdate events. +func (eh voiceServerUpdateEventHandler) Type() string { + return voiceServerUpdateEventType +} + +// New returns a new instance of VoiceServerUpdate. +func (eh voiceServerUpdateEventHandler) New() interface{} { + return &VoiceServerUpdate{} +} + +// Handle is the handler for VoiceServerUpdate events. +func (eh voiceServerUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*VoiceServerUpdate); ok { + eh(s, t) + } +} + +// voiceStateUpdateEventHandler is an event handler for VoiceStateUpdate events. +type voiceStateUpdateEventHandler func(*Session, *VoiceStateUpdate) + +// Type returns the event type for VoiceStateUpdate events. +func (eh voiceStateUpdateEventHandler) Type() string { + return voiceStateUpdateEventType +} + +// New returns a new instance of VoiceStateUpdate. +func (eh voiceStateUpdateEventHandler) New() interface{} { + return &VoiceStateUpdate{} +} + +// Handle is the handler for VoiceStateUpdate events. +func (eh voiceStateUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*VoiceStateUpdate); ok { + eh(s, t) + } +} + +// webhooksUpdateEventHandler is an event handler for WebhooksUpdate events. +type webhooksUpdateEventHandler func(*Session, *WebhooksUpdate) + +// Type returns the event type for WebhooksUpdate events. +func (eh webhooksUpdateEventHandler) Type() string { + return webhooksUpdateEventType +} + +// New returns a new instance of WebhooksUpdate. +func (eh webhooksUpdateEventHandler) New() interface{} { + return &WebhooksUpdate{} +} + +// Handle is the handler for WebhooksUpdate events. +func (eh webhooksUpdateEventHandler) Handle(s *Session, i interface{}) { + if t, ok := i.(*WebhooksUpdate); ok { + eh(s, t) + } +} + +func handlerForInterface(handler interface{}) EventHandler { + switch v := handler.(type) { + case func(*Session, interface{}): + return interfaceEventHandler(v) + case func(*Session, *ApplicationCommandPermissionsUpdate): + return applicationCommandPermissionsUpdateEventHandler(v) + case func(*Session, *AutoModerationActionExecution): + return autoModerationActionExecutionEventHandler(v) + case func(*Session, *AutoModerationRuleCreate): + return autoModerationRuleCreateEventHandler(v) + case func(*Session, *AutoModerationRuleDelete): + return autoModerationRuleDeleteEventHandler(v) + case func(*Session, *AutoModerationRuleUpdate): + return autoModerationRuleUpdateEventHandler(v) + case func(*Session, *ChannelCreate): + return channelCreateEventHandler(v) + case func(*Session, *ChannelDelete): + return channelDeleteEventHandler(v) + case func(*Session, *ChannelPinsUpdate): + return channelPinsUpdateEventHandler(v) + case func(*Session, *ChannelUpdate): + return channelUpdateEventHandler(v) + case func(*Session, *Connect): + return connectEventHandler(v) + case func(*Session, *Disconnect): + return disconnectEventHandler(v) + case func(*Session, *EntitlementCreate): + return entitlementCreateEventHandler(v) + case func(*Session, *EntitlementDelete): + return entitlementDeleteEventHandler(v) + case func(*Session, *EntitlementUpdate): + return entitlementUpdateEventHandler(v) + case func(*Session, *Event): + return eventEventHandler(v) + case func(*Session, *GuildAuditLogEntryCreate): + return guildAuditLogEntryCreateEventHandler(v) + case func(*Session, *GuildBanAdd): + return guildBanAddEventHandler(v) + case func(*Session, *GuildBanRemove): + return guildBanRemoveEventHandler(v) + case func(*Session, *GuildCreate): + return guildCreateEventHandler(v) + case func(*Session, *GuildDelete): + return guildDeleteEventHandler(v) + case func(*Session, *GuildEmojisUpdate): + return guildEmojisUpdateEventHandler(v) + case func(*Session, *GuildIntegrationsUpdate): + return guildIntegrationsUpdateEventHandler(v) + case func(*Session, *GuildMemberAdd): + return guildMemberAddEventHandler(v) + case func(*Session, *GuildMemberRemove): + return guildMemberRemoveEventHandler(v) + case func(*Session, *GuildMemberUpdate): + return guildMemberUpdateEventHandler(v) + case func(*Session, *GuildMembersChunk): + return guildMembersChunkEventHandler(v) + case func(*Session, *GuildRoleCreate): + return guildRoleCreateEventHandler(v) + case func(*Session, *GuildRoleDelete): + return guildRoleDeleteEventHandler(v) + case func(*Session, *GuildRoleUpdate): + return guildRoleUpdateEventHandler(v) + case func(*Session, *GuildScheduledEventCreate): + return guildScheduledEventCreateEventHandler(v) + case func(*Session, *GuildScheduledEventDelete): + return guildScheduledEventDeleteEventHandler(v) + case func(*Session, *GuildScheduledEventUpdate): + return guildScheduledEventUpdateEventHandler(v) + case func(*Session, *GuildScheduledEventUserAdd): + return guildScheduledEventUserAddEventHandler(v) + case func(*Session, *GuildScheduledEventUserRemove): + return guildScheduledEventUserRemoveEventHandler(v) + case func(*Session, *GuildStickersUpdate): + return guildStickersUpdateEventHandler(v) + case func(*Session, *GuildUpdate): + return guildUpdateEventHandler(v) + case func(*Session, *IntegrationCreate): + return integrationCreateEventHandler(v) + case func(*Session, *IntegrationDelete): + return integrationDeleteEventHandler(v) + case func(*Session, *IntegrationUpdate): + return integrationUpdateEventHandler(v) + case func(*Session, *InteractionCreate): + return interactionCreateEventHandler(v) + case func(*Session, *InviteCreate): + return inviteCreateEventHandler(v) + case func(*Session, *InviteDelete): + return inviteDeleteEventHandler(v) + case func(*Session, *MessageCreate): + return messageCreateEventHandler(v) + case func(*Session, *MessageDelete): + return messageDeleteEventHandler(v) + case func(*Session, *MessageDeleteBulk): + return messageDeleteBulkEventHandler(v) + case func(*Session, *MessagePollVoteAdd): + return messagePollVoteAddEventHandler(v) + case func(*Session, *MessagePollVoteRemove): + return messagePollVoteRemoveEventHandler(v) + case func(*Session, *MessageReactionAdd): + return messageReactionAddEventHandler(v) + case func(*Session, *MessageReactionRemove): + return messageReactionRemoveEventHandler(v) + case func(*Session, *MessageReactionRemoveAll): + return messageReactionRemoveAllEventHandler(v) + case func(*Session, *MessageUpdate): + return messageUpdateEventHandler(v) + case func(*Session, *PresenceUpdate): + return presenceUpdateEventHandler(v) + case func(*Session, *PresencesReplace): + return presencesReplaceEventHandler(v) + case func(*Session, *RateLimit): + return rateLimitEventHandler(v) + case func(*Session, *Ready): + return readyEventHandler(v) + case func(*Session, *Resumed): + return resumedEventHandler(v) + case func(*Session, *StageInstanceEventCreate): + return stageInstanceEventCreateEventHandler(v) + case func(*Session, *StageInstanceEventDelete): + return stageInstanceEventDeleteEventHandler(v) + case func(*Session, *StageInstanceEventUpdate): + return stageInstanceEventUpdateEventHandler(v) + case func(*Session, *SubscriptionCreate): + return subscriptionCreateEventHandler(v) + case func(*Session, *SubscriptionDelete): + return subscriptionDeleteEventHandler(v) + case func(*Session, *SubscriptionUpdate): + return subscriptionUpdateEventHandler(v) + case func(*Session, *ThreadCreate): + return threadCreateEventHandler(v) + case func(*Session, *ThreadDelete): + return threadDeleteEventHandler(v) + case func(*Session, *ThreadListSync): + return threadListSyncEventHandler(v) + case func(*Session, *ThreadMemberUpdate): + return threadMemberUpdateEventHandler(v) + case func(*Session, *ThreadMembersUpdate): + return threadMembersUpdateEventHandler(v) + case func(*Session, *ThreadUpdate): + return threadUpdateEventHandler(v) + case func(*Session, *TypingStart): + return typingStartEventHandler(v) + case func(*Session, *UserUpdate): + return userUpdateEventHandler(v) + case func(*Session, *VoiceServerUpdate): + return voiceServerUpdateEventHandler(v) + case func(*Session, *VoiceStateUpdate): + return voiceStateUpdateEventHandler(v) + case func(*Session, *WebhooksUpdate): + return webhooksUpdateEventHandler(v) + } + + return nil +} + +func init() { + registerInterfaceProvider(applicationCommandPermissionsUpdateEventHandler(nil)) + registerInterfaceProvider(autoModerationActionExecutionEventHandler(nil)) + registerInterfaceProvider(autoModerationRuleCreateEventHandler(nil)) + registerInterfaceProvider(autoModerationRuleDeleteEventHandler(nil)) + registerInterfaceProvider(autoModerationRuleUpdateEventHandler(nil)) + registerInterfaceProvider(channelCreateEventHandler(nil)) + registerInterfaceProvider(channelDeleteEventHandler(nil)) + registerInterfaceProvider(channelPinsUpdateEventHandler(nil)) + registerInterfaceProvider(channelUpdateEventHandler(nil)) + registerInterfaceProvider(entitlementCreateEventHandler(nil)) + registerInterfaceProvider(entitlementDeleteEventHandler(nil)) + registerInterfaceProvider(entitlementUpdateEventHandler(nil)) + registerInterfaceProvider(guildAuditLogEntryCreateEventHandler(nil)) + registerInterfaceProvider(guildBanAddEventHandler(nil)) + registerInterfaceProvider(guildBanRemoveEventHandler(nil)) + registerInterfaceProvider(guildCreateEventHandler(nil)) + registerInterfaceProvider(guildDeleteEventHandler(nil)) + registerInterfaceProvider(guildEmojisUpdateEventHandler(nil)) + registerInterfaceProvider(guildIntegrationsUpdateEventHandler(nil)) + registerInterfaceProvider(guildMemberAddEventHandler(nil)) + registerInterfaceProvider(guildMemberRemoveEventHandler(nil)) + registerInterfaceProvider(guildMemberUpdateEventHandler(nil)) + registerInterfaceProvider(guildMembersChunkEventHandler(nil)) + registerInterfaceProvider(guildRoleCreateEventHandler(nil)) + registerInterfaceProvider(guildRoleDeleteEventHandler(nil)) + registerInterfaceProvider(guildRoleUpdateEventHandler(nil)) + registerInterfaceProvider(guildScheduledEventCreateEventHandler(nil)) + registerInterfaceProvider(guildScheduledEventDeleteEventHandler(nil)) + registerInterfaceProvider(guildScheduledEventUpdateEventHandler(nil)) + registerInterfaceProvider(guildScheduledEventUserAddEventHandler(nil)) + registerInterfaceProvider(guildScheduledEventUserRemoveEventHandler(nil)) + registerInterfaceProvider(guildStickersUpdateEventHandler(nil)) + registerInterfaceProvider(guildUpdateEventHandler(nil)) + registerInterfaceProvider(integrationCreateEventHandler(nil)) + registerInterfaceProvider(integrationDeleteEventHandler(nil)) + registerInterfaceProvider(integrationUpdateEventHandler(nil)) + registerInterfaceProvider(interactionCreateEventHandler(nil)) + registerInterfaceProvider(inviteCreateEventHandler(nil)) + registerInterfaceProvider(inviteDeleteEventHandler(nil)) + registerInterfaceProvider(messageCreateEventHandler(nil)) + registerInterfaceProvider(messageDeleteEventHandler(nil)) + registerInterfaceProvider(messageDeleteBulkEventHandler(nil)) + registerInterfaceProvider(messagePollVoteAddEventHandler(nil)) + registerInterfaceProvider(messagePollVoteRemoveEventHandler(nil)) + registerInterfaceProvider(messageReactionAddEventHandler(nil)) + registerInterfaceProvider(messageReactionRemoveEventHandler(nil)) + registerInterfaceProvider(messageReactionRemoveAllEventHandler(nil)) + registerInterfaceProvider(messageUpdateEventHandler(nil)) + registerInterfaceProvider(presenceUpdateEventHandler(nil)) + registerInterfaceProvider(presencesReplaceEventHandler(nil)) + registerInterfaceProvider(readyEventHandler(nil)) + registerInterfaceProvider(resumedEventHandler(nil)) + registerInterfaceProvider(stageInstanceEventCreateEventHandler(nil)) + registerInterfaceProvider(stageInstanceEventDeleteEventHandler(nil)) + registerInterfaceProvider(stageInstanceEventUpdateEventHandler(nil)) + registerInterfaceProvider(subscriptionCreateEventHandler(nil)) + registerInterfaceProvider(subscriptionDeleteEventHandler(nil)) + registerInterfaceProvider(subscriptionUpdateEventHandler(nil)) + registerInterfaceProvider(threadCreateEventHandler(nil)) + registerInterfaceProvider(threadDeleteEventHandler(nil)) + registerInterfaceProvider(threadListSyncEventHandler(nil)) + registerInterfaceProvider(threadMemberUpdateEventHandler(nil)) + registerInterfaceProvider(threadMembersUpdateEventHandler(nil)) + registerInterfaceProvider(threadUpdateEventHandler(nil)) + registerInterfaceProvider(typingStartEventHandler(nil)) + registerInterfaceProvider(userUpdateEventHandler(nil)) + registerInterfaceProvider(voiceServerUpdateEventHandler(nil)) + registerInterfaceProvider(voiceStateUpdateEventHandler(nil)) + registerInterfaceProvider(webhooksUpdateEventHandler(nil)) +} diff --git a/vendor/github.com/bwmarrin/discordgo/events.go b/vendor/github.com/bwmarrin/discordgo/events.go new file mode 100644 index 000000000..ccc73464d --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/events.go @@ -0,0 +1,487 @@ +package discordgo + +import ( + "encoding/json" +) + +// This file contains all the possible structs that can be +// handled by AddHandler/EventHandler. +// DO NOT ADD ANYTHING BUT EVENT HANDLER STRUCTS TO THIS FILE. +//go:generate go run tools/cmd/eventhandlers/main.go + +// Connect is the data for a Connect event. +// This is a synthetic event and is not dispatched by Discord. +type Connect struct{} + +// Disconnect is the data for a Disconnect event. +// This is a synthetic event and is not dispatched by Discord. +type Disconnect struct{} + +// RateLimit is the data for a RateLimit event. +// This is a synthetic event and is not dispatched by Discord. +type RateLimit struct { + *TooManyRequests + URL string +} + +// Event provides a basic initial struct for all websocket events. +type Event struct { + Operation int `json:"op"` + Sequence int64 `json:"s"` + Type string `json:"t"` + RawData json.RawMessage `json:"d"` + // Struct contains one of the other types in this file. + Struct interface{} `json:"-"` +} + +// A Ready stores all data for the websocket READY event. +type Ready struct { + Version int `json:"v"` + SessionID string `json:"session_id"` + User *User `json:"user"` + Shard *[2]int `json:"shard"` + Application *Application `json:"application"` + Guilds []*Guild `json:"guilds"` + PrivateChannels []*Channel `json:"private_channels"` +} + +// ChannelCreate is the data for a ChannelCreate event. +type ChannelCreate struct { + *Channel +} + +// ChannelUpdate is the data for a ChannelUpdate event. +type ChannelUpdate struct { + *Channel + BeforeUpdate *Channel `json:"-"` +} + +// ChannelDelete is the data for a ChannelDelete event. +type ChannelDelete struct { + *Channel +} + +// ChannelPinsUpdate stores data for a ChannelPinsUpdate event. +type ChannelPinsUpdate struct { + LastPinTimestamp string `json:"last_pin_timestamp"` + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id,omitempty"` +} + +// ThreadCreate is the data for a ThreadCreate event. +type ThreadCreate struct { + *Channel + NewlyCreated bool `json:"newly_created"` +} + +// ThreadUpdate is the data for a ThreadUpdate event. +type ThreadUpdate struct { + *Channel + BeforeUpdate *Channel `json:"-"` +} + +// ThreadDelete is the data for a ThreadDelete event. +type ThreadDelete struct { + *Channel +} + +// ThreadListSync is the data for a ThreadListSync event. +type ThreadListSync struct { + // The id of the guild + GuildID string `json:"guild_id"` + // The parent channel ids whose threads are being synced. + // If omitted, then threads were synced for the entire guild. + // This array may contain channel_ids that have no active threads as well, so you know to clear that data. + ChannelIDs []string `json:"channel_ids"` + // All active threads in the given channels that the current user can access + Threads []*Channel `json:"threads"` + // All thread member objects from the synced threads for the current user, + // indicating which threads the current user has been added to + Members []*ThreadMember `json:"members"` +} + +// ThreadMemberUpdate is the data for a ThreadMemberUpdate event. +type ThreadMemberUpdate struct { + *ThreadMember + GuildID string `json:"guild_id"` +} + +// ThreadMembersUpdate is the data for a ThreadMembersUpdate event. +type ThreadMembersUpdate struct { + ID string `json:"id"` + GuildID string `json:"guild_id"` + MemberCount int `json:"member_count"` + AddedMembers []AddedThreadMember `json:"added_members"` + RemovedMembers []string `json:"removed_member_ids"` +} + +// GuildCreate is the data for a GuildCreate event. +type GuildCreate struct { + *Guild +} + +// GuildUpdate is the data for a GuildUpdate event. +type GuildUpdate struct { + *Guild +} + +// GuildDelete is the data for a GuildDelete event. +type GuildDelete struct { + *Guild + BeforeDelete *Guild `json:"-"` +} + +// GuildBanAdd is the data for a GuildBanAdd event. +type GuildBanAdd struct { + User *User `json:"user"` + GuildID string `json:"guild_id"` +} + +// GuildBanRemove is the data for a GuildBanRemove event. +type GuildBanRemove struct { + User *User `json:"user"` + GuildID string `json:"guild_id"` +} + +// GuildMemberAdd is the data for a GuildMemberAdd event. +type GuildMemberAdd struct { + *Member +} + +// GuildMemberUpdate is the data for a GuildMemberUpdate event. +type GuildMemberUpdate struct { + *Member + BeforeUpdate *Member `json:"-"` +} + +// GuildMemberRemove is the data for a GuildMemberRemove event. +type GuildMemberRemove struct { + *Member +} + +// GuildRoleCreate is the data for a GuildRoleCreate event. +type GuildRoleCreate struct { + *GuildRole +} + +// GuildRoleUpdate is the data for a GuildRoleUpdate event. +type GuildRoleUpdate struct { + *GuildRole +} + +// A GuildRoleDelete is the data for a GuildRoleDelete event. +type GuildRoleDelete struct { + RoleID string `json:"role_id"` + GuildID string `json:"guild_id"` +} + +// A GuildEmojisUpdate is the data for a guild emoji update event. +type GuildEmojisUpdate struct { + GuildID string `json:"guild_id"` + Emojis []*Emoji `json:"emojis"` +} + +// A GuildStickersUpdate is the data for a GuildStickersUpdate event. +type GuildStickersUpdate struct { + GuildID string `json:"guild_id"` + Stickers []*Sticker `json:"stickers"` +} + +// A GuildMembersChunk is the data for a GuildMembersChunk event. +type GuildMembersChunk struct { + GuildID string `json:"guild_id"` + Members []*Member `json:"members"` + ChunkIndex int `json:"chunk_index"` + ChunkCount int `json:"chunk_count"` + NotFound []string `json:"not_found,omitempty"` + Presences []*Presence `json:"presences,omitempty"` + Nonce string `json:"nonce,omitempty"` +} + +// GuildIntegrationsUpdate is the data for a GuildIntegrationsUpdate event. +type GuildIntegrationsUpdate struct { + GuildID string `json:"guild_id"` +} + +// StageInstanceEventCreate is the data for a StageInstanceEventCreate event. +type StageInstanceEventCreate struct { + *StageInstance +} + +// StageInstanceEventUpdate is the data for a StageInstanceEventUpdate event. +type StageInstanceEventUpdate struct { + *StageInstance +} + +// StageInstanceEventDelete is the data for a StageInstanceEventDelete event. +type StageInstanceEventDelete struct { + *StageInstance +} + +// GuildScheduledEventCreate is the data for a GuildScheduledEventCreate event. +type GuildScheduledEventCreate struct { + *GuildScheduledEvent +} + +// GuildScheduledEventUpdate is the data for a GuildScheduledEventUpdate event. +type GuildScheduledEventUpdate struct { + *GuildScheduledEvent +} + +// GuildScheduledEventDelete is the data for a GuildScheduledEventDelete event. +type GuildScheduledEventDelete struct { + *GuildScheduledEvent +} + +// GuildScheduledEventUserAdd is the data for a GuildScheduledEventUserAdd event. +type GuildScheduledEventUserAdd struct { + GuildScheduledEventID string `json:"guild_scheduled_event_id"` + UserID string `json:"user_id"` + GuildID string `json:"guild_id"` +} + +// GuildScheduledEventUserRemove is the data for a GuildScheduledEventUserRemove event. +type GuildScheduledEventUserRemove struct { + GuildScheduledEventID string `json:"guild_scheduled_event_id"` + UserID string `json:"user_id"` + GuildID string `json:"guild_id"` +} + +// IntegrationCreate is the data for a IntegrationCreate event. +type IntegrationCreate struct { + *Integration + GuildID string `json:"guild_id"` +} + +// IntegrationUpdate is the data for a IntegrationUpdate event. +type IntegrationUpdate struct { + *Integration + GuildID string `json:"guild_id"` +} + +// IntegrationDelete is the data for a IntegrationDelete event. +type IntegrationDelete struct { + ID string `json:"id"` + GuildID string `json:"guild_id"` + ApplicationID string `json:"application_id,omitempty"` +} + +// MessageCreate is the data for a MessageCreate event. +type MessageCreate struct { + *Message +} + +// UnmarshalJSON is a helper function to unmarshal MessageCreate object. +func (m *MessageCreate) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &m.Message) +} + +// MessageUpdate is the data for a MessageUpdate event. +type MessageUpdate struct { + *Message + // BeforeUpdate will be nil if the Message was not previously cached in the state cache. + BeforeUpdate *Message `json:"-"` +} + +// UnmarshalJSON is a helper function to unmarshal MessageUpdate object. +func (m *MessageUpdate) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &m.Message) +} + +// MessageDelete is the data for a MessageDelete event. +type MessageDelete struct { + *Message + BeforeDelete *Message `json:"-"` +} + +// UnmarshalJSON is a helper function to unmarshal MessageDelete object. +func (m *MessageDelete) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &m.Message) +} + +// MessageReactionAdd is the data for a MessageReactionAdd event. +type MessageReactionAdd struct { + *MessageReaction + Member *Member `json:"member,omitempty"` +} + +// MessageReactionRemove is the data for a MessageReactionRemove event. +type MessageReactionRemove struct { + *MessageReaction +} + +// MessageReactionRemoveAll is the data for a MessageReactionRemoveAll event. +type MessageReactionRemoveAll struct { + *MessageReaction +} + +// PresencesReplace is the data for a PresencesReplace event. +type PresencesReplace []*Presence + +// PresenceUpdate is the data for a PresenceUpdate event. +type PresenceUpdate struct { + Presence + GuildID string `json:"guild_id"` +} + +// Resumed is the data for a Resumed event. +type Resumed struct { + Trace []string `json:"_trace"` +} + +// TypingStart is the data for a TypingStart event. +type TypingStart struct { + UserID string `json:"user_id"` + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id,omitempty"` + Timestamp int `json:"timestamp"` +} + +// UserUpdate is the data for a UserUpdate event. +type UserUpdate struct { + *User +} + +// VoiceServerUpdate is the data for a VoiceServerUpdate event. +type VoiceServerUpdate struct { + Token string `json:"token"` + GuildID string `json:"guild_id"` + Endpoint string `json:"endpoint"` +} + +// VoiceStateUpdate is the data for a VoiceStateUpdate event. +type VoiceStateUpdate struct { + *VoiceState + // BeforeUpdate will be nil if the VoiceState was not previously cached in the state cache. + BeforeUpdate *VoiceState `json:"-"` +} + +// MessageDeleteBulk is the data for a MessageDeleteBulk event +type MessageDeleteBulk struct { + Messages []string `json:"ids"` + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id"` +} + +// WebhooksUpdate is the data for a WebhooksUpdate event +type WebhooksUpdate struct { + GuildID string `json:"guild_id"` + ChannelID string `json:"channel_id"` +} + +// InteractionCreate is the data for a InteractionCreate event +type InteractionCreate struct { + *Interaction +} + +// UnmarshalJSON is a helper function to unmarshal Interaction object. +func (i *InteractionCreate) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &i.Interaction) +} + +// InviteCreate is the data for a InviteCreate event +type InviteCreate struct { + *Invite + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id"` +} + +// InviteDelete is the data for a InviteDelete event +type InviteDelete struct { + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id"` + Code string `json:"code"` +} + +// ApplicationCommandPermissionsUpdate is the data for an ApplicationCommandPermissionsUpdate event +type ApplicationCommandPermissionsUpdate struct { + *GuildApplicationCommandPermissions +} + +// AutoModerationRuleCreate is the data for an AutoModerationRuleCreate event. +type AutoModerationRuleCreate struct { + *AutoModerationRule +} + +// AutoModerationRuleUpdate is the data for an AutoModerationRuleUpdate event. +type AutoModerationRuleUpdate struct { + *AutoModerationRule +} + +// AutoModerationRuleDelete is the data for an AutoModerationRuleDelete event. +type AutoModerationRuleDelete struct { + *AutoModerationRule +} + +// AutoModerationActionExecution is the data for an AutoModerationActionExecution event. +type AutoModerationActionExecution struct { + GuildID string `json:"guild_id"` + Action AutoModerationAction `json:"action"` + RuleID string `json:"rule_id"` + RuleTriggerType AutoModerationRuleTriggerType `json:"rule_trigger_type"` + UserID string `json:"user_id"` + ChannelID string `json:"channel_id"` + MessageID string `json:"message_id"` + AlertSystemMessageID string `json:"alert_system_message_id"` + Content string `json:"content"` + MatchedKeyword string `json:"matched_keyword"` + MatchedContent string `json:"matched_content"` +} + +// GuildAuditLogEntryCreate is the data for a GuildAuditLogEntryCreate event. +type GuildAuditLogEntryCreate struct { + *AuditLogEntry + GuildID string `json:"guild_id"` +} + +// MessagePollVoteAdd is the data for a MessagePollVoteAdd event. +type MessagePollVoteAdd struct { + UserID string `json:"user_id"` + ChannelID string `json:"channel_id"` + MessageID string `json:"message_id"` + GuildID string `json:"guild_id,omitempty"` + AnswerID int `json:"answer_id"` +} + +// MessagePollVoteRemove is the data for a MessagePollVoteRemove event. +type MessagePollVoteRemove struct { + UserID string `json:"user_id"` + ChannelID string `json:"channel_id"` + MessageID string `json:"message_id"` + GuildID string `json:"guild_id,omitempty"` + AnswerID int `json:"answer_id"` +} + +// EntitlementCreate is the data for an EntitlementCreate event. +type EntitlementCreate struct { + *Entitlement +} + +// EntitlementUpdate is the data for an EntitlementUpdate event. +type EntitlementUpdate struct { + *Entitlement +} + +// EntitlementDelete is the data for an EntitlementDelete event. +// NOTE: Entitlements are not deleted when they expire. +type EntitlementDelete struct { + *Entitlement +} + +// SubscriptionCreate is the data for an SubscriptionCreate event. +// https://discord.com/developers/docs/monetization/implementing-app-subscriptions#using-subscription-events-for-the-subscription-lifecycle +type SubscriptionCreate struct { + *Subscription +} + +// SubscriptionUpdate is the data for an SubscriptionUpdate event. +// https://discord.com/developers/docs/monetization/implementing-app-subscriptions#using-subscription-events-for-the-subscription-lifecycle +type SubscriptionUpdate struct { + *Subscription +} + +// SubscriptionDelete is the data for an SubscriptionDelete event. +// https://discord.com/developers/docs/monetization/implementing-app-subscriptions#using-subscription-events-for-the-subscription-lifecycle +type SubscriptionDelete struct { + *Subscription +} diff --git a/vendor/github.com/bwmarrin/discordgo/interactions.go b/vendor/github.com/bwmarrin/discordgo/interactions.go new file mode 100644 index 000000000..1450ad3f1 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/interactions.go @@ -0,0 +1,662 @@ +package discordgo + +import ( + "bytes" + "crypto/ed25519" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "strconv" + "time" +) + +// InteractionDeadline is the time allowed to respond to an interaction. +const InteractionDeadline = time.Second * 3 + +// ApplicationCommandType represents the type of application command. +type ApplicationCommandType uint8 + +// Application command types +const ( + // ChatApplicationCommand is default command type. They are slash commands (i.e. called directly from the chat). + ChatApplicationCommand ApplicationCommandType = 1 + // UserApplicationCommand adds command to user context menu. + UserApplicationCommand ApplicationCommandType = 2 + // MessageApplicationCommand adds command to message context menu. + MessageApplicationCommand ApplicationCommandType = 3 +) + +// ApplicationCommand represents an application's slash command. +type ApplicationCommand struct { + ID string `json:"id,omitempty"` + ApplicationID string `json:"application_id,omitempty"` + GuildID string `json:"guild_id,omitempty"` + Version string `json:"version,omitempty"` + Type ApplicationCommandType `json:"type,omitempty"` + Name string `json:"name"` + NameLocalizations *map[Locale]string `json:"name_localizations,omitempty"` + + // NOTE: DefaultPermission will be soon deprecated. Use DefaultMemberPermissions and Contexts instead. + DefaultPermission *bool `json:"default_permission,omitempty"` + DefaultMemberPermissions *int64 `json:"default_member_permissions,string,omitempty"` + NSFW *bool `json:"nsfw,omitempty"` + + // Deprecated: use Contexts instead. + DMPermission *bool `json:"dm_permission,omitempty"` + Contexts *[]InteractionContextType `json:"contexts,omitempty"` + IntegrationTypes *[]ApplicationIntegrationType `json:"integration_types,omitempty"` + + // NOTE: Chat commands only. Otherwise it mustn't be set. + + Description string `json:"description,omitempty"` + DescriptionLocalizations *map[Locale]string `json:"description_localizations,omitempty"` + Options []*ApplicationCommandOption `json:"options"` +} + +// ApplicationCommandOptionType indicates the type of a slash command's option. +type ApplicationCommandOptionType uint8 + +// Application command option types. +const ( + ApplicationCommandOptionSubCommand ApplicationCommandOptionType = 1 + ApplicationCommandOptionSubCommandGroup ApplicationCommandOptionType = 2 + ApplicationCommandOptionString ApplicationCommandOptionType = 3 + ApplicationCommandOptionInteger ApplicationCommandOptionType = 4 + ApplicationCommandOptionBoolean ApplicationCommandOptionType = 5 + ApplicationCommandOptionUser ApplicationCommandOptionType = 6 + ApplicationCommandOptionChannel ApplicationCommandOptionType = 7 + ApplicationCommandOptionRole ApplicationCommandOptionType = 8 + ApplicationCommandOptionMentionable ApplicationCommandOptionType = 9 + ApplicationCommandOptionNumber ApplicationCommandOptionType = 10 + ApplicationCommandOptionAttachment ApplicationCommandOptionType = 11 +) + +func (t ApplicationCommandOptionType) String() string { + switch t { + case ApplicationCommandOptionSubCommand: + return "SubCommand" + case ApplicationCommandOptionSubCommandGroup: + return "SubCommandGroup" + case ApplicationCommandOptionString: + return "String" + case ApplicationCommandOptionInteger: + return "Integer" + case ApplicationCommandOptionBoolean: + return "Boolean" + case ApplicationCommandOptionUser: + return "User" + case ApplicationCommandOptionChannel: + return "Channel" + case ApplicationCommandOptionRole: + return "Role" + case ApplicationCommandOptionMentionable: + return "Mentionable" + case ApplicationCommandOptionNumber: + return "Number" + case ApplicationCommandOptionAttachment: + return "Attachment" + } + return fmt.Sprintf("ApplicationCommandOptionType(%d)", t) +} + +// ApplicationCommandOption represents an option/subcommand/subcommands group. +type ApplicationCommandOption struct { + Type ApplicationCommandOptionType `json:"type"` + Name string `json:"name"` + NameLocalizations map[Locale]string `json:"name_localizations,omitempty"` + Description string `json:"description,omitempty"` + DescriptionLocalizations map[Locale]string `json:"description_localizations,omitempty"` + // NOTE: This feature was on the API, but at some point developers decided to remove it. + // So I commented it, until it will be officially on the docs. + // Default bool `json:"default"` + + ChannelTypes []ChannelType `json:"channel_types"` + Required bool `json:"required"` + Options []*ApplicationCommandOption `json:"options"` + + // NOTE: mutually exclusive with Choices. + Autocomplete bool `json:"autocomplete"` + Choices []*ApplicationCommandOptionChoice `json:"choices"` + // Minimal value of number/integer option. + MinValue *float64 `json:"min_value,omitempty"` + // Maximum value of number/integer option. + MaxValue float64 `json:"max_value,omitempty"` + // Minimum length of string option. + MinLength *int `json:"min_length,omitempty"` + // Maximum length of string option. + MaxLength int `json:"max_length,omitempty"` +} + +// ApplicationCommandOptionChoice represents a slash command option choice. +type ApplicationCommandOptionChoice struct { + Name string `json:"name"` + NameLocalizations map[Locale]string `json:"name_localizations,omitempty"` + Value interface{} `json:"value"` +} + +// ApplicationCommandPermissions represents a single user or role permission for a command. +type ApplicationCommandPermissions struct { + ID string `json:"id"` + Type ApplicationCommandPermissionType `json:"type"` + Permission bool `json:"permission"` +} + +// GuildAllChannelsID is a helper function which returns guild_id-1. +// It is used in ApplicationCommandPermissions to target all the channels within a guild. +func GuildAllChannelsID(guild string) (id string, err error) { + var v uint64 + v, err = strconv.ParseUint(guild, 10, 64) + if err != nil { + return + } + + return strconv.FormatUint(v-1, 10), nil +} + +// ApplicationCommandPermissionsList represents a list of ApplicationCommandPermissions, needed for serializing to JSON. +type ApplicationCommandPermissionsList struct { + Permissions []*ApplicationCommandPermissions `json:"permissions"` +} + +// GuildApplicationCommandPermissions represents all permissions for a single guild command. +type GuildApplicationCommandPermissions struct { + ID string `json:"id"` + ApplicationID string `json:"application_id"` + GuildID string `json:"guild_id"` + Permissions []*ApplicationCommandPermissions `json:"permissions"` +} + +// ApplicationCommandPermissionType indicates whether a permission is user or role based. +type ApplicationCommandPermissionType uint8 + +// Application command permission types. +const ( + ApplicationCommandPermissionTypeRole ApplicationCommandPermissionType = 1 + ApplicationCommandPermissionTypeUser ApplicationCommandPermissionType = 2 + ApplicationCommandPermissionTypeChannel ApplicationCommandPermissionType = 3 +) + +// InteractionType indicates the type of an interaction event. +type InteractionType uint8 + +// Interaction types +const ( + InteractionPing InteractionType = 1 + InteractionApplicationCommand InteractionType = 2 + InteractionMessageComponent InteractionType = 3 + InteractionApplicationCommandAutocomplete InteractionType = 4 + InteractionModalSubmit InteractionType = 5 +) + +func (t InteractionType) String() string { + switch t { + case InteractionPing: + return "Ping" + case InteractionApplicationCommand: + return "ApplicationCommand" + case InteractionMessageComponent: + return "MessageComponent" + case InteractionModalSubmit: + return "ModalSubmit" + } + return fmt.Sprintf("InteractionType(%d)", t) +} + +// InteractionContextType represents the context in which interaction can be used or was triggered from. +type InteractionContextType uint + +const ( + // InteractionContextGuild indicates that interaction can be used within guilds. + InteractionContextGuild InteractionContextType = 0 + // InteractionContextBotDM indicates that interaction can be used within DMs with the bot. + InteractionContextBotDM InteractionContextType = 1 + // InteractionContextPrivateChannel indicates that interaction can be used within group DMs and DMs with other users. + InteractionContextPrivateChannel InteractionContextType = 2 +) + +// Interaction represents data of an interaction. +type Interaction struct { + ID string `json:"id"` + AppID string `json:"application_id"` + Type InteractionType `json:"type"` + Data InteractionData `json:"data"` + GuildID string `json:"guild_id"` + ChannelID string `json:"channel_id"` + + // The message on which interaction was used. + // NOTE: this field is only filled when a button click triggered the interaction. Otherwise it will be nil. + Message *Message `json:"message"` + + // Bitwise set of permissions the app or bot has within the channel the interaction was sent from + AppPermissions int64 `json:"app_permissions,string"` + + // The member who invoked this interaction. + // NOTE: this field is only filled when the slash command was invoked in a guild; + // if it was invoked in a DM, the `User` field will be filled instead. + // Make sure to check for `nil` before using this field. + Member *Member `json:"member"` + // The user who invoked this interaction. + // NOTE: this field is only filled when the slash command was invoked in a DM; + // if it was invoked in a guild, the `Member` field will be filled instead. + // Make sure to check for `nil` before using this field. + User *User `json:"user"` + + // The user's discord client locale. + Locale Locale `json:"locale"` + // The guild's locale. This defaults to EnglishUS + // NOTE: this field is only filled when the interaction was invoked in a guild. + GuildLocale *Locale `json:"guild_locale"` + + Context InteractionContextType `json:"context"` + AuthorizingIntegrationOwners map[ApplicationIntegrationType]string `json:"authorizing_integration_owners"` + + Token string `json:"token"` + Version int `json:"version"` + + // Any entitlements for the invoking user, representing access to premium SKUs. + // NOTE: this field is only filled in monetized apps + Entitlements []*Entitlement `json:"entitlements"` +} + +type interaction Interaction + +type rawInteraction struct { + interaction + Data json.RawMessage `json:"data"` +} + +// UnmarshalJSON is a method for unmarshalling JSON object to Interaction. +func (i *Interaction) UnmarshalJSON(raw []byte) error { + var tmp rawInteraction + err := json.Unmarshal(raw, &tmp) + if err != nil { + return err + } + + *i = Interaction(tmp.interaction) + + switch tmp.Type { + case InteractionApplicationCommand, InteractionApplicationCommandAutocomplete: + v := ApplicationCommandInteractionData{} + err = json.Unmarshal(tmp.Data, &v) + if err != nil { + return err + } + i.Data = v + case InteractionMessageComponent: + v := MessageComponentInteractionData{} + err = json.Unmarshal(tmp.Data, &v) + if err != nil { + return err + } + i.Data = v + case InteractionModalSubmit: + v := ModalSubmitInteractionData{} + err = json.Unmarshal(tmp.Data, &v) + if err != nil { + return err + } + i.Data = v + } + return nil +} + +// MessageComponentData is helper function to assert the inner InteractionData to MessageComponentInteractionData. +// Make sure to check that the Type of the interaction is InteractionMessageComponent before calling. +func (i Interaction) MessageComponentData() (data MessageComponentInteractionData) { + if i.Type != InteractionMessageComponent { + panic("MessageComponentData called on interaction of type " + i.Type.String()) + } + return i.Data.(MessageComponentInteractionData) +} + +// ApplicationCommandData is helper function to assert the inner InteractionData to ApplicationCommandInteractionData. +// Make sure to check that the Type of the interaction is InteractionApplicationCommand before calling. +func (i Interaction) ApplicationCommandData() (data ApplicationCommandInteractionData) { + if i.Type != InteractionApplicationCommand && i.Type != InteractionApplicationCommandAutocomplete { + panic("ApplicationCommandData called on interaction of type " + i.Type.String()) + } + return i.Data.(ApplicationCommandInteractionData) +} + +// ModalSubmitData is helper function to assert the inner InteractionData to ModalSubmitInteractionData. +// Make sure to check that the Type of the interaction is InteractionModalSubmit before calling. +func (i Interaction) ModalSubmitData() (data ModalSubmitInteractionData) { + if i.Type != InteractionModalSubmit { + panic("ModalSubmitData called on interaction of type " + i.Type.String()) + } + return i.Data.(ModalSubmitInteractionData) +} + +// InteractionData is a common interface for all types of interaction data. +type InteractionData interface { + Type() InteractionType +} + +// ApplicationCommandInteractionData contains the data of application command interaction. +type ApplicationCommandInteractionData struct { + ID string `json:"id"` + Name string `json:"name"` + CommandType ApplicationCommandType `json:"type"` + Resolved *ApplicationCommandInteractionDataResolved `json:"resolved"` + + // Slash command options + Options []*ApplicationCommandInteractionDataOption `json:"options"` + // Target (user/message) id on which context menu command was called. + // The details are stored in Resolved according to command type. + TargetID string `json:"target_id"` +} + +// GetOption finds and returns an application command option by its name. +func (d ApplicationCommandInteractionData) GetOption(name string) (option *ApplicationCommandInteractionDataOption) { + for _, opt := range d.Options { + if opt.Name == name { + option = opt + break + } + } + + return +} + +// ApplicationCommandInteractionDataResolved contains resolved data of command execution. +// Partial Member objects are missing user, deaf and mute fields. +// Partial Channel objects only have id, name, type and permissions fields. +type ApplicationCommandInteractionDataResolved struct { + Users map[string]*User `json:"users"` + Members map[string]*Member `json:"members"` + Roles map[string]*Role `json:"roles"` + Channels map[string]*Channel `json:"channels"` + Messages map[string]*Message `json:"messages"` + Attachments map[string]*MessageAttachment `json:"attachments"` +} + +// Type returns the type of interaction data. +func (ApplicationCommandInteractionData) Type() InteractionType { + return InteractionApplicationCommand +} + +// MessageComponentInteractionData contains the data of message component interaction. +type MessageComponentInteractionData struct { + CustomID string `json:"custom_id"` + ComponentType ComponentType `json:"component_type"` + Resolved MessageComponentInteractionDataResolved `json:"resolved"` + + // NOTE: Only filled when ComponentType is SelectMenuComponent (3). Otherwise is nil. + Values []string `json:"values"` +} + +// MessageComponentInteractionDataResolved contains the resolved data of selected option. +type MessageComponentInteractionDataResolved struct { + Users map[string]*User `json:"users"` + Members map[string]*Member `json:"members"` + Roles map[string]*Role `json:"roles"` + Channels map[string]*Channel `json:"channels"` +} + +// Type returns the type of interaction data. +func (MessageComponentInteractionData) Type() InteractionType { + return InteractionMessageComponent +} + +// ModalSubmitInteractionData contains the data of modal submit interaction. +type ModalSubmitInteractionData struct { + CustomID string `json:"custom_id"` + Components []MessageComponent `json:"-"` +} + +// Type returns the type of interaction data. +func (ModalSubmitInteractionData) Type() InteractionType { + return InteractionModalSubmit +} + +// UnmarshalJSON is a helper function to correctly unmarshal Components. +func (d *ModalSubmitInteractionData) UnmarshalJSON(data []byte) error { + type modalSubmitInteractionData ModalSubmitInteractionData + var v struct { + modalSubmitInteractionData + RawComponents []unmarshalableMessageComponent `json:"components"` + } + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + *d = ModalSubmitInteractionData(v.modalSubmitInteractionData) + d.Components = make([]MessageComponent, len(v.RawComponents)) + for i, v := range v.RawComponents { + d.Components[i] = v.MessageComponent + } + return err +} + +// ApplicationCommandInteractionDataOption represents an option of a slash command. +type ApplicationCommandInteractionDataOption struct { + Name string `json:"name"` + Type ApplicationCommandOptionType `json:"type"` + // NOTE: Contains the value specified by Type. + Value interface{} `json:"value,omitempty"` + Options []*ApplicationCommandInteractionDataOption `json:"options,omitempty"` + + // NOTE: autocomplete interaction only. + Focused bool `json:"focused,omitempty"` +} + +// GetOption finds and returns an application command option by its name. +func (o ApplicationCommandInteractionDataOption) GetOption(name string) (option *ApplicationCommandInteractionDataOption) { + for _, opt := range o.Options { + if opt.Name == name { + option = opt + break + } + } + + return +} + +// IntValue is a utility function for casting option value to integer +func (o ApplicationCommandInteractionDataOption) IntValue() int64 { + if o.Type != ApplicationCommandOptionInteger { + panic("IntValue called on data option of type " + o.Type.String()) + } + return int64(o.Value.(float64)) +} + +// UintValue is a utility function for casting option value to unsigned integer +func (o ApplicationCommandInteractionDataOption) UintValue() uint64 { + if o.Type != ApplicationCommandOptionInteger { + panic("UintValue called on data option of type " + o.Type.String()) + } + return uint64(o.Value.(float64)) +} + +// FloatValue is a utility function for casting option value to float +func (o ApplicationCommandInteractionDataOption) FloatValue() float64 { + if o.Type != ApplicationCommandOptionNumber { + panic("FloatValue called on data option of type " + o.Type.String()) + } + return o.Value.(float64) +} + +// StringValue is a utility function for casting option value to string +func (o ApplicationCommandInteractionDataOption) StringValue() string { + if o.Type != ApplicationCommandOptionString { + panic("StringValue called on data option of type " + o.Type.String()) + } + return o.Value.(string) +} + +// BoolValue is a utility function for casting option value to bool +func (o ApplicationCommandInteractionDataOption) BoolValue() bool { + if o.Type != ApplicationCommandOptionBoolean { + panic("BoolValue called on data option of type " + o.Type.String()) + } + return o.Value.(bool) +} + +// ChannelValue is a utility function for casting option value to channel object. +// s : Session object, if not nil, function additionally fetches all channel's data +func (o ApplicationCommandInteractionDataOption) ChannelValue(s *Session) *Channel { + if o.Type != ApplicationCommandOptionChannel { + panic("ChannelValue called on data option of type " + o.Type.String()) + } + chanID := o.Value.(string) + + if s == nil { + return &Channel{ID: chanID} + } + + ch, err := s.State.Channel(chanID) + if err != nil { + ch, err = s.Channel(chanID) + if err != nil { + return &Channel{ID: chanID} + } + } + + return ch +} + +// RoleValue is a utility function for casting option value to role object. +// s : Session object, if not nil, function additionally fetches all role's data +func (o ApplicationCommandInteractionDataOption) RoleValue(s *Session, gID string) *Role { + if o.Type != ApplicationCommandOptionRole && o.Type != ApplicationCommandOptionMentionable { + panic("RoleValue called on data option of type " + o.Type.String()) + } + roleID := o.Value.(string) + + if s == nil || gID == "" { + return &Role{ID: roleID} + } + + r, err := s.State.Role(gID, roleID) + if err != nil { + roles, err := s.GuildRoles(gID) + if err == nil { + for _, r = range roles { + if r.ID == roleID { + return r + } + } + } + return &Role{ID: roleID} + } + + return r +} + +// UserValue is a utility function for casting option value to user object. +// s : Session object, if not nil, function additionally fetches all user's data +func (o ApplicationCommandInteractionDataOption) UserValue(s *Session) *User { + if o.Type != ApplicationCommandOptionUser && o.Type != ApplicationCommandOptionMentionable { + panic("UserValue called on data option of type " + o.Type.String()) + } + userID := o.Value.(string) + + if s == nil { + return &User{ID: userID} + } + + u, err := s.User(userID) + if err != nil { + return &User{ID: userID} + } + + return u +} + +// InteractionResponseType is type of interaction response. +type InteractionResponseType uint8 + +// Interaction response types. +const ( + // InteractionResponsePong is for ACK ping event. + InteractionResponsePong InteractionResponseType = 1 + // InteractionResponseChannelMessageWithSource is for responding with a message, showing the user's input. + InteractionResponseChannelMessageWithSource InteractionResponseType = 4 + // InteractionResponseDeferredChannelMessageWithSource acknowledges that the event was received, and that a follow-up will come later. + InteractionResponseDeferredChannelMessageWithSource InteractionResponseType = 5 + // InteractionResponseDeferredMessageUpdate acknowledges that the message component interaction event was received, and message will be updated later. + InteractionResponseDeferredMessageUpdate InteractionResponseType = 6 + // InteractionResponseUpdateMessage is for updating the message to which message component was attached. + InteractionResponseUpdateMessage InteractionResponseType = 7 + // InteractionApplicationCommandAutocompleteResult shows autocompletion results. Autocomplete interaction only. + InteractionApplicationCommandAutocompleteResult InteractionResponseType = 8 + // InteractionResponseModal is for responding to an interaction with a modal window. + InteractionResponseModal InteractionResponseType = 9 +) + +// InteractionResponse represents a response for an interaction event. +type InteractionResponse struct { + Type InteractionResponseType `json:"type,omitempty"` + Data *InteractionResponseData `json:"data,omitempty"` +} + +// InteractionResponseData is response data for an interaction. +type InteractionResponseData struct { + TTS bool `json:"tts"` + Content string `json:"content"` + Components []MessageComponent `json:"components"` + Embeds []*MessageEmbed `json:"embeds"` + AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"` + Files []*File `json:"-"` + Attachments *[]*MessageAttachment `json:"attachments,omitempty"` + Poll *Poll `json:"poll,omitempty"` + + // NOTE: only MessageFlagsSuppressEmbeds and MessageFlagsEphemeral can be set. + Flags MessageFlags `json:"flags,omitempty"` + + // NOTE: autocomplete interaction only. + Choices []*ApplicationCommandOptionChoice `json:"choices,omitempty"` + + // NOTE: modal interaction only. + + CustomID string `json:"custom_id,omitempty"` + Title string `json:"title,omitempty"` +} + +// VerifyInteraction implements message verification of the discord interactions api +// signing algorithm, as documented here: +// https://discord.com/developers/docs/interactions/receiving-and-responding#security-and-authorization +func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool { + var msg bytes.Buffer + + signature := r.Header.Get("X-Signature-Ed25519") + if signature == "" { + return false + } + + sig, err := hex.DecodeString(signature) + if err != nil { + return false + } + + if len(sig) != ed25519.SignatureSize { + return false + } + + timestamp := r.Header.Get("X-Signature-Timestamp") + if timestamp == "" { + return false + } + + msg.WriteString(timestamp) + + defer r.Body.Close() + var body bytes.Buffer + + // at the end of the function, copy the original body back into the request + defer func() { + r.Body = ioutil.NopCloser(&body) + }() + + // copy body into buffers + _, err = io.Copy(&msg, io.TeeReader(r.Body, &body)) + if err != nil { + return false + } + + return ed25519.Verify(key, msg.Bytes(), sig) +} diff --git a/vendor/github.com/bwmarrin/discordgo/locales.go b/vendor/github.com/bwmarrin/discordgo/locales.go new file mode 100644 index 000000000..3b45b792a --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/locales.go @@ -0,0 +1,85 @@ +package discordgo + +// Locale represents the accepted languages for Discord. +// https://discord.com/developers/docs/reference#locales +type Locale string + +// String returns the human-readable string of the locale +func (l Locale) String() string { + if name, ok := Locales[l]; ok { + return name + } + return Unknown.String() +} + +// All defined locales in Discord +const ( + EnglishUS Locale = "en-US" + EnglishGB Locale = "en-GB" + Bulgarian Locale = "bg" + ChineseCN Locale = "zh-CN" + ChineseTW Locale = "zh-TW" + Croatian Locale = "hr" + Czech Locale = "cs" + Danish Locale = "da" + Dutch Locale = "nl" + Finnish Locale = "fi" + French Locale = "fr" + German Locale = "de" + Greek Locale = "el" + Hindi Locale = "hi" + Hungarian Locale = "hu" + Italian Locale = "it" + Japanese Locale = "ja" + Korean Locale = "ko" + Lithuanian Locale = "lt" + Norwegian Locale = "no" + Polish Locale = "pl" + PortugueseBR Locale = "pt-BR" + Romanian Locale = "ro" + Russian Locale = "ru" + SpanishES Locale = "es-ES" + SpanishLATAM Locale = "es-419" + Swedish Locale = "sv-SE" + Thai Locale = "th" + Turkish Locale = "tr" + Ukrainian Locale = "uk" + Vietnamese Locale = "vi" + Unknown Locale = "" +) + +// Locales is a map of all the languages codes to their names. +var Locales = map[Locale]string{ + EnglishUS: "English (United States)", + EnglishGB: "English (Great Britain)", + Bulgarian: "Bulgarian", + ChineseCN: "Chinese (China)", + ChineseTW: "Chinese (Taiwan)", + Croatian: "Croatian", + Czech: "Czech", + Danish: "Danish", + Dutch: "Dutch", + Finnish: "Finnish", + French: "French", + German: "German", + Greek: "Greek", + Hindi: "Hindi", + Hungarian: "Hungarian", + Italian: "Italian", + Japanese: "Japanese", + Korean: "Korean", + Lithuanian: "Lithuanian", + Norwegian: "Norwegian", + Polish: "Polish", + PortugueseBR: "Portuguese (Brazil)", + Romanian: "Romanian", + Russian: "Russian", + SpanishES: "Spanish (Spain)", + SpanishLATAM: "Spanish (LATAM)", + Swedish: "Swedish", + Thai: "Thai", + Turkish: "Turkish", + Ukrainian: "Ukrainian", + Vietnamese: "Vietnamese", + Unknown: "unknown", +} diff --git a/vendor/github.com/bwmarrin/discordgo/logging.go b/vendor/github.com/bwmarrin/discordgo/logging.go new file mode 100644 index 000000000..b798d3e87 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/logging.go @@ -0,0 +1,103 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains code related to discordgo package logging + +package discordgo + +import ( + "fmt" + "log" + "runtime" + "strings" +) + +const ( + + // LogError level is used for critical errors that could lead to data loss + // or panic that would not be returned to a calling function. + LogError int = iota + + // LogWarning level is used for very abnormal events and errors that are + // also returned to a calling function. + LogWarning + + // LogInformational level is used for normal non-error activity + LogInformational + + // LogDebug level is for very detailed non-error activity. This is + // very spammy and will impact performance. + LogDebug +) + +// Logger can be used to replace the standard logging for discordgo +var Logger func(msgL, caller int, format string, a ...interface{}) + +// msglog provides package wide logging consistency for discordgo +// the format, a... portion this command follows that of fmt.Printf +// msgL : LogLevel of the message +// caller : 1 + the number of callers away from the message source +// format : Printf style message format +// a ... : comma separated list of values to pass +func msglog(msgL, caller int, format string, a ...interface{}) { + + if Logger != nil { + Logger(msgL, caller, format, a...) + } else { + + pc, file, line, _ := runtime.Caller(caller) + + files := strings.Split(file, "/") + file = files[len(files)-1] + + name := runtime.FuncForPC(pc).Name() + fns := strings.Split(name, ".") + name = fns[len(fns)-1] + + msg := fmt.Sprintf(format, a...) + + log.Printf("[DG%d] %s:%d:%s() %s\n", msgL, file, line, name, msg) + } +} + +// helper function that wraps msglog for the Session struct +// This adds a check to insure the message is only logged +// if the session log level is equal or higher than the +// message log level +func (s *Session) log(msgL int, format string, a ...interface{}) { + + if msgL > s.LogLevel { + return + } + + msglog(msgL, 2, format, a...) +} + +// helper function that wraps msglog for the VoiceConnection struct +// This adds a check to insure the message is only logged +// if the voice connection log level is equal or higher than the +// message log level +func (v *VoiceConnection) log(msgL int, format string, a ...interface{}) { + + if msgL > v.LogLevel { + return + } + + msglog(msgL, 2, format, a...) +} + +// printJSON is a helper function to display JSON data in an easy to read format. +/* NOT USED ATM +func printJSON(body []byte) { + var prettyJSON bytes.Buffer + error := json.Indent(&prettyJSON, body, "", "\t") + if error != nil { + log.Print("JSON parse error: ", error) + } + log.Println(string(prettyJSON.Bytes())) +} +*/ diff --git a/vendor/github.com/bwmarrin/discordgo/message.go b/vendor/github.com/bwmarrin/discordgo/message.go new file mode 100644 index 000000000..4954ed4d3 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/message.go @@ -0,0 +1,638 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains code related to the Message struct + +package discordgo + +import ( + "encoding/json" + "io" + "regexp" + "strings" + "time" +) + +// MessageType is the type of Message +// https://discord.com/developers/docs/resources/channel#message-object-message-types +type MessageType int + +// Block contains the valid known MessageType values +const ( + MessageTypeDefault MessageType = 0 + MessageTypeRecipientAdd MessageType = 1 + MessageTypeRecipientRemove MessageType = 2 + MessageTypeCall MessageType = 3 + MessageTypeChannelNameChange MessageType = 4 + MessageTypeChannelIconChange MessageType = 5 + MessageTypeChannelPinnedMessage MessageType = 6 + MessageTypeGuildMemberJoin MessageType = 7 + MessageTypeUserPremiumGuildSubscription MessageType = 8 + MessageTypeUserPremiumGuildSubscriptionTierOne MessageType = 9 + MessageTypeUserPremiumGuildSubscriptionTierTwo MessageType = 10 + MessageTypeUserPremiumGuildSubscriptionTierThree MessageType = 11 + MessageTypeChannelFollowAdd MessageType = 12 + MessageTypeGuildDiscoveryDisqualified MessageType = 14 + MessageTypeGuildDiscoveryRequalified MessageType = 15 + MessageTypeThreadCreated MessageType = 18 + MessageTypeReply MessageType = 19 + MessageTypeChatInputCommand MessageType = 20 + MessageTypeThreadStarterMessage MessageType = 21 + MessageTypeContextMenuCommand MessageType = 23 +) + +// A Message stores all data related to a specific Discord message. +type Message struct { + // The ID of the message. + ID string `json:"id"` + + // The ID of the channel in which the message was sent. + ChannelID string `json:"channel_id"` + + // The ID of the guild in which the message was sent. + GuildID string `json:"guild_id,omitempty"` + + // The content of the message. + Content string `json:"content"` + + // The time at which the messsage was sent. + // CAUTION: this field may be removed in a + // future API version; it is safer to calculate + // the creation time via the ID. + Timestamp time.Time `json:"timestamp"` + + // The time at which the last edit of the message + // occurred, if it has been edited. + EditedTimestamp *time.Time `json:"edited_timestamp"` + + // The roles mentioned in the message. + MentionRoles []string `json:"mention_roles"` + + // Whether the message is text-to-speech. + TTS bool `json:"tts"` + + // Whether the message mentions everyone. + MentionEveryone bool `json:"mention_everyone"` + + // The author of the message. This is not guaranteed to be a + // valid user (webhook-sent messages do not possess a full author). + Author *User `json:"author"` + + // A list of attachments present in the message. + Attachments []*MessageAttachment `json:"attachments"` + + // A list of components attached to the message. + Components []MessageComponent `json:"-"` + + // A list of embeds present in the message. + Embeds []*MessageEmbed `json:"embeds"` + + // A list of users mentioned in the message. + Mentions []*User `json:"mentions"` + + // A list of reactions to the message. + Reactions []*MessageReactions `json:"reactions"` + + // Whether the message is pinned or not. + Pinned bool `json:"pinned"` + + // The type of the message. + Type MessageType `json:"type"` + + // The webhook ID of the message, if it was generated by a webhook + WebhookID string `json:"webhook_id"` + + // Member properties for this message's author, + // contains only partial information + Member *Member `json:"member"` + + // Channels specifically mentioned in this message + // Not all channel mentions in a message will appear in mention_channels. + // Only textual channels that are visible to everyone in a lurkable guild will ever be included. + // Only crossposted messages (via Channel Following) currently include mention_channels at all. + // If no mentions in the message meet these requirements, this field will not be sent. + MentionChannels []*Channel `json:"mention_channels"` + + // Is sent with Rich Presence-related chat embeds + Activity *MessageActivity `json:"activity"` + + // Is sent with Rich Presence-related chat embeds + Application *MessageApplication `json:"application"` + + // MessageReference contains reference data sent with crossposted or reply messages. + // This does not contain the reference *to* this message; this is for when *this* message references another. + // To generate a reference to this message, use (*Message).Reference(). + MessageReference *MessageReference `json:"message_reference"` + + // The message associated with the message_reference + // NOTE: This field is only returned for messages with a type of 19 (REPLY) or 21 (THREAD_STARTER_MESSAGE). + // If the message is a reply but the referenced_message field is not present, + // the backend did not attempt to fetch the message that was being replied to, so its state is unknown. + // If the field exists but is null, the referenced message was deleted. + ReferencedMessage *Message `json:"referenced_message"` + + // The message associated with the message_reference. + // This is a minimal subset of fields in a message (e.g. Author is excluded) + // NOTE: This field is only returned when referenced when MessageReference.Type is MessageReferenceTypeForward. + MessageSnapshots []MessageSnapshot `json:"message_snapshots"` + + // Deprecated, use InteractionMetadata. + // Is sent when the message is a response to an Interaction, without an existing message. + // This means responses to message component interactions do not include this property, + // instead including a MessageReference, as components exist on preexisting messages. + Interaction *MessageInteraction `json:"interaction"` + + InteractionMetadata *MessageInteractionMetadata `json:"interaction_metadata"` + + // The flags of the message, which describe extra features of a message. + // This is a combination of bit masks; the presence of a certain permission can + // be checked by performing a bitwise AND between this int and the flag. + Flags MessageFlags `json:"flags"` + + // The thread that was started from this message, includes thread member object + Thread *Channel `json:"thread,omitempty"` + + // An array of StickerItem objects, representing sent stickers, if there were any. + StickerItems []*StickerItem `json:"sticker_items"` + + // A poll object. + Poll *Poll `json:"poll"` +} + +// UnmarshalJSON is a helper function to unmarshal the Message. +func (m *Message) UnmarshalJSON(data []byte) error { + type message Message + var v struct { + message + RawComponents []unmarshalableMessageComponent `json:"components"` + } + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + *m = Message(v.message) + m.Components = make([]MessageComponent, len(v.RawComponents)) + for i, v := range v.RawComponents { + m.Components[i] = v.MessageComponent + } + return err +} + +// GetCustomEmojis pulls out all the custom (Non-unicode) emojis from a message and returns a Slice of the Emoji struct. +func (m *Message) GetCustomEmojis() []*Emoji { + var toReturn []*Emoji + emojis := EmojiRegex.FindAllString(m.Content, -1) + if len(emojis) < 1 { + return toReturn + } + for _, em := range emojis { + parts := strings.Split(em, ":") + toReturn = append(toReturn, &Emoji{ + ID: parts[2][:len(parts[2])-1], + Name: parts[1], + Animated: strings.HasPrefix(em, " mentions with the +// username of the mention. +func (m *Message) ContentWithMentionsReplaced() (content string) { + content = m.Content + + for _, user := range m.Mentions { + content = strings.NewReplacer( + "<@"+user.ID+">", "@"+user.Username, + "<@!"+user.ID+">", "@"+user.Username, + ).Replace(content) + } + return +} + +var patternChannels = regexp.MustCompile("<#[^>]*>") + +// ContentWithMoreMentionsReplaced will replace all @ mentions with the +// username of the mention, but also role IDs and more. +func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) { + content = m.Content + + if !s.StateEnabled { + content = m.ContentWithMentionsReplaced() + return + } + + channel, err := s.State.Channel(m.ChannelID) + if err != nil { + content = m.ContentWithMentionsReplaced() + return + } + + for _, user := range m.Mentions { + nick := user.Username + + member, err := s.State.Member(channel.GuildID, user.ID) + if err == nil && member.Nick != "" { + nick = member.Nick + } + + content = strings.NewReplacer( + "<@"+user.ID+">", "@"+user.Username, + "<@!"+user.ID+">", "@"+nick, + ).Replace(content) + } + for _, roleID := range m.MentionRoles { + role, err := s.State.Role(channel.GuildID, roleID) + if err != nil || !role.Mentionable { + continue + } + + content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1) + } + + content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string { + channel, err := s.State.Channel(mention[2 : len(mention)-1]) + if err != nil || channel.Type == ChannelTypeGuildVoice { + return mention + } + + return "#" + channel.Name + }) + return +} + +// MessageInteraction contains information about the application command interaction which generated the message. +type MessageInteraction struct { + ID string `json:"id"` + Type InteractionType `json:"type"` + Name string `json:"name"` + User *User `json:"user"` + + // Member is only present when the interaction is from a guild. + Member *Member `json:"member"` +} + +// MessageInteractionMetadata contains metadata of an interaction, including relevant user info. +type MessageInteractionMetadata struct { + // ID of the interaction. + ID string `json:"id"` + // Type of the interaction. + Type InteractionType `json:"type"` + // User who triggered the interaction. + User *User `json:"user"` + // IDs for installation context(s) related to an interaction. + AuthorizingIntegrationOwners map[ApplicationIntegrationType]string `json:"authorizing_integration_owners"` + // ID of the original response message. + // NOTE: present only on followup messages. + OriginalResponseMessageID string `json:"original_response_message_id,omitempty"` + // ID of the message that contained interactive component. + // NOTE: present only on message component interactions. + InteractedMessageID string `json:"interacted_message_id,omitempty"` + // Metadata for interaction that was used to open a modal. + // NOTE: present only on modal submit interactions. + TriggeringInteractionMetadata *MessageInteractionMetadata `json:"triggering_interaction_metadata,omitempty"` +} diff --git a/vendor/github.com/bwmarrin/discordgo/mkdocs.yml b/vendor/github.com/bwmarrin/discordgo/mkdocs.yml new file mode 100644 index 000000000..3ee8eb378 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/mkdocs.yml @@ -0,0 +1,17 @@ +site_name: DiscordGo +site_author: Bruce Marriner +site_url: http://bwmarrin.github.io/discordgo/ +repo_url: https://github.com/bwmarrin/discordgo + +dev_addr: 0.0.0.0:8000 +theme: yeti + +markdown_extensions: + - smarty + - toc: + permalink: True + - sane_lists + +pages: + - 'Home': 'index.md' + - 'Getting Started': 'GettingStarted.md' diff --git a/vendor/github.com/bwmarrin/discordgo/oauth2.go b/vendor/github.com/bwmarrin/discordgo/oauth2.go new file mode 100644 index 000000000..2fa2d8d54 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/oauth2.go @@ -0,0 +1,154 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains functions related to Discord OAuth2 endpoints + +package discordgo + +// ------------------------------------------------------------------------------------------------ +// Code specific to Discord OAuth2 Applications +// ------------------------------------------------------------------------------------------------ + +// The MembershipState represents whether the user is in the team or has been invited into it +type MembershipState int + +// Constants for the different stages of the MembershipState +const ( + MembershipStateInvited MembershipState = 1 + MembershipStateAccepted MembershipState = 2 +) + +// A TeamMember struct stores values for a single Team Member, extending the normal User data - note that the user field is partial +type TeamMember struct { + User *User `json:"user"` + TeamID string `json:"team_id"` + MembershipState MembershipState `json:"membership_state"` + Permissions []string `json:"permissions"` +} + +// A Team struct stores the members of a Discord Developer Team as well as some metadata about it +type Team struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Icon string `json:"icon"` + OwnerID string `json:"owner_user_id"` + Members []*TeamMember `json:"members"` +} + +// Application returns an Application structure of a specific Application +// appID : The ID of an Application +func (s *Session) Application(appID string) (st *Application, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointOAuth2Application(appID), nil, EndpointOAuth2Application("")) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// Applications returns all applications for the authenticated user +func (s *Session) Applications() (st []*Application, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointOAuth2Applications, nil, EndpointOAuth2Applications) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ApplicationCreate creates a new Application +// name : Name of Application / Bot +// uris : Redirect URIs (Not required) +func (s *Session) ApplicationCreate(ap *Application) (st *Application, err error) { + + data := struct { + Name string `json:"name"` + Description string `json:"description"` + }{ap.Name, ap.Description} + + body, err := s.RequestWithBucketID("POST", EndpointOAuth2Applications, data, EndpointOAuth2Applications) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ApplicationUpdate updates an existing Application +// var : desc +func (s *Session) ApplicationUpdate(appID string, ap *Application) (st *Application, err error) { + + data := struct { + Name string `json:"name"` + Description string `json:"description"` + }{ap.Name, ap.Description} + + body, err := s.RequestWithBucketID("PUT", EndpointOAuth2Application(appID), data, EndpointOAuth2Application("")) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ApplicationDelete deletes an existing Application +// appID : The ID of an Application +func (s *Session) ApplicationDelete(appID string) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointOAuth2Application(appID), nil, EndpointOAuth2Application("")) + if err != nil { + return + } + + return +} + +// Asset struct stores values for an asset of an application +type Asset struct { + Type int `json:"type"` + ID string `json:"id"` + Name string `json:"name"` +} + +// ApplicationAssets returns an application's assets +func (s *Session) ApplicationAssets(appID string) (ass []*Asset, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointOAuth2ApplicationAssets(appID), nil, EndpointOAuth2ApplicationAssets("")) + if err != nil { + return + } + + err = unmarshal(body, &ass) + return +} + +// ------------------------------------------------------------------------------------------------ +// Code specific to Discord OAuth2 Application Bots +// ------------------------------------------------------------------------------------------------ + +// ApplicationBotCreate creates an Application Bot Account +// +// appID : The ID of an Application +// +// NOTE: func name may change, if I can think up something better. +func (s *Session) ApplicationBotCreate(appID string) (st *User, err error) { + + body, err := s.RequestWithBucketID("POST", EndpointOAuth2ApplicationsBot(appID), nil, EndpointOAuth2ApplicationsBot("")) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} diff --git a/vendor/github.com/bwmarrin/discordgo/ratelimit.go b/vendor/github.com/bwmarrin/discordgo/ratelimit.go new file mode 100644 index 000000000..c992fd45e --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/ratelimit.go @@ -0,0 +1,197 @@ +package discordgo + +import ( + "math" + "net/http" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// customRateLimit holds information for defining a custom rate limit +type customRateLimit struct { + suffix string + requests int + reset time.Duration +} + +// RateLimiter holds all ratelimit buckets +type RateLimiter struct { + sync.Mutex + global *int64 + buckets map[string]*Bucket + globalRateLimit time.Duration + customRateLimits []*customRateLimit +} + +// NewRatelimiter returns a new RateLimiter +func NewRatelimiter() *RateLimiter { + + return &RateLimiter{ + buckets: make(map[string]*Bucket), + global: new(int64), + customRateLimits: []*customRateLimit{ + { + suffix: "//reactions//", + requests: 1, + reset: 200 * time.Millisecond, + }, + }, + } +} + +// GetBucket retrieves or creates a bucket +func (r *RateLimiter) GetBucket(key string) *Bucket { + r.Lock() + defer r.Unlock() + + if bucket, ok := r.buckets[key]; ok { + return bucket + } + + b := &Bucket{ + Remaining: 1, + Key: key, + global: r.global, + } + + // Check if there is a custom ratelimit set for this bucket ID. + for _, rl := range r.customRateLimits { + if strings.HasSuffix(b.Key, rl.suffix) { + b.customRateLimit = rl + break + } + } + + r.buckets[key] = b + return b +} + +// GetWaitTime returns the duration you should wait for a Bucket +func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { + // If we ran out of calls and the reset time is still ahead of us + // then we need to take it easy and relax a little + if b.Remaining < minRemaining && b.reset.After(time.Now()) { + return b.reset.Sub(time.Now()) + } + + // Check for global ratelimits + sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) + if now := time.Now(); now.Before(sleepTo) { + return sleepTo.Sub(now) + } + + return 0 +} + +// LockBucket Locks until a request can be made +func (r *RateLimiter) LockBucket(bucketID string) *Bucket { + return r.LockBucketObject(r.GetBucket(bucketID)) +} + +// LockBucketObject Locks an already resolved bucket until a request can be made +func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { + b.Lock() + + if wait := r.GetWaitTime(b, 1); wait > 0 { + time.Sleep(wait) + } + + b.Remaining-- + return b +} + +// Bucket represents a ratelimit bucket, each bucket gets ratelimited individually (-global ratelimits) +type Bucket struct { + sync.Mutex + Key string + Remaining int + limit int + reset time.Time + global *int64 + + lastReset time.Time + customRateLimit *customRateLimit + Userdata interface{} +} + +// Release unlocks the bucket and reads the headers to update the buckets ratelimit info +// and locks up the whole thing in case if there's a global ratelimit. +func (b *Bucket) Release(headers http.Header) error { + defer b.Unlock() + + // Check if the bucket uses a custom ratelimiter + if rl := b.customRateLimit; rl != nil { + if time.Now().Sub(b.lastReset) >= rl.reset { + b.Remaining = rl.requests - 1 + b.lastReset = time.Now() + } + if b.Remaining < 1 { + b.reset = time.Now().Add(rl.reset) + } + return nil + } + + if headers == nil { + return nil + } + + remaining := headers.Get("X-RateLimit-Remaining") + reset := headers.Get("X-RateLimit-Reset") + global := headers.Get("X-RateLimit-Global") + resetAfter := headers.Get("X-RateLimit-Reset-After") + + // Update global and per bucket reset time if the proper headers are available + // If global is set, then it will block all buckets until after Retry-After + // If Retry-After without global is provided it will use that for the new reset + // time since it's more accurate than X-RateLimit-Reset. + // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset + if resetAfter != "" { + parsedAfter, err := strconv.ParseFloat(resetAfter, 64) + if err != nil { + return err + } + + whole, frac := math.Modf(parsedAfter) + resetAt := time.Now().Add(time.Duration(whole) * time.Second).Add(time.Duration(frac*1000) * time.Millisecond) + + // Lock either this single bucket or all buckets + if global != "" { + atomic.StoreInt64(b.global, resetAt.UnixNano()) + } else { + b.reset = resetAt + } + } else if reset != "" { + // Calculate the reset time by using the date header returned from discord + discordTime, err := http.ParseTime(headers.Get("Date")) + if err != nil { + return err + } + + unix, err := strconv.ParseFloat(reset, 64) + if err != nil { + return err + } + + // Calculate the time until reset and add it to the current local time + // some extra time is added because without it i still encountered 429's. + // The added amount is the lowest amount that gave no 429's + // in 1k requests + whole, frac := math.Modf(unix) + delta := time.Unix(int64(whole), 0).Add(time.Duration(frac*1000)*time.Millisecond).Sub(discordTime) + time.Millisecond*250 + b.reset = time.Now().Add(delta) + } + + // Udpate remaining if header is present + if remaining != "" { + parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) + if err != nil { + return err + } + b.Remaining = int(parsedRemaining) + } + + return nil +} diff --git a/vendor/github.com/bwmarrin/discordgo/restapi.go b/vendor/github.com/bwmarrin/discordgo/restapi.go new file mode 100644 index 000000000..49ef78633 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/restapi.go @@ -0,0 +1,3707 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains functions for interacting with the Discord REST/JSON API +// at the lowest level. + +package discordgo + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "image" + _ "image/jpeg" // For JPEG decoding + _ "image/png" // For PNG decoding + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "context" +) + +// All error constants +var ( + ErrJSONUnmarshal = errors.New("json unmarshal") + ErrStatusOffline = errors.New("You can't set your Status to offline") + ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3") + ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1") + ErrGuildNoIcon = errors.New("guild does not have an icon set") + ErrGuildNoSplash = errors.New("guild does not have a splash set") + ErrUnauthorized = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header") +) + +var ( + // Marshal defines function used to encode JSON payloads + Marshal func(v interface{}) ([]byte, error) = json.Marshal + // Unmarshal defines function used to decode JSON payloads + Unmarshal func(src []byte, v interface{}) error = json.Unmarshal +) + +// RESTError stores error information about a request with a bad response code. +// Message is not always present, there are cases where api calls can fail +// without returning a json message. +type RESTError struct { + Request *http.Request + Response *http.Response + ResponseBody []byte + + Message *APIErrorMessage // Message may be nil. +} + +// newRestError returns a new REST API error. +func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError { + restErr := &RESTError{ + Request: req, + Response: resp, + ResponseBody: body, + } + + // Attempt to decode the error and assume no message was provided if it fails + var msg *APIErrorMessage + err := Unmarshal(body, &msg) + if err == nil { + restErr.Message = msg + } + + return restErr +} + +// Error returns a Rest API Error with its status code and body. +func (r RESTError) Error() string { + return "HTTP " + r.Response.Status + ", " + string(r.ResponseBody) +} + +// RateLimitError is returned when a request exceeds a rate limit +// and ShouldRetryOnRateLimit is false. The request may be manually +// retried after waiting the duration specified by RetryAfter. +type RateLimitError struct { + *RateLimit +} + +// Error returns a rate limit error with rate limited endpoint and retry time. +func (e RateLimitError) Error() string { + return "Rate limit exceeded on " + e.URL + ", retry after " + e.RetryAfter.String() +} + +// RequestConfig is an HTTP request configuration. +type RequestConfig struct { + Request *http.Request + ShouldRetryOnRateLimit bool + MaxRestRetries int + Client *http.Client +} + +// newRequestConfig returns a new HTTP request configuration based on parameters in Session. +func newRequestConfig(s *Session, req *http.Request) *RequestConfig { + return &RequestConfig{ + ShouldRetryOnRateLimit: s.ShouldRetryOnRateLimit, + MaxRestRetries: s.MaxRestRetries, + Client: s.Client, + Request: req, + } +} + +// RequestOption is a function which mutates request configuration. +// It can be supplied as an argument to any REST method. +type RequestOption func(cfg *RequestConfig) + +// WithClient changes the HTTP client used for the request. +func WithClient(client *http.Client) RequestOption { + return func(cfg *RequestConfig) { + if client != nil { + cfg.Client = client + } + } +} + +// WithRetryOnRatelimit controls whether session will retry the request on rate limit. +func WithRetryOnRatelimit(retry bool) RequestOption { + return func(cfg *RequestConfig) { + cfg.ShouldRetryOnRateLimit = retry + } +} + +// WithRestRetries changes maximum amount of retries if request fails. +func WithRestRetries(max int) RequestOption { + return func(cfg *RequestConfig) { + cfg.MaxRestRetries = max + } +} + +// WithHeader sets a header in the request. +func WithHeader(key, value string) RequestOption { + return func(cfg *RequestConfig) { + cfg.Request.Header.Set(key, value) + } +} + +// WithAuditLogReason changes audit log reason associated with the request. +func WithAuditLogReason(reason string) RequestOption { + return WithHeader("X-Audit-Log-Reason", reason) +} + +// WithLocale changes accepted locale of the request. +func WithLocale(locale Locale) RequestOption { + return WithHeader("X-Discord-Locale", string(locale)) +} + +// WithContext changes context of the request. +func WithContext(ctx context.Context) RequestOption { + return func(cfg *RequestConfig) { + cfg.Request = cfg.Request.WithContext(ctx) + } +} + +// Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr +func (s *Session) Request(method, urlStr string, data interface{}, options ...RequestOption) (response []byte, err error) { + return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0], options...) +} + +// RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data. +func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string, options ...RequestOption) (response []byte, err error) { + var body []byte + if data != nil { + body, err = Marshal(data) + if err != nil { + return + } + } + + return s.RequestRaw(method, urlStr, "application/json", body, bucketID, 0, options...) +} + +// RequestRaw makes a (GET/POST/...) Requests to Discord REST API. +// Preferably use the other Request* methods but this lets you send JSON directly if that's what you have. +// Sequence is the sequence number, if it fails with a 502 it will +// retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries +func (s *Session) RequestRaw(method, urlStr, contentType string, b []byte, bucketID string, sequence int, options ...RequestOption) (response []byte, err error) { + if bucketID == "" { + bucketID = strings.SplitN(urlStr, "?", 2)[0] + } + return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence, options...) +} + +// RequestWithLockedBucket makes a request using a bucket that's already been locked +func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int, options ...RequestOption) (response []byte, err error) { + if s.Debug { + log.Printf("API REQUEST %8s :: %s\n", method, urlStr) + log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b)) + } + + req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b)) + if err != nil { + bucket.Release(nil) + return + } + + // Not used on initial login.. + // TODO: Verify if a login, otherwise complain about no-token + if s.Token != "" { + req.Header.Set("authorization", s.Token) + } + + // Discord's API returns a 400 Bad Request is Content-Type is set, but the + // request body is empty. + if b != nil { + req.Header.Set("Content-Type", contentType) + } + + // TODO: Make a configurable static variable. + req.Header.Set("User-Agent", s.UserAgent) + + cfg := newRequestConfig(s, req) + for _, opt := range options { + opt(cfg) + } + req = cfg.Request + + if s.Debug { + for k, v := range req.Header { + log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v) + } + } + + resp, err := cfg.Client.Do(req) + if err != nil { + bucket.Release(nil) + return + } + defer func() { + err2 := resp.Body.Close() + if s.Debug && err2 != nil { + log.Println("error closing resp body") + } + }() + + err = bucket.Release(resp.Header) + if err != nil { + return + } + + response, err = ioutil.ReadAll(resp.Body) + if err != nil { + return + } + + if s.Debug { + + log.Printf("API RESPONSE STATUS :: %s\n", resp.Status) + for k, v := range resp.Header { + log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v) + } + log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response) + } + + switch resp.StatusCode { + case http.StatusOK: + case http.StatusCreated: + case http.StatusNoContent: + case http.StatusBadGateway: + // Retry sending request if possible + if sequence < cfg.MaxRestRetries { + + s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status) + response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1, options...) + } else { + err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response) + } + case 429: // TOO MANY REQUESTS - Rate limiting + rl := TooManyRequests{} + err = Unmarshal(response, &rl) + if err != nil { + s.log(LogError, "rate limit unmarshal error, %s", err) + return + } + + if cfg.ShouldRetryOnRateLimit { + s.log(LogInformational, "Rate Limiting %s, retry in %v", urlStr, rl.RetryAfter) + s.handleEvent(rateLimitEventType, &RateLimit{TooManyRequests: &rl, URL: urlStr}) + + time.Sleep(rl.RetryAfter) + // we can make the above smarter + // this method can cause longer delays than required + + response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence, options...) + } else { + err = &RateLimitError{&RateLimit{TooManyRequests: &rl, URL: urlStr}} + } + case http.StatusUnauthorized: + if strings.Index(s.Token, "Bot ") != 0 { + s.log(LogInformational, ErrUnauthorized.Error()) + err = ErrUnauthorized + } + fallthrough + default: // Error condition + err = newRestError(req, resp, response) + } + + return +} + +func unmarshal(data []byte, v interface{}) error { + err := Unmarshal(data, v) + if err != nil { + return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err) + } + + return nil +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Users +// ------------------------------------------------------------------------------------------------ + +// User returns the user details of the given userID +// userID : A user ID or "@me" which is a shortcut of current user ID +func (s *Session) User(userID string, options ...RequestOption) (st *User, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserAvatar is deprecated. Please use UserAvatarDecode +// userID : A user ID or "@me" which is a shortcut of current user ID +func (s *Session) UserAvatar(userID string, options ...RequestOption) (img image.Image, err error) { + u, err := s.User(userID, options...) + if err != nil { + return + } + img, err = s.UserAvatarDecode(u, options...) + return +} + +// UserAvatarDecode returns an image.Image of a user's Avatar +// user : The user which avatar should be retrieved +func (s *Session) UserAvatarDecode(u *User, options ...RequestOption) (img image.Image, err error) { + body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""), options...) + if err != nil { + return + } + + img, _, err = image.Decode(bytes.NewReader(body)) + return +} + +// UserUpdate updates current user settings. +func (s *Session) UserUpdate(username, avatar, banner string, options ...RequestOption) (st *User, err error) { + + // NOTE: Avatar must be either the hash/id of existing Avatar or + // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG + // to set a new avatar. + // If left blank, avatar will be set to null/blank + + data := struct { + Username string `json:"username,omitempty"` + Avatar string `json:"avatar,omitempty"` + Banner string `json:"banner,omitempty"` + }{username, avatar, banner} + + body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserConnections returns the user's connections +func (s *Session) UserConnections(options ...RequestOption) (conn []*UserConnection, err error) { + response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"), options...) + if err != nil { + return nil, err + } + + err = unmarshal(response, &conn) + if err != nil { + return + } + + return +} + +// UserChannelCreate creates a new User (Private) Channel with another User +// recipientID : A user ID for the user to which this channel is opened with. +func (s *Session) UserChannelCreate(recipientID string, options ...RequestOption) (st *Channel, err error) { + + data := struct { + RecipientID string `json:"recipient_id"` + }{recipientID} + + body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserGuildMember returns a guild member object for the current user in the given Guild. +// guildID : ID of the guild +func (s *Session) UserGuildMember(guildID string, options ...RequestOption) (st *Member, err error) { + body, err := s.RequestWithBucketID("GET", EndpointUserGuildMember("@me", guildID), nil, EndpointUserGuildMember("@me", guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserGuilds returns an array of UserGuild structures for all guilds. +// limit : The number guilds that can be returned. (max 200) +// beforeID : If provided all guilds returned will be before given ID. +// afterID : If provided all guilds returned will be after given ID. +// withCounts : Whether to include approximate member and presence counts or not. +func (s *Session) UserGuilds(limit int, beforeID, afterID string, withCounts bool, options ...RequestOption) (st []*UserGuild, err error) { + + v := url.Values{} + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + if afterID != "" { + v.Set("after", afterID) + } + if beforeID != "" { + v.Set("before", beforeID) + } + if withCounts { + v.Set("with_counts", "true") + } + + uri := EndpointUserGuilds("@me") + + if len(v) > 0 { + uri += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserChannelPermissions returns the permission of a user in a channel. +// userID : The ID of the user to calculate permissions for. +// channelID : The ID of the channel to calculate permission for. +// fetchOptions : Options used to fetch guild, member or channel if they are not present in state. +// +// NOTE: This function is now deprecated and will be removed in the future. +// Please see the same function inside state.go +func (s *Session) UserChannelPermissions(userID, channelID string, fetchOptions ...RequestOption) (apermissions int64, err error) { + // Try to just get permissions from state. + apermissions, err = s.State.UserChannelPermissions(userID, channelID) + if err == nil { + return + } + + // Otherwise try get as much data from state as possible, falling back to the network. + channel, err := s.State.Channel(channelID) + if err != nil || channel == nil { + channel, err = s.Channel(channelID, fetchOptions...) + if err != nil { + return + } + } + + guild, err := s.State.Guild(channel.GuildID) + if err != nil || guild == nil { + guild, err = s.Guild(channel.GuildID, fetchOptions...) + if err != nil { + return + } + } + + if userID == guild.OwnerID { + apermissions = PermissionAll + return + } + + member, err := s.State.Member(guild.ID, userID) + if err != nil || member == nil { + member, err = s.GuildMember(guild.ID, userID, fetchOptions...) + if err != nil { + return + } + } + + return memberPermissions(guild, channel, userID, member.Roles), nil +} + +// Calculates the permissions for a member. +// https://support.discord.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured- +func memberPermissions(guild *Guild, channel *Channel, userID string, roles []string) (apermissions int64) { + if userID == guild.OwnerID { + apermissions = PermissionAll + return + } + + for _, role := range guild.Roles { + if role.ID == guild.ID { + apermissions |= role.Permissions + break + } + } + + for _, role := range guild.Roles { + for _, roleID := range roles { + if role.ID == roleID { + apermissions |= role.Permissions + break + } + } + } + + if apermissions&PermissionAdministrator == PermissionAdministrator { + apermissions |= PermissionAll + } + + // Apply @everyone overrides from the channel. + for _, overwrite := range channel.PermissionOverwrites { + if guild.ID == overwrite.ID { + apermissions &= ^overwrite.Deny + apermissions |= overwrite.Allow + break + } + } + + var denies, allows int64 + // Member overwrites can override role overrides, so do two passes + for _, overwrite := range channel.PermissionOverwrites { + for _, roleID := range roles { + if overwrite.Type == PermissionOverwriteTypeRole && roleID == overwrite.ID { + denies |= overwrite.Deny + allows |= overwrite.Allow + break + } + } + } + + apermissions &= ^denies + apermissions |= allows + + for _, overwrite := range channel.PermissionOverwrites { + if overwrite.Type == PermissionOverwriteTypeMember && overwrite.ID == userID { + apermissions &= ^overwrite.Deny + apermissions |= overwrite.Allow + break + } + } + + if apermissions&PermissionAdministrator == PermissionAdministrator { + apermissions |= PermissionAllChannel + } + + return apermissions +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Guilds +// ------------------------------------------------------------------------------------------------ + +// Guild returns a Guild structure of a specific Guild. +// guildID : The ID of a Guild +func (s *Session) Guild(guildID string, options ...RequestOption) (st *Guild, err error) { + body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildWithCounts returns a Guild structure of a specific Guild with approximate member and presence counts. +// guildID : The ID of a Guild +func (s *Session) GuildWithCounts(guildID string, options ...RequestOption) (st *Guild, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID)+"?with_counts=true", nil, EndpointGuild(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildPreview returns a GuildPreview structure of a specific public Guild. +// guildID : The ID of a Guild +func (s *Session) GuildPreview(guildID string, options ...RequestOption) (st *GuildPreview, err error) { + body, err := s.RequestWithBucketID("GET", EndpointGuildPreview(guildID), nil, EndpointGuildPreview(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildCreate creates a new Guild +// name : A name for the Guild (2-100 characters) +func (s *Session) GuildCreate(name string, options ...RequestOption) (st *Guild, err error) { + + data := struct { + Name string `json:"name"` + }{name} + + body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildEdit edits a new Guild +// guildID : The ID of a Guild +// g : A GuildParams struct with the values Name, Region and VerificationLevel defined. +func (s *Session) GuildEdit(guildID string, g *GuildParams, options ...RequestOption) (st *Guild, err error) { + + // Bounds checking for VerificationLevel, interval: [0, 4] + if g.VerificationLevel != nil { + val := *g.VerificationLevel + if val < 0 || val > 4 { + err = ErrVerificationLevelBounds + return + } + } + + // Bounds checking for regions + if g.Region != "" { + isValid := false + regions, _ := s.VoiceRegions(options...) + for _, r := range regions { + if g.Region == r.ID { + isValid = true + } + } + if !isValid { + var valid []string + for _, r := range regions { + valid = append(valid, r.ID) + } + err = fmt.Errorf("Region not a valid region (%q)", valid) + return + } + } + + body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildDelete deletes a Guild. +// guildID : The ID of a Guild +func (s *Session) GuildDelete(guildID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...) + return +} + +// GuildLeave leaves a Guild. +// guildID : The ID of a Guild +func (s *Session) GuildLeave(guildID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID), options...) + return +} + +// GuildBans returns an array of GuildBan structures for bans in the given guild. +// guildID : The ID of a Guild +// limit : Max number of bans to return (max 1000) +// beforeID : If not empty all returned users will be after the given id +// afterID : If not empty all returned users will be before the given id +func (s *Session) GuildBans(guildID string, limit int, beforeID, afterID string, options ...RequestOption) (st []*GuildBan, err error) { + uri := EndpointGuildBans(guildID) + + v := url.Values{} + if limit != 0 { + v.Set("limit", strconv.Itoa(limit)) + } + if beforeID != "" { + v.Set("before", beforeID) + } + if afterID != "" { + v.Set("after", afterID) + } + + if len(v) > 0 { + uri += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildBans(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildBanCreate bans the given user from the given guild. +// guildID : The ID of a Guild. +// userID : The ID of a User +// days : The number of days of previous comments to delete. +func (s *Session) GuildBanCreate(guildID, userID string, days int, options ...RequestOption) (err error) { + return s.GuildBanCreateWithReason(guildID, userID, "", days, options...) +} + +// GuildBan finds ban by given guild and user id and returns GuildBan structure +func (s *Session) GuildBan(guildID, userID string, options ...RequestOption) (st *GuildBan, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, userID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildBanCreateWithReason bans the given user from the given guild also providing a reaso. +// guildID : The ID of a Guild. +// userID : The ID of a User +// reason : The reason for this ban +// days : The number of days of previous comments to delete. +func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int, options ...RequestOption) (err error) { + + uri := EndpointGuildBan(guildID, userID) + + queryParams := url.Values{} + if days > 0 { + queryParams.Set("delete_message_days", strconv.Itoa(days)) + } + if reason != "" { + queryParams.Set("reason", reason) + } + + if len(queryParams) > 0 { + uri += "?" + queryParams.Encode() + } + + _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""), options...) + return +} + +// GuildBanDelete removes the given user from the guild bans +// guildID : The ID of a Guild. +// userID : The ID of a User +func (s *Session) GuildBanDelete(guildID, userID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""), options...) + return +} + +// GuildMembers returns a list of members for a guild. +// guildID : The ID of a Guild. +// after : The id of the member to return members after +// limit : max number of members to return (max 1000) +func (s *Session) GuildMembers(guildID string, after string, limit int, options ...RequestOption) (st []*Member, err error) { + + uri := EndpointGuildMembers(guildID) + + v := url.Values{} + + if after != "" { + v.Set("after", after) + } + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + + if len(v) > 0 { + uri += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildMembersSearch returns a list of guild member objects whose username or nickname starts with a provided string +// guildID : The ID of a Guild +// query : Query string to match username(s) and nickname(s) against +// limit : Max number of members to return (default 1, min 1, max 1000) +func (s *Session) GuildMembersSearch(guildID, query string, limit int, options ...RequestOption) (st []*Member, err error) { + + uri := EndpointGuildMembersSearch(guildID) + + queryParams := url.Values{} + queryParams.Set("query", query) + if limit > 1 { + queryParams.Set("limit", strconv.Itoa(limit)) + } + + body, err := s.RequestWithBucketID("GET", uri+"?"+queryParams.Encode(), nil, uri, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildMember returns a member of a guild. +// guildID : The ID of a Guild. +// userID : The ID of a User +func (s *Session) GuildMember(guildID, userID string, options ...RequestOption) (st *Member, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + // The returned object doesn't have the GuildID attribute so we will set it here. + st.GuildID = guildID + return +} + +// GuildMemberAdd force joins a user to the guild. +// guildID : The ID of a Guild. +// userID : The ID of a User. +// data : Parameters of the user to add. +func (s *Session) GuildMemberAdd(guildID, userID string, data *GuildMemberAddParams, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + if err != nil { + return err + } + + return err +} + +// GuildMemberDelete removes the given user from the given guild. +// guildID : The ID of a Guild. +// userID : The ID of a User +func (s *Session) GuildMemberDelete(guildID, userID string, options ...RequestOption) (err error) { + + return s.GuildMemberDeleteWithReason(guildID, userID, "", options...) +} + +// GuildMemberDeleteWithReason removes the given user from the given guild. +// guildID : The ID of a Guild. +// userID : The ID of a User +// reason : The reason for the kick +func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string, options ...RequestOption) (err error) { + + uri := EndpointGuildMember(guildID, userID) + if reason != "" { + uri += "?reason=" + url.QueryEscape(reason) + } + + _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberEdit edits and returns updated member. +// guildID : The ID of a Guild. +// userID : The ID of a User. +// data : Updated GuildMember data. +func (s *Session) GuildMemberEdit(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) { + var body []byte + body, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + if err != nil { + return nil, err + } + + err = unmarshal(body, &st) + return +} + +// GuildMemberEditComplex edits the nickname and roles of a member. +// NOTE: deprecated, use GuildMemberEdit instead. +// +// guildID : The ID of a Guild. +// userID : The ID of a User. +// data : A GuildMemberEditData struct with the new nickname and roles +func (s *Session) GuildMemberEditComplex(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) { + return s.GuildMemberEdit(guildID, userID, data, options...) +} + +// GuildMemberMove moves a guild member from one voice channel to another/none +// guildID : The ID of a Guild. +// userID : The ID of a User. +// channelID : The ID of a channel to move user to or nil to remove from voice channel +// +// NOTE : I am not entirely set on the name of this function and it may change +// prior to the final 1.0.0 release of Discordgo +func (s *Session) GuildMemberMove(guildID string, userID string, channelID *string, options ...RequestOption) (err error) { + data := struct { + ChannelID *string `json:"channel_id"` + }{channelID} + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberNickname updates the nickname of a guild member +// guildID : The ID of a guild +// userID : The ID of a user +// userID : The ID of a user or "@me" which is a shortcut of the current user ID +// nickname : The nickname of the member, "" will reset their nickname +func (s *Session) GuildMemberNickname(guildID, userID, nickname string, options ...RequestOption) (err error) { + + data := struct { + Nick string `json:"nick"` + }{nickname} + + if userID == "@me" { + userID += "/nick" + } + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberMute server mutes a guild member +// guildID : The ID of a Guild. +// userID : The ID of a User. +// mute : boolean value for if the user should be muted +func (s *Session) GuildMemberMute(guildID string, userID string, mute bool, options ...RequestOption) (err error) { + data := struct { + Mute bool `json:"mute"` + }{mute} + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberTimeout times out a guild member +// guildID : The ID of a Guild. +// userID : The ID of a User. +// until : The timestamp for how long a member should be timed out. Set to nil to remove timeout. +func (s *Session) GuildMemberTimeout(guildID string, userID string, until *time.Time, options ...RequestOption) (err error) { + data := struct { + CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"` + }{until} + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberDeafen server deafens a guild member +// guildID : The ID of a Guild. +// userID : The ID of a User. +// deaf : boolean value for if the user should be deafened +func (s *Session) GuildMemberDeafen(guildID string, userID string, deaf bool, options ...RequestOption) (err error) { + data := struct { + Deaf bool `json:"deaf"` + }{deaf} + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) + return +} + +// GuildMemberRoleAdd adds the specified role to a given member +// guildID : The ID of a Guild. +// userID : The ID of a User. +// roleID : The ID of a Role to be assigned to the user. +func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""), options...) + + return +} + +// GuildMemberRoleRemove removes the specified role to a given member +// guildID : The ID of a Guild. +// userID : The ID of a User. +// roleID : The ID of a Role to be removed from the user. +func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""), options...) + + return +} + +// GuildChannels returns an array of Channel structures for all channels of a +// given guild. +// guildID : The ID of a Guild. +func (s *Session) GuildChannels(guildID string, options ...RequestOption) (st []*Channel, err error) { + + body, err := s.RequestRaw("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildChannelCreateData is provided to GuildChannelCreateComplex +type GuildChannelCreateData struct { + Name string `json:"name"` + Type ChannelType `json:"type"` + Topic string `json:"topic,omitempty"` + Bitrate int `json:"bitrate,omitempty"` + UserLimit int `json:"user_limit,omitempty"` + RateLimitPerUser int `json:"rate_limit_per_user,omitempty"` + Position int `json:"position,omitempty"` + PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"` + ParentID string `json:"parent_id,omitempty"` + NSFW bool `json:"nsfw,omitempty"` +} + +// GuildChannelCreateComplex creates a new channel in the given guild +// guildID : The ID of a Guild +// data : A data struct describing the new Channel, Name and Type are mandatory, other fields depending on the type +func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData, options ...RequestOption) (st *Channel, err error) { + body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildChannelCreate creates a new channel in the given guild +// guildID : The ID of a Guild. +// name : Name of the channel (2-100 chars length) +// ctype : Type of the channel +func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType, options ...RequestOption) (st *Channel, err error) { + return s.GuildChannelCreateComplex(guildID, GuildChannelCreateData{ + Name: name, + Type: ctype, + }, options...) +} + +// GuildChannelsReorder updates the order of channels in a guild +// guildID : The ID of a Guild. +// channels : Updated channels. +func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel, options ...RequestOption) (err error) { + + data := make([]struct { + ID string `json:"id"` + Position int `json:"position"` + }, len(channels)) + + for i, c := range channels { + data[i].ID = c.ID + data[i].Position = c.Position + } + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID), options...) + return +} + +// GuildInvites returns an array of Invite structures for the given guild +// guildID : The ID of a Guild. +func (s *Session) GuildInvites(guildID string, options ...RequestOption) (st []*Invite, err error) { + body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildRoles returns all roles for a given guild. +// guildID : The ID of a Guild. +func (s *Session) GuildRoles(guildID string, options ...RequestOption) (st []*Role, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return // TODO return pointer +} + +// GuildRoleCreate creates a new Guild Role and returns it. +// guildID : The ID of a Guild. +// data : New Role parameters. +func (s *Session) GuildRoleCreate(guildID string, data *RoleParams, options ...RequestOption) (st *Role, err error) { + body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), data, EndpointGuildRoles(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildRoleEdit updates an existing Guild Role and returns updated Role data. +// guildID : The ID of a Guild. +// roleID : The ID of a Role. +// data : Updated Role data. +func (s *Session) GuildRoleEdit(guildID, roleID string, data *RoleParams, options ...RequestOption) (st *Role, err error) { + + // Prevent sending a color int that is too big. + if data.Color != nil && *data.Color > 0xFFFFFF { + return nil, fmt.Errorf("color value cannot be larger than 0xFFFFFF") + } + + body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildRoleReorder reoders guild roles +// guildID : The ID of a Guild. +// roles : A list of ordered roles. +func (s *Session) GuildRoleReorder(guildID string, roles []*Role, options ...RequestOption) (st []*Role, err error) { + + body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildRoleDelete deletes an existing role. +// guildID : The ID of a Guild. +// roleID : The ID of a Role. +func (s *Session) GuildRoleDelete(guildID, roleID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""), options...) + + return +} + +// GuildPruneCount Returns the number of members that would be removed in a prune operation. +// Requires 'KICK_MEMBER' permission. +// guildID : The ID of a Guild. +// days : The number of days to count prune for (1 or more). +func (s *Session) GuildPruneCount(guildID string, days uint32, options ...RequestOption) (count uint32, err error) { + count = 0 + + if days <= 0 { + err = ErrPruneDaysBounds + return + } + + p := struct { + Pruned uint32 `json:"pruned"` + }{} + + uri := EndpointGuildPrune(guildID) + "?days=" + strconv.FormatUint(uint64(days), 10) + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &p) + if err != nil { + return + } + + count = p.Pruned + + return +} + +// GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission. +// Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation. +// guildID : The ID of a Guild. +// days : The number of days to count prune for (1 or more). +func (s *Session) GuildPrune(guildID string, days uint32, options ...RequestOption) (count uint32, err error) { + + count = 0 + + if days <= 0 { + err = ErrPruneDaysBounds + return + } + + data := struct { + days uint32 + }{days} + + p := struct { + Pruned uint32 `json:"pruned"` + }{} + + body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &p) + if err != nil { + return + } + + count = p.Pruned + + return +} + +// GuildIntegrations returns an array of Integrations for a guild. +// guildID : The ID of a Guild. +func (s *Session) GuildIntegrations(guildID string, options ...RequestOption) (st []*Integration, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildIntegrationCreate creates a Guild Integration. +// guildID : The ID of a Guild. +// integrationType : The Integration type. +// integrationID : The ID of an integration. +func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string, options ...RequestOption) (err error) { + + data := struct { + Type string `json:"type"` + ID string `json:"id"` + }{integrationType, integrationID} + + _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID), options...) + return +} + +// GuildIntegrationEdit edits a Guild Integration. +// guildID : The ID of a Guild. +// integrationType : The Integration type. +// integrationID : The ID of an integration. +// expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation). +// expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions. +// enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently). +func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool, options ...RequestOption) (err error) { + + data := struct { + ExpireBehavior int `json:"expire_behavior"` + ExpireGracePeriod int `json:"expire_grace_period"` + EnableEmoticons bool `json:"enable_emoticons"` + }{expireBehavior, expireGracePeriod, enableEmoticons} + + _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""), options...) + return +} + +// GuildIntegrationDelete removes the given integration from the Guild. +// guildID : The ID of a Guild. +// integrationID : The ID of an integration. +func (s *Session) GuildIntegrationDelete(guildID, integrationID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""), options...) + return +} + +// GuildIcon returns an image.Image of a guild icon. +// guildID : The ID of a Guild. +func (s *Session) GuildIcon(guildID string, options ...RequestOption) (img image.Image, err error) { + g, err := s.Guild(guildID, options...) + if err != nil { + return + } + + if g.Icon == "" { + err = ErrGuildNoIcon + return + } + + body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""), options...) + if err != nil { + return + } + + img, _, err = image.Decode(bytes.NewReader(body)) + return +} + +// GuildSplash returns an image.Image of a guild splash image. +// guildID : The ID of a Guild. +func (s *Session) GuildSplash(guildID string, options ...RequestOption) (img image.Image, err error) { + g, err := s.Guild(guildID, options...) + if err != nil { + return + } + + if g.Splash == "" { + err = ErrGuildNoSplash + return + } + + body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""), options...) + if err != nil { + return + } + + img, _, err = image.Decode(bytes.NewReader(body)) + return +} + +// GuildEmbed returns the embed for a Guild. +// guildID : The ID of a Guild. +func (s *Session) GuildEmbed(guildID string, options ...RequestOption) (st *GuildEmbed, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildEmbedEdit edits the embed of a Guild. +// guildID : The ID of a Guild. +// data : New GuildEmbed data. +func (s *Session) GuildEmbedEdit(guildID string, data *GuildEmbed, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID), options...) + return +} + +// GuildAuditLog returns the audit log for a Guild. +// guildID : The ID of a Guild. +// userID : If provided the log will be filtered for the given ID. +// beforeID : If provided all log entries returned will be before the given ID. +// actionType : If provided the log will be filtered for the given Action Type. +// limit : The number messages that can be returned. (default 50, min 1, max 100) +func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int, options ...RequestOption) (st *GuildAuditLog, err error) { + + uri := EndpointGuildAuditLogs(guildID) + + v := url.Values{} + if userID != "" { + v.Set("user_id", userID) + } + if beforeID != "" { + v.Set("before", beforeID) + } + if actionType > 0 { + v.Set("action_type", strconv.Itoa(actionType)) + } + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + if len(v) > 0 { + uri = fmt.Sprintf("%s?%s", uri, v.Encode()) + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildEmojis returns all emoji +// guildID : The ID of a Guild. +func (s *Session) GuildEmojis(guildID string, options ...RequestOption) (emoji []*Emoji, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildEmojis(guildID), nil, EndpointGuildEmojis(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// GuildEmoji returns specified emoji. +// guildID : The ID of a Guild +// emojiID : The ID of an Emoji to retrieve +func (s *Session) GuildEmoji(guildID, emojiID string, options ...RequestOption) (emoji *Emoji, err error) { + var body []byte + body, err = s.RequestWithBucketID("GET", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmoji(guildID, emojiID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// GuildEmojiCreate creates a new Emoji. +// guildID : The ID of a Guild. +// data : New Emoji data. +func (s *Session) GuildEmojiCreate(guildID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { + body, err := s.RequestWithBucketID("POST", EndpointGuildEmojis(guildID), data, EndpointGuildEmojis(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// GuildEmojiEdit modifies and returns updated Emoji. +// guildID : The ID of a Guild. +// emojiID : The ID of an Emoji. +// data : Updated Emoji data. +func (s *Session) GuildEmojiEdit(guildID, emojiID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { + body, err := s.RequestWithBucketID("PATCH", EndpointGuildEmoji(guildID, emojiID), data, EndpointGuildEmojis(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// GuildEmojiDelete deletes an Emoji. +// guildID : The ID of a Guild. +// emojiID : The ID of an Emoji. +func (s *Session) GuildEmojiDelete(guildID, emojiID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmojis(guildID), options...) + return +} + +// ApplicationEmojis returns all emojis for the given application +// appID : ID of the application +func (s *Session) ApplicationEmojis(appID string, options ...RequestOption) (emojis []*Emoji, err error) { + body, err := s.RequestWithBucketID("GET", EndpointApplicationEmojis(appID), nil, EndpointApplicationEmojis(appID), options...) + if err != nil { + return + } + + var temp struct { + Items []*Emoji `json:"items"` + } + + err = unmarshal(body, &temp) + if err != nil { + return + } + + emojis = temp.Items + return +} + +// ApplicationEmoji returns the emoji for the given application. +// appID : ID of the application +// emojiID : ID of an Emoji to retrieve +func (s *Session) ApplicationEmoji(appID, emojiID string, options ...RequestOption) (emoji *Emoji, err error) { + var body []byte + body, err = s.RequestWithBucketID("GET", EndpointApplicationEmoji(appID, emojiID), nil, EndpointApplicationEmoji(appID, emojiID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// ApplicationEmojiCreate creates a new Emoji for the given application. +// appID : ID of the application +// data : New Emoji data +func (s *Session) ApplicationEmojiCreate(appID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { + body, err := s.RequestWithBucketID("POST", EndpointApplicationEmojis(appID), data, EndpointApplicationEmojis(appID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// ApplicationEmojiEdit modifies and returns updated Emoji for the given application. +// appID : ID of the application +// emojiID : ID of an Emoji +// data : Updated Emoji data +func (s *Session) ApplicationEmojiEdit(appID string, emojiID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { + body, err := s.RequestWithBucketID("PATCH", EndpointApplicationEmoji(appID, emojiID), data, EndpointApplicationEmojis(appID), options...) + if err != nil { + return + } + + err = unmarshal(body, &emoji) + return +} + +// ApplicationEmojiDelete deletes an Emoji for the given application. +// appID : ID of the application +// emojiID : ID of an Emoji +func (s *Session) ApplicationEmojiDelete(appID, emojiID string, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("DELETE", EndpointApplicationEmoji(appID, emojiID), nil, EndpointApplicationEmojis(appID), options...) + return +} + +// GuildTemplate returns a GuildTemplate for the given code +// templateCode: The Code of a GuildTemplate +func (s *Session) GuildTemplate(templateCode string, options ...RequestOption) (st *GuildTemplate, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildTemplate(templateCode), nil, EndpointGuildTemplate(templateCode), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildCreateWithTemplate creates a guild based on a GuildTemplate +// templateCode: The Code of a GuildTemplate +// name: The name of the guild (2-100) characters +// icon: base64 encoded 128x128 image for the guild icon +func (s *Session) GuildCreateWithTemplate(templateCode, name, icon string, options ...RequestOption) (st *Guild, err error) { + + data := struct { + Name string `json:"name"` + Icon string `json:"icon"` + }{name, icon} + + body, err := s.RequestWithBucketID("POST", EndpointGuildTemplate(templateCode), data, EndpointGuildTemplate(templateCode), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildTemplates returns all of GuildTemplates +// guildID: The ID of the guild +func (s *Session) GuildTemplates(guildID string, options ...RequestOption) (st []*GuildTemplate, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildTemplates(guildID), nil, EndpointGuildTemplates(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildTemplateCreate creates a template for the guild +// guildID : The ID of the guild +// data : Template metadata +func (s *Session) GuildTemplateCreate(guildID string, data *GuildTemplateParams, options ...RequestOption) (st *GuildTemplate) { + body, err := s.RequestWithBucketID("POST", EndpointGuildTemplates(guildID), data, EndpointGuildTemplates(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildTemplateSync syncs the template to the guild's current state +// guildID: The ID of the guild +// templateCode: The code of the template +func (s *Session) GuildTemplateSync(guildID, templateCode string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("PUT", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""), options...) + return +} + +// GuildTemplateEdit modifies the template's metadata +// guildID : The ID of the guild +// templateCode : The code of the template +// data : New template metadata +func (s *Session) GuildTemplateEdit(guildID, templateCode string, data *GuildTemplateParams, options ...RequestOption) (st *GuildTemplate, err error) { + + body, err := s.RequestWithBucketID("PATCH", EndpointGuildTemplateSync(guildID, templateCode), data, EndpointGuildTemplateSync(guildID, ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildTemplateDelete deletes the template +// guildID: The ID of the guild +// templateCode: The code of the template +func (s *Session) GuildTemplateDelete(guildID, templateCode string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""), options...) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Channels +// ------------------------------------------------------------------------------------------------ + +// Channel returns a Channel structure of a specific Channel. +// channelID : The ID of the Channel you want returned. +func (s *Session) Channel(channelID string, options ...RequestOption) (st *Channel, err error) { + body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelEdit edits the given channel and returns the updated Channel data. +// channelID : The ID of a Channel. +// data : New Channel data. +func (s *Session) ChannelEdit(channelID string, data *ChannelEdit, options ...RequestOption) (st *Channel, err error) { + body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return + +} + +// ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct +// NOTE: deprecated, use ChannelEdit instead +// channelID : The ID of a Channel +// data : The channel struct to send +func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit, options ...RequestOption) (st *Channel, err error) { + return s.ChannelEdit(channelID, data, options...) +} + +// ChannelDelete deletes the given channel +// channelID : The ID of a Channel +func (s *Session) ChannelDelete(channelID string, options ...RequestOption) (st *Channel, err error) { + + body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelTyping broadcasts to all members that authenticated user is typing in +// the given channel. +// channelID : The ID of a Channel +func (s *Session) ChannelTyping(channelID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID), options...) + return +} + +// ChannelMessages returns an array of Message structures for messages within +// a given channel. +// channelID : The ID of a Channel. +// limit : The number messages that can be returned. (max 100) +// beforeID : If provided all messages returned will be before given ID. +// afterID : If provided all messages returned will be after given ID. +// aroundID : If provided all messages returned will be around given ID. +func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string, options ...RequestOption) (st []*Message, err error) { + + uri := EndpointChannelMessages(channelID) + + v := url.Values{} + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + if afterID != "" { + v.Set("after", afterID) + } + if beforeID != "" { + v.Set("before", beforeID) + } + if aroundID != "" { + v.Set("around", aroundID) + } + if len(v) > 0 { + uri += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelMessage gets a single message by ID from a given channel. +// channeld : The ID of a Channel +// messageID : the ID of a Message +func (s *Session) ChannelMessage(channelID, messageID string, options ...RequestOption) (st *Message, err error) { + + response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""), options...) + if err != nil { + return + } + + err = unmarshal(response, &st) + return +} + +// ChannelMessageSend sends a message to the given channel. +// channelID : The ID of a Channel. +// content : The message to send. +func (s *Session) ChannelMessageSend(channelID string, content string, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendComplex(channelID, &MessageSend{ + Content: content, + }, options...) +} + +var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") + +// ChannelMessageSendComplex sends a message to the given channel. +// channelID : The ID of a Channel. +// data : The message struct to send. +func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend, options ...RequestOption) (st *Message, err error) { + // TODO: Remove this when compatibility is not required. + if data.Embed != nil { + if data.Embeds == nil { + data.Embeds = []*MessageEmbed{data.Embed} + } else { + err = fmt.Errorf("cannot specify both Embed and Embeds") + return + } + } + + for _, embed := range data.Embeds { + if embed.Type == "" { + embed.Type = "rich" + } + } + endpoint := EndpointChannelMessages(channelID) + + // TODO: Remove this when compatibility is not required. + files := data.Files + if data.File != nil { + if files == nil { + files = []*File{data.File} + } else { + err = fmt.Errorf("cannot specify both File and Files") + return + } + } + + if data.StickerIDs != nil { + if len(data.StickerIDs) > 3 { + err = fmt.Errorf("cannot send more than 3 stickers") + return + } + } + + var response []byte + if len(files) > 0 { + contentType, body, encodeErr := MultipartBodyWithJSON(data, files) + if encodeErr != nil { + return st, encodeErr + } + response, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) + } else { + response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + } + if err != nil { + return + } + + err = unmarshal(response, &st) + return +} + +// ChannelMessageSendTTS sends a message to the given channel with Text to Speech. +// channelID : The ID of a Channel. +// content : The message to send. +func (s *Session) ChannelMessageSendTTS(channelID string, content string, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendComplex(channelID, &MessageSend{ + Content: content, + TTS: true, + }, options...) +} + +// ChannelMessageSendEmbed sends a message to the given channel with embedded data. +// channelID : The ID of a Channel. +// embed : The embed data to send. +func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendEmbeds(channelID, []*MessageEmbed{embed}, options...) +} + +// ChannelMessageSendEmbeds sends a message to the given channel with multiple embedded data. +// channelID : The ID of a Channel. +// embeds : The embeds data to send. +func (s *Session) ChannelMessageSendEmbeds(channelID string, embeds []*MessageEmbed, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendComplex(channelID, &MessageSend{ + Embeds: embeds, + }, options...) +} + +// ChannelMessageSendReply sends a message to the given channel with reference data. +// channelID : The ID of a Channel. +// content : The message to send. +// reference : The message reference to send. +func (s *Session) ChannelMessageSendReply(channelID string, content string, reference *MessageReference, options ...RequestOption) (*Message, error) { + if reference == nil { + return nil, fmt.Errorf("reply attempted with nil message reference") + } + return s.ChannelMessageSendComplex(channelID, &MessageSend{ + Content: content, + Reference: reference, + }, options...) +} + +// ChannelMessageSendEmbedReply sends a message to the given channel with reference data and embedded data. +// channelID : The ID of a Channel. +// embed : The embed data to send. +// reference : The message reference to send. +func (s *Session) ChannelMessageSendEmbedReply(channelID string, embed *MessageEmbed, reference *MessageReference, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendEmbedsReply(channelID, []*MessageEmbed{embed}, reference, options...) +} + +// ChannelMessageSendEmbedsReply sends a message to the given channel with reference data and multiple embedded data. +// channelID : The ID of a Channel. +// embeds : The embeds data to send. +// reference : The message reference to send. +func (s *Session) ChannelMessageSendEmbedsReply(channelID string, embeds []*MessageEmbed, reference *MessageReference, options ...RequestOption) (*Message, error) { + if reference == nil { + return nil, fmt.Errorf("reply attempted with nil message reference") + } + return s.ChannelMessageSendComplex(channelID, &MessageSend{ + Embeds: embeds, + Reference: reference, + }, options...) +} + +// ChannelMessageEdit edits an existing message, replacing it entirely with +// the given content. +// channelID : The ID of a Channel +// messageID : The ID of a Message +// content : The contents of the message +func (s *Session) ChannelMessageEdit(channelID, messageID, content string, options ...RequestOption) (*Message, error) { + return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content), options...) +} + +// ChannelMessageEditComplex edits an existing message, replacing it entirely with +// the given MessageEdit struct +func (s *Session) ChannelMessageEditComplex(m *MessageEdit, options ...RequestOption) (st *Message, err error) { + // TODO: Remove this when compatibility is not required. + if m.Embed != nil { + if m.Embeds == nil { + m.Embeds = &[]*MessageEmbed{m.Embed} + } else { + err = fmt.Errorf("cannot specify both Embed and Embeds") + return + } + } + + if m.Embeds != nil { + for _, embed := range *m.Embeds { + if embed.Type == "" { + embed.Type = "rich" + } + } + } + + endpoint := EndpointChannelMessage(m.Channel, m.ID) + + var response []byte + if len(m.Files) > 0 { + contentType, body, encodeErr := MultipartBodyWithJSON(m, m.Files) + if encodeErr != nil { + return st, encodeErr + } + response, err = s.RequestRaw("PATCH", endpoint, contentType, body, EndpointChannelMessage(m.Channel, ""), 0, options...) + } else { + response, err = s.RequestWithBucketID("PATCH", endpoint, m, EndpointChannelMessage(m.Channel, ""), options...) + } + if err != nil { + return + } + + err = unmarshal(response, &st) + return +} + +// ChannelMessageEditEmbed edits an existing message with embedded data. +// channelID : The ID of a Channel +// messageID : The ID of a Message +// embed : The embed data to send +func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed, options ...RequestOption) (*Message, error) { + return s.ChannelMessageEditEmbeds(channelID, messageID, []*MessageEmbed{embed}, options...) +} + +// ChannelMessageEditEmbeds edits an existing message with multiple embedded data. +// channelID : The ID of a Channel +// messageID : The ID of a Message +// embeds : The embeds data to send +func (s *Session) ChannelMessageEditEmbeds(channelID, messageID string, embeds []*MessageEmbed, options ...RequestOption) (*Message, error) { + return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbeds(embeds), options...) +} + +// ChannelMessageDelete deletes a message from the Channel. +func (s *Session) ChannelMessageDelete(channelID, messageID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""), options...) + return +} + +// ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs. +// If only one messageID is in the slice call channelMessageDelete function. +// If the slice is empty do nothing. +// channelID : The ID of the channel for the messages to delete. +// messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages. +func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string, options ...RequestOption) (err error) { + + if len(messages) == 0 { + return + } + + if len(messages) == 1 { + err = s.ChannelMessageDelete(channelID, messages[0], options...) + return + } + + if len(messages) > 100 { + messages = messages[:100] + } + + data := struct { + Messages []string `json:"messages"` + }{messages} + + _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID), options...) + return +} + +// ChannelMessagePin pins a message within a given channel. +// channelID: The ID of a channel. +// messageID: The ID of a message. +func (s *Session) ChannelMessagePin(channelID, messageID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""), options...) + return +} + +// ChannelMessageUnpin unpins a message within a given channel. +// channelID: The ID of a channel. +// messageID: The ID of a message. +func (s *Session) ChannelMessageUnpin(channelID, messageID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""), options...) + return +} + +// ChannelMessagesPinned returns an array of Message structures for pinned messages +// within a given channel +// channelID : The ID of a Channel. +func (s *Session) ChannelMessagesPinned(channelID string, options ...RequestOption) (st []*Message, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID), options...) + + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelFileSend sends a file to the given channel. +// channelID : The ID of a Channel. +// name: The name of the file. +// io.Reader : A reader for the file contents. +func (s *Session) ChannelFileSend(channelID, name string, r io.Reader, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}}, options...) +} + +// ChannelFileSendWithMessage sends a file to the given channel with an message. +// DEPRECATED. Use ChannelMessageSendComplex instead. +// channelID : The ID of a Channel. +// content: Optional Message content. +// name: The name of the file. +// io.Reader : A reader for the file contents. +func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader, options ...RequestOption) (*Message, error) { + return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content}, options...) +} + +// ChannelInvites returns an array of Invite structures for the given channel +// channelID : The ID of a Channel +func (s *Session) ChannelInvites(channelID string, options ...RequestOption) (st []*Invite, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelInviteCreate creates a new invite for the given channel. +// channelID : The ID of a Channel +// i : An Invite struct with the values MaxAge, MaxUses and Temporary defined. +func (s *Session) ChannelInviteCreate(channelID string, i Invite, options ...RequestOption) (st *Invite, err error) { + + data := struct { + MaxAge int `json:"max_age"` + MaxUses int `json:"max_uses"` + Temporary bool `json:"temporary"` + Unique bool `json:"unique"` + }{i.MaxAge, i.MaxUses, i.Temporary, i.Unique} + + body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelPermissionSet creates a Permission Override for the given channel. +// NOTE: This func name may changed. Using Set instead of Create because +// you can both create a new override or update an override with this function. +func (s *Session) ChannelPermissionSet(channelID, targetID string, targetType PermissionOverwriteType, allow, deny int64, options ...RequestOption) (err error) { + + data := struct { + ID string `json:"id"` + Type PermissionOverwriteType `json:"type"` + Allow int64 `json:"allow,string"` + Deny int64 `json:"deny,string"` + }{targetID, targetType, allow, deny} + + _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""), options...) + return +} + +// ChannelPermissionDelete deletes a specific permission override for the given channel. +// NOTE: Name of this func may change. +func (s *Session) ChannelPermissionDelete(channelID, targetID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""), options...) + return +} + +// ChannelMessageCrosspost cross posts a message in a news channel to followers +// of the channel +// channelID : The ID of a Channel +// messageID : The ID of a Message +func (s *Session) ChannelMessageCrosspost(channelID, messageID string, options ...RequestOption) (st *Message, err error) { + + endpoint := EndpointChannelMessageCrosspost(channelID, messageID) + + body, err := s.RequestWithBucketID("POST", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ChannelNewsFollow follows a news channel in the targetID +// channelID : The ID of a News Channel +// targetID : The ID of a Channel where the News Channel should post to +func (s *Session) ChannelNewsFollow(channelID, targetID string, options ...RequestOption) (st *ChannelFollow, err error) { + + endpoint := EndpointChannelFollow(channelID) + + data := struct { + WebhookChannelID string `json:"webhook_channel_id"` + }{targetID} + + body, err := s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Invites +// ------------------------------------------------------------------------------------------------ + +// Invite returns an Invite structure of the given invite +// inviteID : The invite code +func (s *Session) Invite(inviteID string, options ...RequestOption) (st *Invite, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// InviteWithCounts returns an Invite structure of the given invite including approximate member counts +// inviteID : The invite code +func (s *Session) InviteWithCounts(inviteID string, options ...RequestOption) (st *Invite, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID)+"?with_counts=true", nil, EndpointInvite(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// InviteComplex returns an Invite structure of the given invite including specified fields. +// inviteID : The invite code +// guildScheduledEventID : If specified, includes specified guild scheduled event. +// withCounts : Whether to include approximate member counts or not +// withExpiration : Whether to include expiration time or not +func (s *Session) InviteComplex(inviteID, guildScheduledEventID string, withCounts, withExpiration bool, options ...RequestOption) (st *Invite, err error) { + endpoint := EndpointInvite(inviteID) + v := url.Values{} + if guildScheduledEventID != "" { + v.Set("guild_scheduled_event_id", guildScheduledEventID) + } + if withCounts { + v.Set("with_counts", "true") + } + if withExpiration { + v.Set("with_expiration", "true") + } + + if len(v) != 0 { + endpoint += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", endpoint, nil, EndpointInvite(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// InviteDelete deletes an existing invite +// inviteID : the code of an invite +func (s *Session) InviteDelete(inviteID string, options ...RequestOption) (st *Invite, err error) { + + body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// InviteAccept accepts an Invite to a Guild or Channel +// inviteID : The invite code +func (s *Session) InviteAccept(inviteID string, options ...RequestOption) (st *Invite, err error) { + + body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Voice +// ------------------------------------------------------------------------------------------------ + +// VoiceRegions returns the voice server regions +func (s *Session) VoiceRegions(options ...RequestOption) (st []*VoiceRegion, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to Discord Websockets +// ------------------------------------------------------------------------------------------------ + +// Gateway returns the websocket Gateway address +func (s *Session) Gateway(options ...RequestOption) (gateway string, err error) { + + response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway, options...) + if err != nil { + return + } + + temp := struct { + URL string `json:"url"` + }{} + + err = unmarshal(response, &temp) + if err != nil { + return + } + + gateway = temp.URL + + // Ensure the gateway always has a trailing slash. + // MacOS will fail to connect if we add query params without a trailing slash on the base domain. + if !strings.HasSuffix(gateway, "/") { + gateway += "/" + } + + return +} + +// GatewayBot returns the websocket Gateway address and the recommended number of shards +func (s *Session) GatewayBot(options ...RequestOption) (st *GatewayBotResponse, err error) { + + response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot, options...) + if err != nil { + return + } + + err = unmarshal(response, &st) + if err != nil { + return + } + + // Ensure the gateway always has a trailing slash. + // MacOS will fail to connect if we add query params without a trailing slash on the base domain. + if !strings.HasSuffix(st.URL, "/") { + st.URL += "/" + } + + return +} + +// Functions specific to Webhooks + +// WebhookCreate returns a new Webhook. +// channelID: The ID of a Channel. +// name : The name of the webhook. +// avatar : The avatar of the webhook. +func (s *Session) WebhookCreate(channelID, name, avatar string, options ...RequestOption) (st *Webhook, err error) { + + data := struct { + Name string `json:"name"` + Avatar string `json:"avatar,omitempty"` + }{name, avatar} + + body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// ChannelWebhooks returns all webhooks for a given channel. +// channelID: The ID of a channel. +func (s *Session) ChannelWebhooks(channelID string, options ...RequestOption) (st []*Webhook, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// GuildWebhooks returns all webhooks for a given guild. +// guildID: The ID of a Guild. +func (s *Session) GuildWebhooks(guildID string, options ...RequestOption) (st []*Webhook, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// Webhook returns a webhook for a given ID +// webhookID: The ID of a webhook. +func (s *Session) Webhook(webhookID string, options ...RequestOption) (st *Webhook, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// WebhookWithToken returns a webhook for a given ID +// webhookID: The ID of a webhook. +// token : The auth token for the webhook. +func (s *Session) WebhookWithToken(webhookID, token string, options ...RequestOption) (st *Webhook, err error) { + + body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// WebhookEdit updates an existing Webhook. +// webhookID: The ID of a webhook. +// name : The name of the webhook. +// avatar : The avatar of the webhook. +func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string, options ...RequestOption) (st *Webhook, err error) { + + data := struct { + Name string `json:"name,omitempty"` + Avatar string `json:"avatar,omitempty"` + ChannelID string `json:"channel_id,omitempty"` + }{name, avatar, channelID} + + body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// WebhookEditWithToken updates an existing Webhook with an auth token. +// webhookID: The ID of a webhook. +// token : The auth token for the webhook. +// name : The name of the webhook. +// avatar : The avatar of the webhook. +func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string, options ...RequestOption) (st *Webhook, err error) { + + data := struct { + Name string `json:"name,omitempty"` + Avatar string `json:"avatar,omitempty"` + }{name, avatar} + + var body []byte + body, err = s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +// WebhookDelete deletes a webhook for a given ID +// webhookID: The ID of a webhook. +func (s *Session) WebhookDelete(webhookID string, options ...RequestOption) (err error) { + + _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks, options...) + + return +} + +// WebhookDeleteWithToken deletes a webhook for a given ID with an auth token. +// webhookID: The ID of a webhook. +// token : The auth token for the webhook. +func (s *Session) WebhookDeleteWithToken(webhookID, token string, options ...RequestOption) (st *Webhook, err error) { + + body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + + return +} + +func (s *Session) webhookExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams, options ...RequestOption) (st *Message, err error) { + uri := EndpointWebhookToken(webhookID, token) + + v := url.Values{} + if wait { + v.Set("wait", "true") + } + + if threadID != "" { + v.Set("thread_id", threadID) + } + if len(v) != 0 { + uri += "?" + v.Encode() + } + + var response []byte + if len(data.Files) > 0 { + contentType, body, encodeErr := MultipartBodyWithJSON(data, data.Files) + if encodeErr != nil { + return st, encodeErr + } + + response, err = s.RequestRaw("POST", uri, contentType, body, uri, 0, options...) + } else { + response, err = s.RequestWithBucketID("POST", uri, data, uri, options...) + } + if !wait || err != nil { + return + } + + err = unmarshal(response, &st) + return +} + +// WebhookExecute executes a webhook. +// webhookID: The ID of a webhook. +// token : The auth token for the webhook +// wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) +func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams, options ...RequestOption) (st *Message, err error) { + return s.webhookExecute(webhookID, token, wait, "", data, options...) +} + +// WebhookThreadExecute executes a webhook in a thread. +// webhookID: The ID of a webhook. +// token : The auth token for the webhook +// wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) +// threadID : Sends a message to the specified thread within a webhook's channel. The thread will automatically be unarchived. +func (s *Session) WebhookThreadExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams, options ...RequestOption) (st *Message, err error) { + return s.webhookExecute(webhookID, token, wait, threadID, data, options...) +} + +// WebhookMessage gets a webhook message. +// webhookID : The ID of a webhook +// token : The auth token for the webhook +// messageID : The ID of message to get +func (s *Session) WebhookMessage(webhookID, token, messageID string, options ...RequestOption) (message *Message, err error) { + uri := EndpointWebhookMessage(webhookID, token, messageID) + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointWebhookToken("", ""), options...) + if err != nil { + return + } + + err = Unmarshal(body, &message) + + return +} + +// WebhookMessageEdit edits a webhook message and returns a new one. +// webhookID : The ID of a webhook +// token : The auth token for the webhook +// messageID : The ID of message to edit +func (s *Session) WebhookMessageEdit(webhookID, token, messageID string, data *WebhookEdit, options ...RequestOption) (st *Message, err error) { + uri := EndpointWebhookMessage(webhookID, token, messageID) + + var response []byte + if len(data.Files) > 0 { + contentType, body, err := MultipartBodyWithJSON(data, data.Files) + if err != nil { + return nil, err + } + + response, err = s.RequestRaw("PATCH", uri, contentType, body, uri, 0, options...) + if err != nil { + return nil, err + } + } else { + response, err = s.RequestWithBucketID("PATCH", uri, data, EndpointWebhookToken("", ""), options...) + + if err != nil { + return nil, err + } + } + + err = unmarshal(response, &st) + return +} + +// WebhookMessageDelete deletes a webhook message. +// webhookID : The ID of a webhook +// token : The auth token for the webhook +// messageID : The ID of a message to edit +func (s *Session) WebhookMessageDelete(webhookID, token, messageID string, options ...RequestOption) (err error) { + uri := EndpointWebhookMessage(webhookID, token, messageID) + + _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointWebhookToken("", ""), options...) + return +} + +// MessageReactionAdd creates an emoji reaction to a message. +// channelID : The channel ID. +// messageID : The message ID. +// emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier in name:id format (e.g. "hello:1234567654321") +func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string, options ...RequestOption) error { + + // emoji such as #⃣ need to have # escaped + emojiID = strings.Replace(emojiID, "#", "%23", -1) + _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""), options...) + + return err +} + +// MessageReactionRemove deletes an emoji reaction to a message. +// channelID : The channel ID. +// messageID : The message ID. +// emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier. +// userID : @me or ID of the user to delete the reaction for. +func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string, options ...RequestOption) error { + + // emoji such as #⃣ need to have # escaped + emojiID = strings.Replace(emojiID, "#", "%23", -1) + _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""), options...) + + return err +} + +// MessageReactionsRemoveAll deletes all reactions from a message +// channelID : The channel ID +// messageID : The message ID. +func (s *Session) MessageReactionsRemoveAll(channelID, messageID string, options ...RequestOption) error { + + _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID), options...) + + return err +} + +// MessageReactionsRemoveEmoji deletes all reactions of a certain emoji from a message +// channelID : The channel ID +// messageID : The message ID +// emojiID : The emoji ID +func (s *Session) MessageReactionsRemoveEmoji(channelID, messageID, emojiID string, options ...RequestOption) error { + + // emoji such as #⃣ need to have # escaped + emojiID = strings.Replace(emojiID, "#", "%23", -1) + _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactions(channelID, messageID, emojiID), nil, EndpointMessageReactions(channelID, messageID, emojiID), options...) + + return err +} + +// MessageReactions gets all the users reactions for a specific emoji. +// channelID : The channel ID. +// messageID : The message ID. +// emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier. +// limit : max number of users to return (max 100) +// beforeID : If provided all reactions returned will be before given ID. +// afterID : If provided all reactions returned will be after given ID. +func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int, beforeID, afterID string, options ...RequestOption) (st []*User, err error) { + // emoji such as #⃣ need to have # escaped + emojiID = strings.Replace(emojiID, "#", "%23", -1) + uri := EndpointMessageReactions(channelID, messageID, emojiID) + + v := url.Values{} + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + + if afterID != "" { + v.Set("after", afterID) + } + if beforeID != "" { + v.Set("before", beforeID) + } + + if len(v) > 0 { + uri += "?" + v.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to threads +// ------------------------------------------------------------------------------------------------ + +// MessageThreadStartComplex creates a new thread from an existing message. +// channelID : Channel to create thread in +// messageID : Message to start thread from +// data : Parameters of the thread +func (s *Session) MessageThreadStartComplex(channelID, messageID string, data *ThreadStart, options ...RequestOption) (ch *Channel, err error) { + endpoint := EndpointChannelMessageThread(channelID, messageID) + var body []byte + body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &ch) + return +} + +// MessageThreadStart creates a new thread from an existing message. +// channelID : Channel to create thread in +// messageID : Message to start thread from +// name : Name of the thread +// archiveDuration : Auto archive duration (in minutes) +func (s *Session) MessageThreadStart(channelID, messageID string, name string, archiveDuration int, options ...RequestOption) (ch *Channel, err error) { + return s.MessageThreadStartComplex(channelID, messageID, &ThreadStart{ + Name: name, + AutoArchiveDuration: archiveDuration, + }, options...) +} + +// ThreadStartComplex creates a new thread. +// channelID : Channel to create thread in +// data : Parameters of the thread +func (s *Session) ThreadStartComplex(channelID string, data *ThreadStart, options ...RequestOption) (ch *Channel, err error) { + endpoint := EndpointChannelThreads(channelID) + var body []byte + body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &ch) + return +} + +// ThreadStart creates a new thread. +// channelID : Channel to create thread in +// name : Name of the thread +// archiveDuration : Auto archive duration (in minutes) +func (s *Session) ThreadStart(channelID, name string, typ ChannelType, archiveDuration int, options ...RequestOption) (ch *Channel, err error) { + return s.ThreadStartComplex(channelID, &ThreadStart{ + Name: name, + Type: typ, + AutoArchiveDuration: archiveDuration, + }, options...) +} + +// ForumThreadStartComplex starts a new thread (creates a post) in a forum channel. +// channelID : Channel to create thread in. +// threadData : Parameters of the thread. +// messageData : Parameters of the starting message. +func (s *Session) ForumThreadStartComplex(channelID string, threadData *ThreadStart, messageData *MessageSend, options ...RequestOption) (th *Channel, err error) { + endpoint := EndpointChannelThreads(channelID) + + // TODO: Remove this when compatibility is not required. + if messageData.Embed != nil { + if messageData.Embeds == nil { + messageData.Embeds = []*MessageEmbed{messageData.Embed} + } else { + err = fmt.Errorf("cannot specify both Embed and Embeds") + return + } + } + + for _, embed := range messageData.Embeds { + if embed.Type == "" { + embed.Type = "rich" + } + } + + // TODO: Remove this when compatibility is not required. + files := messageData.Files + if messageData.File != nil { + if files == nil { + files = []*File{messageData.File} + } else { + err = fmt.Errorf("cannot specify both File and Files") + return + } + } + + data := struct { + *ThreadStart + Message *MessageSend `json:"message"` + }{ThreadStart: threadData, Message: messageData} + + var response []byte + if len(files) > 0 { + contentType, body, encodeErr := MultipartBodyWithJSON(data, files) + if encodeErr != nil { + return th, encodeErr + } + + response, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) + } else { + response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + } + if err != nil { + return + } + + err = unmarshal(response, &th) + return +} + +// ForumThreadStart starts a new thread (post) in a forum channel. +// channelID : Channel to create thread in. +// name : Name of the thread. +// archiveDuration : Auto archive duration. +// content : Content of the starting message. +func (s *Session) ForumThreadStart(channelID, name string, archiveDuration int, content string, options ...RequestOption) (th *Channel, err error) { + return s.ForumThreadStartComplex(channelID, &ThreadStart{ + Name: name, + AutoArchiveDuration: archiveDuration, + }, &MessageSend{Content: content}, options...) +} + +// ForumThreadStartEmbed starts a new thread (post) in a forum channel. +// channelID : Channel to create thread in. +// name : Name of the thread. +// archiveDuration : Auto archive duration. +// embed : Embed data of the starting message. +func (s *Session) ForumThreadStartEmbed(channelID, name string, archiveDuration int, embed *MessageEmbed, options ...RequestOption) (th *Channel, err error) { + return s.ForumThreadStartComplex(channelID, &ThreadStart{ + Name: name, + AutoArchiveDuration: archiveDuration, + }, &MessageSend{Embeds: []*MessageEmbed{embed}}, options...) +} + +// ForumThreadStartEmbeds starts a new thread (post) in a forum channel. +// channelID : Channel to create thread in. +// name : Name of the thread. +// archiveDuration : Auto archive duration. +// embeds : Embeds data of the starting message. +func (s *Session) ForumThreadStartEmbeds(channelID, name string, archiveDuration int, embeds []*MessageEmbed, options ...RequestOption) (th *Channel, err error) { + return s.ForumThreadStartComplex(channelID, &ThreadStart{ + Name: name, + AutoArchiveDuration: archiveDuration, + }, &MessageSend{Embeds: embeds}, options...) +} + +// ThreadJoin adds current user to a thread +func (s *Session) ThreadJoin(id string, options ...RequestOption) error { + endpoint := EndpointThreadMember(id, "@me") + _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint, options...) + return err +} + +// ThreadLeave removes current user to a thread +func (s *Session) ThreadLeave(id string, options ...RequestOption) error { + endpoint := EndpointThreadMember(id, "@me") + _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) + return err +} + +// ThreadMemberAdd adds another member to a thread +func (s *Session) ThreadMemberAdd(threadID, memberID string, options ...RequestOption) error { + endpoint := EndpointThreadMember(threadID, memberID) + _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint, options...) + return err +} + +// ThreadMemberRemove removes another member from a thread +func (s *Session) ThreadMemberRemove(threadID, memberID string, options ...RequestOption) error { + endpoint := EndpointThreadMember(threadID, memberID) + _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) + return err +} + +// ThreadMember returns thread member object for the specified member of a thread. +// withMember : Whether to include a guild member object. +func (s *Session) ThreadMember(threadID, memberID string, withMember bool, options ...RequestOption) (member *ThreadMember, err error) { + uri := EndpointThreadMember(threadID, memberID) + + queryParams := url.Values{} + if withMember { + queryParams.Set("with_member", "true") + } + + if len(queryParams) > 0 { + uri += "?" + queryParams.Encode() + } + + var body []byte + body, err = s.RequestWithBucketID("GET", uri, nil, uri, options...) + + if err != nil { + return + } + + err = unmarshal(body, &member) + return +} + +// ThreadMembers returns all members of specified thread. +// limit : Max number of thread members to return (1-100). Defaults to 100. +// afterID : Get thread members after this user ID. +// withMember : Whether to include a guild member object for each thread member. +func (s *Session) ThreadMembers(threadID string, limit int, withMember bool, afterID string, options ...RequestOption) (members []*ThreadMember, err error) { + uri := EndpointThreadMembers(threadID) + + queryParams := url.Values{} + if withMember { + queryParams.Set("with_member", "true") + } + if limit > 0 { + queryParams.Set("limit", strconv.Itoa(limit)) + } + if afterID != "" { + queryParams.Set("after", afterID) + } + + if len(queryParams) > 0 { + uri += "?" + queryParams.Encode() + } + + var body []byte + body, err = s.RequestWithBucketID("GET", uri, nil, uri, options...) + + if err != nil { + return + } + + err = unmarshal(body, &members) + return +} + +// ThreadsActive returns all active threads for specified channel. +func (s *Session) ThreadsActive(channelID string, options ...RequestOption) (threads *ThreadsList, err error) { + var body []byte + body, err = s.RequestWithBucketID("GET", EndpointChannelActiveThreads(channelID), nil, EndpointChannelActiveThreads(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &threads) + return +} + +// GuildThreadsActive returns all active threads for specified guild. +func (s *Session) GuildThreadsActive(guildID string, options ...RequestOption) (threads *ThreadsList, err error) { + var body []byte + body, err = s.RequestWithBucketID("GET", EndpointGuildActiveThreads(guildID), nil, EndpointGuildActiveThreads(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &threads) + return +} + +// ThreadsArchived returns archived threads for specified channel. +// before : If specified returns only threads before the timestamp +// limit : Optional maximum amount of threads to return. +func (s *Session) ThreadsArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { + endpoint := EndpointChannelPublicArchivedThreads(channelID) + v := url.Values{} + if before != nil { + v.Set("before", before.Format(time.RFC3339)) + } + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + + if len(v) > 0 { + endpoint += "?" + v.Encode() + } + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &threads) + return +} + +// ThreadsPrivateArchived returns archived private threads for specified channel. +// before : If specified returns only threads before the timestamp +// limit : Optional maximum amount of threads to return. +func (s *Session) ThreadsPrivateArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { + endpoint := EndpointChannelPrivateArchivedThreads(channelID) + v := url.Values{} + if before != nil { + v.Set("before", before.Format(time.RFC3339)) + } + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + + if len(v) > 0 { + endpoint += "?" + v.Encode() + } + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &threads) + return +} + +// ThreadsPrivateJoinedArchived returns archived joined private threads for specified channel. +// before : If specified returns only threads before the timestamp +// limit : Optional maximum amount of threads to return. +func (s *Session) ThreadsPrivateJoinedArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { + endpoint := EndpointChannelJoinedPrivateArchivedThreads(channelID) + v := url.Values{} + if before != nil { + v.Set("before", before.Format(time.RFC3339)) + } + + if limit > 0 { + v.Set("limit", strconv.Itoa(limit)) + } + + if len(v) > 0 { + endpoint += "?" + v.Encode() + } + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &threads) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to application (slash) commands +// ------------------------------------------------------------------------------------------------ + +// ApplicationCommandCreate creates a global application command and returns it. +// appID : The application ID. +// guildID : Guild ID to create guild-specific application command. If empty - creates global application command. +// cmd : New application command data. +func (s *Session) ApplicationCommandCreate(appID string, guildID string, cmd *ApplicationCommand, options ...RequestOption) (ccmd *ApplicationCommand, err error) { + endpoint := EndpointApplicationGlobalCommands(appID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommands(appID, guildID) + } + + body, err := s.RequestWithBucketID("POST", endpoint, *cmd, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &ccmd) + + return +} + +// ApplicationCommandEdit edits application command and returns new command data. +// appID : The application ID. +// cmdID : Application command ID to edit. +// guildID : Guild ID to edit guild-specific application command. If empty - edits global application command. +// cmd : Updated application command data. +func (s *Session) ApplicationCommandEdit(appID, guildID, cmdID string, cmd *ApplicationCommand, options ...RequestOption) (updated *ApplicationCommand, err error) { + endpoint := EndpointApplicationGlobalCommand(appID, cmdID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) + } + + body, err := s.RequestWithBucketID("PATCH", endpoint, *cmd, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &updated) + + return +} + +// ApplicationCommandBulkOverwrite Creates commands overwriting existing commands. Returns a list of commands. +// appID : The application ID. +// commands : The commands to create. +func (s *Session) ApplicationCommandBulkOverwrite(appID string, guildID string, commands []*ApplicationCommand, options ...RequestOption) (createdCommands []*ApplicationCommand, err error) { + endpoint := EndpointApplicationGlobalCommands(appID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommands(appID, guildID) + } + + body, err := s.RequestWithBucketID("PUT", endpoint, commands, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &createdCommands) + + return +} + +// ApplicationCommandDelete deletes application command by ID. +// appID : The application ID. +// cmdID : Application command ID to delete. +// guildID : Guild ID to delete guild-specific application command. If empty - deletes global application command. +func (s *Session) ApplicationCommandDelete(appID, guildID, cmdID string, options ...RequestOption) error { + endpoint := EndpointApplicationGlobalCommand(appID, cmdID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) + } + + _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) + + return err +} + +// ApplicationCommand retrieves an application command by given ID. +// appID : The application ID. +// cmdID : Application command ID. +// guildID : Guild ID to retrieve guild-specific application command. If empty - retrieves global application command. +func (s *Session) ApplicationCommand(appID, guildID, cmdID string, options ...RequestOption) (cmd *ApplicationCommand, err error) { + endpoint := EndpointApplicationGlobalCommand(appID, cmdID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) + } + + body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &cmd) + + return +} + +// ApplicationCommands retrieves all commands in application. +// appID : The application ID. +// guildID : Guild ID to retrieve all guild-specific application commands. If empty - retrieves global application commands. +func (s *Session) ApplicationCommands(appID, guildID string, options ...RequestOption) (cmd []*ApplicationCommand, err error) { + endpoint := EndpointApplicationGlobalCommands(appID) + if guildID != "" { + endpoint = EndpointApplicationGuildCommands(appID, guildID) + } + + body, err := s.RequestWithBucketID("GET", endpoint+"?with_localizations=true", nil, "GET "+endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &cmd) + + return +} + +// GuildApplicationCommandsPermissions returns permissions for application commands in a guild. +// appID : The application ID +// guildID : Guild ID to retrieve application commands permissions for. +func (s *Session) GuildApplicationCommandsPermissions(appID, guildID string, options ...RequestOption) (permissions []*GuildApplicationCommandPermissions, err error) { + endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &permissions) + return +} + +// ApplicationCommandPermissions returns all permissions of an application command +// appID : The Application ID +// guildID : The guild ID containing the application command +// cmdID : The command ID to retrieve the permissions of +func (s *Session) ApplicationCommandPermissions(appID, guildID, cmdID string, options ...RequestOption) (permissions *GuildApplicationCommandPermissions, err error) { + endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &permissions) + return +} + +// ApplicationCommandPermissionsEdit edits the permissions of an application command +// appID : The Application ID +// guildID : The guild ID containing the application command +// cmdID : The command ID to edit the permissions of +// permissions : An object containing a list of permissions for the application command +// +// NOTE: Requires OAuth2 token with applications.commands.permissions.update scope +func (s *Session) ApplicationCommandPermissionsEdit(appID, guildID, cmdID string, permissions *ApplicationCommandPermissionsList, options ...RequestOption) (err error) { + endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID) + + _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint, options...) + return +} + +// ApplicationCommandPermissionsBatchEdit edits the permissions of a batch of commands +// appID : The Application ID +// guildID : The guild ID to batch edit commands of +// permissions : A list of permissions paired with a command ID, guild ID, and application ID per application command +// +// NOTE: This endpoint has been disabled with updates to command permissions (Permissions v2). Please use ApplicationCommandPermissionsEdit instead. +func (s *Session) ApplicationCommandPermissionsBatchEdit(appID, guildID string, permissions []*GuildApplicationCommandPermissions, options ...RequestOption) (err error) { + endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID) + + _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint, options...) + return +} + +// InteractionRespond creates the response to an interaction. +// interaction : Interaction instance. +// resp : Response message data. +func (s *Session) InteractionRespond(interaction *Interaction, resp *InteractionResponse, options ...RequestOption) error { + endpoint := EndpointInteractionResponse(interaction.ID, interaction.Token) + + if resp.Data != nil && len(resp.Data.Files) > 0 { + contentType, body, err := MultipartBodyWithJSON(resp, resp.Data.Files) + if err != nil { + return err + } + + _, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) + return err + } + + _, err := s.RequestWithBucketID("POST", endpoint, *resp, endpoint, options...) + return err +} + +// InteractionResponse gets the response to an interaction. +// interaction : Interaction instance. +func (s *Session) InteractionResponse(interaction *Interaction, options ...RequestOption) (*Message, error) { + return s.WebhookMessage(interaction.AppID, interaction.Token, "@original", options...) +} + +// InteractionResponseEdit edits the response to an interaction. +// interaction : Interaction instance. +// newresp : Updated response message data. +func (s *Session) InteractionResponseEdit(interaction *Interaction, newresp *WebhookEdit, options ...RequestOption) (*Message, error) { + return s.WebhookMessageEdit(interaction.AppID, interaction.Token, "@original", newresp, options...) +} + +// InteractionResponseDelete deletes the response to an interaction. +// interaction : Interaction instance. +func (s *Session) InteractionResponseDelete(interaction *Interaction, options ...RequestOption) error { + endpoint := EndpointInteractionResponseActions(interaction.AppID, interaction.Token) + + _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) + + return err +} + +// FollowupMessageCreate creates the followup message for an interaction. +// interaction : Interaction instance. +// wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) +// data : Data of the message to send. +func (s *Session) FollowupMessageCreate(interaction *Interaction, wait bool, data *WebhookParams, options ...RequestOption) (*Message, error) { + return s.WebhookExecute(interaction.AppID, interaction.Token, wait, data, options...) +} + +// FollowupMessageEdit edits a followup message of an interaction. +// interaction : Interaction instance. +// messageID : The followup message ID. +// data : Data to update the message +func (s *Session) FollowupMessageEdit(interaction *Interaction, messageID string, data *WebhookEdit, options ...RequestOption) (*Message, error) { + return s.WebhookMessageEdit(interaction.AppID, interaction.Token, messageID, data, options...) +} + +// FollowupMessageDelete deletes a followup message of an interaction. +// interaction : Interaction instance. +// messageID : The followup message ID. +func (s *Session) FollowupMessageDelete(interaction *Interaction, messageID string, options ...RequestOption) error { + return s.WebhookMessageDelete(interaction.AppID, interaction.Token, messageID, options...) +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to stage instances +// ------------------------------------------------------------------------------------------------ + +// StageInstanceCreate creates and returns a new Stage instance associated to a Stage channel. +// data : Parameters needed to create a stage instance. +// data : The data of the Stage instance to create +func (s *Session) StageInstanceCreate(data *StageInstanceParams, options ...RequestOption) (si *StageInstance, err error) { + body, err := s.RequestWithBucketID("POST", EndpointStageInstances, data, EndpointStageInstances, options...) + if err != nil { + return + } + + err = unmarshal(body, &si) + return +} + +// StageInstance will retrieve a Stage instance by ID of the Stage channel. +// channelID : The ID of the Stage channel +func (s *Session) StageInstance(channelID string, options ...RequestOption) (si *StageInstance, err error) { + body, err := s.RequestWithBucketID("GET", EndpointStageInstance(channelID), nil, EndpointStageInstance(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &si) + return +} + +// StageInstanceEdit will edit a Stage instance by ID of the Stage channel. +// channelID : The ID of the Stage channel +// data : The data to edit the Stage instance +func (s *Session) StageInstanceEdit(channelID string, data *StageInstanceParams, options ...RequestOption) (si *StageInstance, err error) { + + body, err := s.RequestWithBucketID("PATCH", EndpointStageInstance(channelID), data, EndpointStageInstance(channelID), options...) + if err != nil { + return + } + + err = unmarshal(body, &si) + return +} + +// StageInstanceDelete will delete a Stage instance by ID of the Stage channel. +// channelID : The ID of the Stage channel +func (s *Session) StageInstanceDelete(channelID string, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("DELETE", EndpointStageInstance(channelID), nil, EndpointStageInstance(channelID), options...) + return +} + +// ------------------------------------------------------------------------------------------------ +// Functions specific to guilds scheduled events +// ------------------------------------------------------------------------------------------------ + +// GuildScheduledEvents returns an array of GuildScheduledEvent for a guild +// guildID : The ID of a Guild +// userCount : Whether to include the user count in the response +func (s *Session) GuildScheduledEvents(guildID string, userCount bool, options ...RequestOption) (st []*GuildScheduledEvent, err error) { + uri := EndpointGuildScheduledEvents(guildID) + if userCount { + uri += "?with_user_count=true" + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvents(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildScheduledEvent returns a specific GuildScheduledEvent in a guild +// guildID : The ID of a Guild +// eventID : The ID of the event +// userCount : Whether to include the user count in the response +func (s *Session) GuildScheduledEvent(guildID, eventID string, userCount bool, options ...RequestOption) (st *GuildScheduledEvent, err error) { + uri := EndpointGuildScheduledEvent(guildID, eventID) + if userCount { + uri += "?with_user_count=true" + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvent(guildID, eventID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildScheduledEventCreate creates a GuildScheduledEvent for a guild and returns it +// guildID : The ID of a Guild +// eventID : The ID of the event +func (s *Session) GuildScheduledEventCreate(guildID string, event *GuildScheduledEventParams, options ...RequestOption) (st *GuildScheduledEvent, err error) { + body, err := s.RequestWithBucketID("POST", EndpointGuildScheduledEvents(guildID), event, EndpointGuildScheduledEvents(guildID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildScheduledEventEdit updates a specific event for a guild and returns it. +// guildID : The ID of a Guild +// eventID : The ID of the event +func (s *Session) GuildScheduledEventEdit(guildID, eventID string, event *GuildScheduledEventParams, options ...RequestOption) (st *GuildScheduledEvent, err error) { + body, err := s.RequestWithBucketID("PATCH", EndpointGuildScheduledEvent(guildID, eventID), event, EndpointGuildScheduledEvent(guildID, eventID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildScheduledEventDelete deletes a specific GuildScheduledEvent in a guild +// guildID : The ID of a Guild +// eventID : The ID of the event +func (s *Session) GuildScheduledEventDelete(guildID, eventID string, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("DELETE", EndpointGuildScheduledEvent(guildID, eventID), nil, EndpointGuildScheduledEvent(guildID, eventID), options...) + return +} + +// GuildScheduledEventUsers returns an array of GuildScheduledEventUser for a particular event in a guild +// guildID : The ID of a Guild +// eventID : The ID of the event +// limit : The maximum number of users to return (Max 100) +// withMember : Whether to include the member object in the response +// beforeID : If is not empty all returned users entries will be before the given ID +// afterID : If is not empty all returned users entries will be after the given ID +func (s *Session) GuildScheduledEventUsers(guildID, eventID string, limit int, withMember bool, beforeID, afterID string, options ...RequestOption) (st []*GuildScheduledEventUser, err error) { + uri := EndpointGuildScheduledEventUsers(guildID, eventID) + + queryParams := url.Values{} + if withMember { + queryParams.Set("with_member", "true") + } + if limit > 0 { + queryParams.Set("limit", strconv.Itoa(limit)) + } + if beforeID != "" { + queryParams.Set("before", beforeID) + } + if afterID != "" { + queryParams.Set("after", afterID) + } + + if len(queryParams) > 0 { + uri += "?" + queryParams.Encode() + } + + body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEventUsers(guildID, eventID), options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// GuildOnboarding returns onboarding configuration of a guild. +// guildID : The ID of the guild +func (s *Session) GuildOnboarding(guildID string, options ...RequestOption) (onboarding *GuildOnboarding, err error) { + endpoint := EndpointGuildOnboarding(guildID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &onboarding) + return +} + +// GuildOnboardingEdit edits onboarding configuration of a guild. +// guildID : The ID of the guild +// o : New GuildOnboarding data +func (s *Session) GuildOnboardingEdit(guildID string, o *GuildOnboarding, options ...RequestOption) (onboarding *GuildOnboarding, err error) { + endpoint := EndpointGuildOnboarding(guildID) + + var body []byte + body, err = s.RequestWithBucketID("PUT", endpoint, o, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &onboarding) + return +} + +// ---------------------------------------------------------------------- +// Functions specific to auto moderation +// ---------------------------------------------------------------------- + +// AutoModerationRules returns a list of auto moderation rules. +// guildID : ID of the guild +func (s *Session) AutoModerationRules(guildID string, options ...RequestOption) (st []*AutoModerationRule, err error) { + endpoint := EndpointGuildAutoModerationRules(guildID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// AutoModerationRule returns an auto moderation rule. +// guildID : ID of the guild +// ruleID : ID of the auto moderation rule +func (s *Session) AutoModerationRule(guildID, ruleID string, options ...RequestOption) (st *AutoModerationRule, err error) { + endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// AutoModerationRuleCreate creates an auto moderation rule with the given data and returns it. +// guildID : ID of the guild +// rule : Rule data +func (s *Session) AutoModerationRuleCreate(guildID string, rule *AutoModerationRule, options ...RequestOption) (st *AutoModerationRule, err error) { + endpoint := EndpointGuildAutoModerationRules(guildID) + + var body []byte + body, err = s.RequestWithBucketID("POST", endpoint, rule, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// AutoModerationRuleEdit edits and returns the updated auto moderation rule. +// guildID : ID of the guild +// ruleID : ID of the auto moderation rule +// rule : New rule data +func (s *Session) AutoModerationRuleEdit(guildID, ruleID string, rule *AutoModerationRule, options ...RequestOption) (st *AutoModerationRule, err error) { + endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) + + var body []byte + body, err = s.RequestWithBucketID("PATCH", endpoint, rule, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// AutoModerationRuleDelete deletes an auto moderation rule. +// guildID : ID of the guild +// ruleID : ID of the auto moderation rule +func (s *Session) AutoModerationRuleDelete(guildID, ruleID string, options ...RequestOption) (err error) { + endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) + _, err = s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) + return +} + +// ApplicationRoleConnectionMetadata returns application role connection metadata. +// appID : ID of the application +func (s *Session) ApplicationRoleConnectionMetadata(appID string) (st []*ApplicationRoleConnectionMetadata, err error) { + endpoint := EndpointApplicationRoleConnectionMetadata(appID) + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ApplicationRoleConnectionMetadataUpdate updates and returns application role connection metadata. +// appID : ID of the application +// metadata : New metadata +func (s *Session) ApplicationRoleConnectionMetadataUpdate(appID string, metadata []*ApplicationRoleConnectionMetadata) (st []*ApplicationRoleConnectionMetadata, err error) { + endpoint := EndpointApplicationRoleConnectionMetadata(appID) + var body []byte + body, err = s.RequestWithBucketID("PUT", endpoint, metadata, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// UserApplicationRoleConnection returns user role connection to the specified application. +// appID : ID of the application +func (s *Session) UserApplicationRoleConnection(appID string) (st *ApplicationRoleConnection, err error) { + endpoint := EndpointUserApplicationRoleConnection(appID) + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &st) + return + +} + +// UserApplicationRoleConnectionUpdate updates and returns user role connection to the specified application. +// appID : ID of the application +// connection : New ApplicationRoleConnection data +func (s *Session) UserApplicationRoleConnectionUpdate(appID string, rconn *ApplicationRoleConnection) (st *ApplicationRoleConnection, err error) { + endpoint := EndpointUserApplicationRoleConnection(appID) + var body []byte + body, err = s.RequestWithBucketID("PUT", endpoint, rconn, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &st) + return +} + +// ---------------------------------------------------------------------- +// Functions specific to polls +// ---------------------------------------------------------------------- + +// PollAnswerVoters returns users who voted for a particular answer in a poll on the specified message. +// channelID : ID of the channel. +// messageID : ID of the message. +// answerID : ID of the answer. +func (s *Session) PollAnswerVoters(channelID, messageID string, answerID int) (voters []*User, err error) { + endpoint := EndpointPollAnswerVoters(channelID, messageID, answerID) + + var body []byte + body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) + if err != nil { + return + } + + var r struct { + Users []*User `json:"users"` + } + + err = unmarshal(body, &r) + if err != nil { + return + } + + voters = r.Users + return +} + +// PollExpire expires poll on the specified message. +// channelID : ID of the channel. +// messageID : ID of the message. +func (s *Session) PollExpire(channelID, messageID string) (msg *Message, err error) { + endpoint := EndpointPollExpire(channelID, messageID) + + var body []byte + body, err = s.RequestWithBucketID("POST", endpoint, nil, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &msg) + return +} + +// ---------------------------------------------------------------------- +// Functions specific to monetization +// ---------------------------------------------------------------------- + +// SKUs returns all SKUs for a given application. +// appID : The ID of the application. +func (s *Session) SKUs(appID string) (skus []*SKU, err error) { + endpoint := EndpointApplicationSKUs(appID) + + body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint) + if err != nil { + return + } + + err = unmarshal(body, &skus) + return +} + +// Entitlements returns all Entitlements for a given app, active and expired. +// appID : The ID of the application. +// filterOptions : Optional filter options; otherwise set it to nil. +func (s *Session) Entitlements(appID string, filterOptions *EntitlementFilterOptions, options ...RequestOption) (entitlements []*Entitlement, err error) { + endpoint := EndpointEntitlements(appID) + + queryParams := url.Values{} + if filterOptions != nil { + if filterOptions.UserID != "" { + queryParams.Set("user_id", filterOptions.UserID) + } + if filterOptions.SkuIDs != nil && len(filterOptions.SkuIDs) > 0 { + queryParams.Set("sku_ids", strings.Join(filterOptions.SkuIDs, ",")) + } + if filterOptions.Before != nil { + queryParams.Set("before", filterOptions.Before.Format(time.RFC3339)) + } + if filterOptions.After != nil { + queryParams.Set("after", filterOptions.After.Format(time.RFC3339)) + } + if filterOptions.Limit > 0 { + queryParams.Set("limit", strconv.Itoa(filterOptions.Limit)) + } + if filterOptions.GuildID != "" { + queryParams.Set("guild_id", filterOptions.GuildID) + } + if filterOptions.ExcludeEnded { + queryParams.Set("exclude_ended", "true") + } + } + + body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &entitlements) + return +} + +// EntitlementConsume marks a given One-Time Purchase for the user as consumed. +func (s *Session) EntitlementConsume(appID, entitlementID string, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("POST", EndpointEntitlementConsume(appID, entitlementID), nil, EndpointEntitlementConsume(appID, ""), options...) + return +} + +// EntitlementTestCreate creates a test entitlement to a given SKU for a given guild or user. +// Discord will act as though that user or guild has entitlement to your premium offering. +func (s *Session) EntitlementTestCreate(appID string, data *EntitlementTest, options ...RequestOption) (err error) { + endpoint := EndpointEntitlements(appID) + + _, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) + return +} + +// EntitlementTestDelete deletes a currently-active test entitlement. Discord will act as though +// that user or guild no longer has entitlement to your premium offering. +func (s *Session) EntitlementTestDelete(appID, entitlementID string, options ...RequestOption) (err error) { + _, err = s.RequestWithBucketID("DELETE", EndpointEntitlement(appID, entitlementID), nil, EndpointEntitlement(appID, ""), options...) + return +} + +// Subscriptions returns all subscriptions containing the SKU. +// skuID : The ID of the SKU. +// userID : User ID for which to return subscriptions. Required except for OAuth queries. +// before : Optional timestamp to retrieve subscriptions before this time. +// after : Optional timestamp to retrieve subscriptions after this time. +// limit : Optional maximum number of subscriptions to return (1-100, default 50). +func (s *Session) Subscriptions(skuID string, userID string, before, after *time.Time, limit int, options ...RequestOption) (subscriptions []*Subscription, err error) { + endpoint := EndpointSubscriptions(skuID) + + queryParams := url.Values{} + if before != nil { + queryParams.Set("before", before.Format(time.RFC3339)) + } + if after != nil { + queryParams.Set("after", after.Format(time.RFC3339)) + } + if userID != "" { + queryParams.Set("user_id", userID) + } + if limit > 0 { + queryParams.Set("limit", strconv.Itoa(limit)) + } + + body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &subscriptions) + return +} + +// Subscription returns a subscription by its SKU and subscription ID. +// skuID : The ID of the SKU. +// subscriptionID : The ID of the subscription. +// userID : User ID for which to return the subscription. Required except for OAuth queries. +func (s *Session) Subscription(skuID, subscriptionID, userID string, options ...RequestOption) (subscription *Subscription, err error) { + endpoint := EndpointSubscription(skuID, subscriptionID) + + queryParams := url.Values{} + if userID != "" { + // Unlike stated in the documentation, the user_id parameter is required here. + queryParams.Set("user_id", userID) + } + + body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) + if err != nil { + return + } + + err = unmarshal(body, &subscription) + return +} diff --git a/vendor/github.com/bwmarrin/discordgo/state.go b/vendor/github.com/bwmarrin/discordgo/state.go new file mode 100644 index 000000000..d1fbb383e --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/state.go @@ -0,0 +1,1310 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains code related to state tracking. If enabled, state +// tracking will capture the initial READY packet and many other websocket +// events and maintain an in-memory state of guilds, channels, users, and +// so forth. This information can be accessed through the Session.State struct. + +package discordgo + +import ( + "errors" + "sort" + "sync" +) + +// ErrNilState is returned when the state is nil. +var ErrNilState = errors.New("state not instantiated, please use discordgo.New() or assign Session.State") + +// ErrStateNotFound is returned when the state cache +// requested is not found +var ErrStateNotFound = errors.New("state cache not found") + +// ErrMessageIncompletePermissions is returned when the message +// requested for permissions does not contain enough data to +// generate the permissions. +var ErrMessageIncompletePermissions = errors.New("message incomplete, unable to determine permissions") + +// A State contains the current known state. +// As discord sends this in a READY blob, it seems reasonable to simply +// use that struct as the data store. +type State struct { + sync.RWMutex + Ready + + // MaxMessageCount represents how many messages per channel the state will store. + MaxMessageCount int + TrackChannels bool + TrackThreads bool + TrackEmojis bool + TrackStickers bool + TrackMembers bool + TrackThreadMembers bool + TrackRoles bool + TrackVoice bool + TrackPresences bool + + guildMap map[string]*Guild + channelMap map[string]*Channel + memberMap map[string]map[string]*Member +} + +// NewState creates an empty state. +func NewState() *State { + return &State{ + Ready: Ready{ + PrivateChannels: []*Channel{}, + Guilds: []*Guild{}, + }, + TrackChannels: true, + TrackThreads: true, + TrackEmojis: true, + TrackStickers: true, + TrackMembers: true, + TrackThreadMembers: true, + TrackRoles: true, + TrackVoice: true, + TrackPresences: true, + guildMap: make(map[string]*Guild), + channelMap: make(map[string]*Channel), + memberMap: make(map[string]map[string]*Member), + } +} + +func (s *State) createMemberMap(guild *Guild) { + members := make(map[string]*Member) + for _, m := range guild.Members { + members[m.User.ID] = m + } + s.memberMap[guild.ID] = members +} + +// GuildAdd adds a guild to the current world state, or +// updates it if it already exists. +func (s *State) GuildAdd(guild *Guild) error { + if s == nil { + return ErrNilState + } + + s.Lock() + defer s.Unlock() + + // Update the channels to point to the right guild, adding them to the channelMap as we go + for _, c := range guild.Channels { + s.channelMap[c.ID] = c + } + + // Add all the threads to the state in case of thread sync list. + for _, t := range guild.Threads { + s.channelMap[t.ID] = t + } + + // If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid + if guild.Members != nil { + s.createMemberMap(guild) + } else if _, ok := s.memberMap[guild.ID]; !ok { + // Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist + s.memberMap[guild.ID] = make(map[string]*Member) + } + + if g, ok := s.guildMap[guild.ID]; ok { + // We are about to replace `g` in the state with `guild`, but first we need to + // make sure we preserve any fields that the `guild` doesn't contain from `g`. + if guild.MemberCount == 0 { + guild.MemberCount = g.MemberCount + } + if guild.Roles == nil { + guild.Roles = g.Roles + } + if guild.Emojis == nil { + guild.Emojis = g.Emojis + } + if guild.Members == nil { + guild.Members = g.Members + } + if guild.Presences == nil { + guild.Presences = g.Presences + } + if guild.Channels == nil { + guild.Channels = g.Channels + } + if guild.Threads == nil { + guild.Threads = g.Threads + } + if guild.VoiceStates == nil { + guild.VoiceStates = g.VoiceStates + } + *g = *guild + return nil + } + + s.Guilds = append(s.Guilds, guild) + s.guildMap[guild.ID] = guild + + return nil +} + +// GuildRemove removes a guild from current world state. +func (s *State) GuildRemove(guild *Guild) error { + if s == nil { + return ErrNilState + } + + _, err := s.Guild(guild.ID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + delete(s.guildMap, guild.ID) + + for i, g := range s.Guilds { + if g.ID == guild.ID { + s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...) + return nil + } + } + + return nil +} + +// Guild gets a guild by ID. +// Useful for querying if @me is in a guild: +// _, err := discordgo.Session.State.Guild(guildID) +// isInGuild := err == nil +func (s *State) Guild(guildID string) (*Guild, error) { + if s == nil { + return nil, ErrNilState + } + + s.RLock() + defer s.RUnlock() + + if g, ok := s.guildMap[guildID]; ok { + return g, nil + } + + return nil, ErrStateNotFound +} + +func (s *State) presenceAdd(guildID string, presence *Presence) error { + guild, ok := s.guildMap[guildID] + if !ok { + return ErrStateNotFound + } + + for i, p := range guild.Presences { + if p.User.ID == presence.User.ID { + //guild.Presences[i] = presence + + //Update status + guild.Presences[i].Activities = presence.Activities + if presence.Status != "" { + guild.Presences[i].Status = presence.Status + } + if presence.ClientStatus.Desktop != "" { + guild.Presences[i].ClientStatus.Desktop = presence.ClientStatus.Desktop + } + if presence.ClientStatus.Mobile != "" { + guild.Presences[i].ClientStatus.Mobile = presence.ClientStatus.Mobile + } + if presence.ClientStatus.Web != "" { + guild.Presences[i].ClientStatus.Web = presence.ClientStatus.Web + } + + //Update the optionally sent user information + //ID Is a mandatory field so you should not need to check if it is empty + guild.Presences[i].User.ID = presence.User.ID + + if presence.User.Avatar != "" { + guild.Presences[i].User.Avatar = presence.User.Avatar + } + if presence.User.Discriminator != "" { + guild.Presences[i].User.Discriminator = presence.User.Discriminator + } + if presence.User.Email != "" { + guild.Presences[i].User.Email = presence.User.Email + } + if presence.User.Token != "" { + guild.Presences[i].User.Token = presence.User.Token + } + if presence.User.Username != "" { + guild.Presences[i].User.Username = presence.User.Username + } + + return nil + } + } + + guild.Presences = append(guild.Presences, presence) + return nil +} + +// PresenceAdd adds a presence to the current world state, or +// updates it if it already exists. +func (s *State) PresenceAdd(guildID string, presence *Presence) error { + if s == nil { + return ErrNilState + } + + s.Lock() + defer s.Unlock() + + return s.presenceAdd(guildID, presence) +} + +// PresenceRemove removes a presence from the current world state. +func (s *State) PresenceRemove(guildID string, presence *Presence) error { + if s == nil { + return ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + for i, p := range guild.Presences { + if p.User.ID == presence.User.ID { + guild.Presences = append(guild.Presences[:i], guild.Presences[i+1:]...) + return nil + } + } + + return ErrStateNotFound +} + +// Presence gets a presence by ID from a guild. +func (s *State) Presence(guildID, userID string) (*Presence, error) { + if s == nil { + return nil, ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return nil, err + } + + for _, p := range guild.Presences { + if p.User.ID == userID { + return p, nil + } + } + + return nil, ErrStateNotFound +} + +// TODO: Consider moving Guild state update methods onto *Guild. + +func (s *State) memberAdd(member *Member) error { + guild, ok := s.guildMap[member.GuildID] + if !ok { + return ErrStateNotFound + } + + members, ok := s.memberMap[member.GuildID] + if !ok { + return ErrStateNotFound + } + + m, ok := members[member.User.ID] + if !ok { + members[member.User.ID] = member + guild.Members = append(guild.Members, member) + } else { + // We are about to replace `m` in the state with `member`, but first we need to + // make sure we preserve any fields that the `member` doesn't contain from `m`. + if member.JoinedAt.IsZero() { + member.JoinedAt = m.JoinedAt + } + *m = *member + } + return nil +} + +// MemberAdd adds a member to the current world state, or +// updates it if it already exists. +func (s *State) MemberAdd(member *Member) error { + if s == nil { + return ErrNilState + } + + s.Lock() + defer s.Unlock() + + return s.memberAdd(member) +} + +// MemberRemove removes a member from current world state. +func (s *State) MemberRemove(member *Member) error { + if s == nil { + return ErrNilState + } + + guild, err := s.Guild(member.GuildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + members, ok := s.memberMap[member.GuildID] + if !ok { + return ErrStateNotFound + } + + _, ok = members[member.User.ID] + if !ok { + return ErrStateNotFound + } + delete(members, member.User.ID) + + for i, m := range guild.Members { + if m.User.ID == member.User.ID { + guild.Members = append(guild.Members[:i], guild.Members[i+1:]...) + return nil + } + } + + return ErrStateNotFound +} + +// Member gets a member by ID from a guild. +func (s *State) Member(guildID, userID string) (*Member, error) { + if s == nil { + return nil, ErrNilState + } + + s.RLock() + defer s.RUnlock() + + members, ok := s.memberMap[guildID] + if !ok { + return nil, ErrStateNotFound + } + + m, ok := members[userID] + if ok { + return m, nil + } + + return nil, ErrStateNotFound +} + +// RoleAdd adds a role to the current world state, or +// updates it if it already exists. +func (s *State) RoleAdd(guildID string, role *Role) error { + if s == nil { + return ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + for i, r := range guild.Roles { + if r.ID == role.ID { + guild.Roles[i] = role + return nil + } + } + + guild.Roles = append(guild.Roles, role) + return nil +} + +// RoleRemove removes a role from current world state by ID. +func (s *State) RoleRemove(guildID, roleID string) error { + if s == nil { + return ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + for i, r := range guild.Roles { + if r.ID == roleID { + guild.Roles = append(guild.Roles[:i], guild.Roles[i+1:]...) + return nil + } + } + + return ErrStateNotFound +} + +// Role gets a role by ID from a guild. +func (s *State) Role(guildID, roleID string) (*Role, error) { + if s == nil { + return nil, ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return nil, err + } + + s.RLock() + defer s.RUnlock() + + for _, r := range guild.Roles { + if r.ID == roleID { + return r, nil + } + } + + return nil, ErrStateNotFound +} + +// ChannelAdd adds a channel to the current world state, or +// updates it if it already exists. +// Channels may exist either as PrivateChannels or inside +// a guild. +func (s *State) ChannelAdd(channel *Channel) error { + if s == nil { + return ErrNilState + } + + s.Lock() + defer s.Unlock() + + // If the channel exists, replace it + if c, ok := s.channelMap[channel.ID]; ok { + if channel.Messages == nil { + channel.Messages = c.Messages + } + if channel.PermissionOverwrites == nil { + channel.PermissionOverwrites = c.PermissionOverwrites + } + if channel.ThreadMetadata == nil { + channel.ThreadMetadata = c.ThreadMetadata + } + + *c = *channel + return nil + } + + if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { + s.PrivateChannels = append(s.PrivateChannels, channel) + s.channelMap[channel.ID] = channel + return nil + } + + guild, ok := s.guildMap[channel.GuildID] + if !ok { + return ErrStateNotFound + } + + if channel.IsThread() { + guild.Threads = append(guild.Threads, channel) + } else { + guild.Channels = append(guild.Channels, channel) + } + + s.channelMap[channel.ID] = channel + + return nil +} + +// ChannelRemove removes a channel from current world state. +func (s *State) ChannelRemove(channel *Channel) error { + if s == nil { + return ErrNilState + } + + _, err := s.Channel(channel.ID) + if err != nil { + return err + } + + if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { + s.Lock() + defer s.Unlock() + + for i, c := range s.PrivateChannels { + if c.ID == channel.ID { + s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...) + break + } + } + delete(s.channelMap, channel.ID) + return nil + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + if channel.IsThread() { + for i, t := range guild.Threads { + if t.ID == channel.ID { + guild.Threads = append(guild.Threads[:i], guild.Threads[i+1:]...) + break + } + } + } else { + for i, c := range guild.Channels { + if c.ID == channel.ID { + guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...) + break + } + } + } + + delete(s.channelMap, channel.ID) + + return nil +} + +// ThreadListSync syncs guild threads with provided ones. +func (s *State) ThreadListSync(tls *ThreadListSync) error { + guild, err := s.Guild(tls.GuildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + // This algorithm filters out archived or + // threads which are children of channels in channelIDs + // and then it adds all synced threads to guild threads and cache + index := 0 +outer: + for _, t := range guild.Threads { + if !t.ThreadMetadata.Archived && tls.ChannelIDs != nil { + for _, v := range tls.ChannelIDs { + if t.ParentID == v { + delete(s.channelMap, t.ID) + continue outer + } + } + guild.Threads[index] = t + index++ + } else { + delete(s.channelMap, t.ID) + } + } + guild.Threads = guild.Threads[:index] + for _, t := range tls.Threads { + s.channelMap[t.ID] = t + guild.Threads = append(guild.Threads, t) + } + + for _, m := range tls.Members { + if c, ok := s.channelMap[m.ID]; ok { + c.Member = m + } + } + + return nil +} + +// ThreadMembersUpdate updates thread members list +func (s *State) ThreadMembersUpdate(tmu *ThreadMembersUpdate) error { + thread, err := s.Channel(tmu.ID) + if err != nil { + return err + } + s.Lock() + defer s.Unlock() + + for idx, member := range thread.Members { + for _, removedMember := range tmu.RemovedMembers { + if member.ID == removedMember { + thread.Members = append(thread.Members[:idx], thread.Members[idx+1:]...) + break + } + } + } + + for _, addedMember := range tmu.AddedMembers { + thread.Members = append(thread.Members, addedMember.ThreadMember) + if addedMember.Member != nil { + err = s.memberAdd(addedMember.Member) + if err != nil { + return err + } + } + if addedMember.Presence != nil { + err = s.presenceAdd(tmu.GuildID, addedMember.Presence) + if err != nil { + return err + } + } + } + thread.MemberCount = tmu.MemberCount + + return nil +} + +// ThreadMemberUpdate sets or updates member data for the current user. +func (s *State) ThreadMemberUpdate(mu *ThreadMemberUpdate) error { + thread, err := s.Channel(mu.ID) + if err != nil { + return err + } + + thread.Member = mu.ThreadMember + return nil +} + +// Channel gets a channel by ID, it will look in all guilds and private channels. +func (s *State) Channel(channelID string) (*Channel, error) { + if s == nil { + return nil, ErrNilState + } + + s.RLock() + defer s.RUnlock() + + if c, ok := s.channelMap[channelID]; ok { + return c, nil + } + + return nil, ErrStateNotFound +} + +// Emoji returns an emoji for a guild and emoji id. +func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) { + if s == nil { + return nil, ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return nil, err + } + + s.RLock() + defer s.RUnlock() + + for _, e := range guild.Emojis { + if e.ID == emojiID { + return e, nil + } + } + + return nil, ErrStateNotFound +} + +// EmojiAdd adds an emoji to the current world state. +func (s *State) EmojiAdd(guildID string, emoji *Emoji) error { + if s == nil { + return ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + for i, e := range guild.Emojis { + if e.ID == emoji.ID { + guild.Emojis[i] = emoji + return nil + } + } + + guild.Emojis = append(guild.Emojis, emoji) + return nil +} + +// EmojisAdd adds multiple emojis to the world state. +func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error { + for _, e := range emojis { + if err := s.EmojiAdd(guildID, e); err != nil { + return err + } + } + return nil +} + +// MessageAdd adds a message to the current world state, or updates it if it exists. +// If the channel cannot be found, the message is discarded. +// Messages are kept in state up to s.MaxMessageCount per channel. +func (s *State) MessageAdd(message *Message) error { + if s == nil { + return ErrNilState + } + + c, err := s.Channel(message.ChannelID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + // If the message exists, merge in the new message contents. + for _, m := range c.Messages { + if m.ID == message.ID { + if message.Content != "" { + m.Content = message.Content + } + if message.EditedTimestamp != nil { + m.EditedTimestamp = message.EditedTimestamp + } + if message.Mentions != nil { + m.Mentions = message.Mentions + } + if message.Embeds != nil { + m.Embeds = message.Embeds + } + if message.Attachments != nil { + m.Attachments = message.Attachments + } + if !message.Timestamp.IsZero() { + m.Timestamp = message.Timestamp + } + if message.Author != nil { + m.Author = message.Author + } + if message.Components != nil { + m.Components = message.Components + } + + return nil + } + } + + c.Messages = append(c.Messages, message) + + if len(c.Messages) > s.MaxMessageCount { + c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:] + } + + return nil +} + +// MessageRemove removes a message from the world state. +func (s *State) MessageRemove(message *Message) error { + if s == nil { + return ErrNilState + } + + return s.messageRemoveByID(message.ChannelID, message.ID) +} + +// messageRemoveByID removes a message by channelID and messageID from the world state. +func (s *State) messageRemoveByID(channelID, messageID string) error { + c, err := s.Channel(channelID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + for i, m := range c.Messages { + if m.ID == messageID { + c.Messages = append(c.Messages[:i], c.Messages[i+1:]...) + + return nil + } + } + + return ErrStateNotFound +} + +func (s *State) voiceStateUpdate(update *VoiceStateUpdate) error { + guild, err := s.Guild(update.GuildID) + if err != nil { + return err + } + + s.Lock() + defer s.Unlock() + + // Handle Leaving Channel + if update.ChannelID == "" { + for i, state := range guild.VoiceStates { + if state.UserID == update.UserID { + guild.VoiceStates = append(guild.VoiceStates[:i], guild.VoiceStates[i+1:]...) + return nil + } + } + } else { + for i, state := range guild.VoiceStates { + if state.UserID == update.UserID { + guild.VoiceStates[i] = update.VoiceState + return nil + } + } + + guild.VoiceStates = append(guild.VoiceStates, update.VoiceState) + } + + return nil +} + +// VoiceState gets a VoiceState by guild and user ID. +func (s *State) VoiceState(guildID, userID string) (*VoiceState, error) { + if s == nil { + return nil, ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return nil, err + } + + for _, state := range guild.VoiceStates { + if state.UserID == userID { + return state, nil + } + } + + return nil, ErrStateNotFound +} + +// Message gets a message by channel and message ID. +func (s *State) Message(channelID, messageID string) (*Message, error) { + if s == nil { + return nil, ErrNilState + } + + c, err := s.Channel(channelID) + if err != nil { + return nil, err + } + + s.RLock() + defer s.RUnlock() + + for _, m := range c.Messages { + if m.ID == messageID { + return m, nil + } + } + + return nil, ErrStateNotFound +} + +// OnReady takes a Ready event and updates all internal state. +func (s *State) onReady(se *Session, r *Ready) (err error) { + if s == nil { + return ErrNilState + } + + s.Lock() + defer s.Unlock() + + // We must track at least the current user for Voice, even + // if state is disabled, store the bare essentials. + if !se.StateEnabled { + ready := Ready{ + Version: r.Version, + SessionID: r.SessionID, + User: r.User, + Shard: r.Shard, + Application: r.Application, + } + + s.Ready = ready + + return nil + } + + s.Ready = *r + + for _, g := range s.Guilds { + s.guildMap[g.ID] = g + s.createMemberMap(g) + + for _, c := range g.Channels { + s.channelMap[c.ID] = c + } + } + + for _, c := range s.PrivateChannels { + s.channelMap[c.ID] = c + } + + return nil +} + +// OnInterface handles all events related to states. +func (s *State) OnInterface(se *Session, i interface{}) (err error) { + if s == nil { + return ErrNilState + } + + r, ok := i.(*Ready) + if ok { + return s.onReady(se, r) + } + + if !se.StateEnabled { + return nil + } + + switch t := i.(type) { + case *GuildCreate: + err = s.GuildAdd(t.Guild) + case *GuildUpdate: + err = s.GuildAdd(t.Guild) + case *GuildDelete: + var old *Guild + old, err = s.Guild(t.ID) + if err == nil { + oldCopy := *old + t.BeforeDelete = &oldCopy + } + + err = s.GuildRemove(t.Guild) + case *GuildMemberAdd: + var guild *Guild + // Updates the MemberCount of the guild. + guild, err = s.Guild(t.Member.GuildID) + if err != nil { + return err + } + guild.MemberCount++ + + // Caches member if tracking is enabled. + if s.TrackMembers { + err = s.MemberAdd(t.Member) + } + case *GuildMemberUpdate: + if s.TrackMembers { + var old *Member + old, err = s.Member(t.GuildID, t.User.ID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + + err = s.MemberAdd(t.Member) + } + case *GuildMemberRemove: + var guild *Guild + // Updates the MemberCount of the guild. + guild, err = s.Guild(t.Member.GuildID) + if err != nil { + return err + } + guild.MemberCount-- + + // Removes member from the cache if tracking is enabled. + if s.TrackMembers { + err = s.MemberRemove(t.Member) + } + case *GuildMembersChunk: + if s.TrackMembers { + for i := range t.Members { + t.Members[i].GuildID = t.GuildID + err = s.MemberAdd(t.Members[i]) + } + } + + if s.TrackPresences { + for _, p := range t.Presences { + err = s.PresenceAdd(t.GuildID, p) + } + } + case *GuildRoleCreate: + if s.TrackRoles { + err = s.RoleAdd(t.GuildID, t.Role) + } + case *GuildRoleUpdate: + if s.TrackRoles { + err = s.RoleAdd(t.GuildID, t.Role) + } + case *GuildRoleDelete: + if s.TrackRoles { + err = s.RoleRemove(t.GuildID, t.RoleID) + } + case *GuildEmojisUpdate: + if s.TrackEmojis { + var guild *Guild + guild, err = s.Guild(t.GuildID) + if err != nil { + return err + } + s.Lock() + defer s.Unlock() + guild.Emojis = t.Emojis + } + case *GuildStickersUpdate: + if s.TrackStickers { + var guild *Guild + guild, err = s.Guild(t.GuildID) + if err != nil { + return err + } + s.Lock() + defer s.Unlock() + guild.Stickers = t.Stickers + } + case *ChannelCreate: + if s.TrackChannels { + err = s.ChannelAdd(t.Channel) + } + case *ChannelUpdate: + if s.TrackChannels { + old, err := s.Channel(t.ID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + err = s.ChannelAdd(t.Channel) + } + case *ChannelDelete: + if s.TrackChannels { + err = s.ChannelRemove(t.Channel) + } + case *ThreadCreate: + if s.TrackThreads { + err = s.ChannelAdd(t.Channel) + } + case *ThreadUpdate: + if s.TrackThreads { + old, err := s.Channel(t.ID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + err = s.ChannelAdd(t.Channel) + } + case *ThreadDelete: + if s.TrackThreads { + err = s.ChannelRemove(t.Channel) + } + case *ThreadMemberUpdate: + if s.TrackThreads { + err = s.ThreadMemberUpdate(t) + } + case *ThreadMembersUpdate: + if s.TrackThreadMembers { + err = s.ThreadMembersUpdate(t) + } + case *ThreadListSync: + if s.TrackThreads { + err = s.ThreadListSync(t) + } + case *MessageCreate: + if s.MaxMessageCount != 0 { + err = s.MessageAdd(t.Message) + } + case *MessageUpdate: + if s.MaxMessageCount != 0 { + var old *Message + old, err = s.Message(t.ChannelID, t.ID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + + err = s.MessageAdd(t.Message) + } + case *MessageDelete: + if s.MaxMessageCount != 0 { + var old *Message + old, err = s.Message(t.ChannelID, t.ID) + if err == nil { + oldCopy := *old + t.BeforeDelete = &oldCopy + } + + err = s.MessageRemove(t.Message) + } + case *MessageDeleteBulk: + if s.MaxMessageCount != 0 { + for _, mID := range t.Messages { + s.messageRemoveByID(t.ChannelID, mID) + } + } + case *VoiceStateUpdate: + if s.TrackVoice { + var old *VoiceState + old, err = s.VoiceState(t.GuildID, t.UserID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + + err = s.voiceStateUpdate(t) + } + case *PresenceUpdate: + if s.TrackPresences { + s.PresenceAdd(t.GuildID, &t.Presence) + } + if s.TrackMembers { + if t.Status == StatusOffline { + return + } + + var m *Member + m, err = s.Member(t.GuildID, t.User.ID) + + if err != nil { + // Member not found; this is a user coming online + m = &Member{ + GuildID: t.GuildID, + User: t.User, + } + } else { + if t.User.Username != "" { + m.User.Username = t.User.Username + } + } + + err = s.MemberAdd(m) + } + + } + + return +} + +// UserChannelPermissions returns the permission of a user in a channel. +// userID : The ID of the user to calculate permissions for. +// channelID : The ID of the channel to calculate permission for. +func (s *State) UserChannelPermissions(userID, channelID string) (apermissions int64, err error) { + if s == nil { + return 0, ErrNilState + } + + channel, err := s.Channel(channelID) + if err != nil { + return + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return + } + + member, err := s.Member(guild.ID, userID) + if err != nil { + return + } + + return memberPermissions(guild, channel, userID, member.Roles), nil +} + +// MessagePermissions returns the permissions of the author of the message +// in the channel in which it was sent. +func (s *State) MessagePermissions(message *Message) (apermissions int64, err error) { + if s == nil { + return 0, ErrNilState + } + + if message.Author == nil || message.Member == nil { + return 0, ErrMessageIncompletePermissions + } + + channel, err := s.Channel(message.ChannelID) + if err != nil { + return + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return + } + + return memberPermissions(guild, channel, message.Author.ID, message.Member.Roles), nil +} + +// UserColor returns the color of a user in a channel. +// While colors are defined at a Guild level, determining for a channel is more useful in message handlers. +// 0 is returned in cases of error, which is the color of @everyone. +// userID : The ID of the user to calculate the color for. +// channelID : The ID of the channel to calculate the color for. +func (s *State) UserColor(userID, channelID string) int { + if s == nil { + return 0 + } + + channel, err := s.Channel(channelID) + if err != nil { + return 0 + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return 0 + } + + member, err := s.Member(guild.ID, userID) + if err != nil { + return 0 + } + + return firstRoleColorColor(guild, member.Roles) +} + +// MessageColor returns the color of the author's name as displayed +// in the client associated with this message. +func (s *State) MessageColor(message *Message) int { + if s == nil { + return 0 + } + + if message.Member == nil || message.Member.Roles == nil { + return 0 + } + + channel, err := s.Channel(message.ChannelID) + if err != nil { + return 0 + } + + guild, err := s.Guild(channel.GuildID) + if err != nil { + return 0 + } + + return firstRoleColorColor(guild, message.Member.Roles) +} + +func firstRoleColorColor(guild *Guild, memberRoles []string) int { + roles := Roles(guild.Roles) + sort.Sort(roles) + + for _, role := range roles { + for _, roleID := range memberRoles { + if role.ID == roleID { + if role.Color != 0 { + return role.Color + } + } + } + } + + for _, role := range roles { + if role.ID == guild.ID { + return role.Color + } + } + + return 0 +} diff --git a/vendor/github.com/bwmarrin/discordgo/structs.go b/vendor/github.com/bwmarrin/discordgo/structs.go new file mode 100644 index 000000000..24c10c294 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/structs.go @@ -0,0 +1,3074 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains all structures for the discordgo package. These +// may be moved about later into separate files but I find it easier to have +// them all located together. + +package discordgo + +import ( + "encoding/json" + "fmt" + "math" + "net/http" + "regexp" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +// A Session represents a connection to the Discord API. +type Session struct { + sync.RWMutex + + // General configurable settings. + + // Authentication token for this session + // TODO: Remove Below, Deprecated, Use Identify struct + Token string + + MFA bool + + // Debug for printing JSON request/responses + Debug bool // Deprecated, will be removed. + LogLevel int + + // Should the session reconnect the websocket on errors. + ShouldReconnectOnError bool + + // Should voice connections reconnect on a session reconnect. + ShouldReconnectVoiceOnSessionError bool + + // Should the session retry requests when rate limited. + ShouldRetryOnRateLimit bool + + // Identify is sent during initial handshake with the discord gateway. + // https://discord.com/developers/docs/topics/gateway#identify + Identify Identify + + // TODO: Remove Below, Deprecated, Use Identify struct + // Should the session request compressed websocket data. + Compress bool + + // Sharding + ShardID int + ShardCount int + + // Should state tracking be enabled. + // State tracking is the best way for getting the users + // active guilds and the members of the guilds. + StateEnabled bool + + // Whether or not to call event handlers synchronously. + // e.g. false = launch event handlers in their own goroutines. + SyncEvents bool + + // Exposed but should not be modified by User. + + // Whether the Data Websocket is ready + DataReady bool // NOTE: Maye be deprecated soon + + // Max number of REST API retries + MaxRestRetries int + + // Status stores the current status of the websocket connection + // this is being tested, may stay, may go away. + status int32 + + // Whether the Voice Websocket is ready + VoiceReady bool // NOTE: Deprecated. + + // Whether the UDP Connection is ready + UDPReady bool // NOTE: Deprecated + + // Stores a mapping of guild id's to VoiceConnections + VoiceConnections map[string]*VoiceConnection + + // Managed state object, updated internally with events when + // StateEnabled is true. + State *State + + // The http client used for REST requests + Client *http.Client + + // The dialer used for WebSocket connection + Dialer *websocket.Dialer + + // The user agent used for REST APIs + UserAgent string + + // Stores the last HeartbeatAck that was received (in UTC) + LastHeartbeatAck time.Time + + // Stores the last Heartbeat sent (in UTC) + LastHeartbeatSent time.Time + + // used to deal with rate limits + Ratelimiter *RateLimiter + + // Event handlers + handlersMu sync.RWMutex + handlers map[string][]*eventHandlerInstance + onceHandlers map[string][]*eventHandlerInstance + + // The websocket connection. + wsConn *websocket.Conn + + // When nil, the session is not listening. + listening chan interface{} + + // sequence tracks the current gateway api websocket sequence number + sequence *int64 + + // stores sessions current Discord Gateway + gateway string + + // stores session ID of current Gateway connection + sessionID string + + // used to make sure gateway websocket writes do not happen concurrently + wsMutex sync.Mutex +} + +// ApplicationIntegrationType dictates where application can be installed and its available interaction contexts. +type ApplicationIntegrationType uint + +const ( + // ApplicationIntegrationGuildInstall indicates that app is installable to guilds. + ApplicationIntegrationGuildInstall ApplicationIntegrationType = 0 + // ApplicationIntegrationUserInstall indicates that app is installable to users. + ApplicationIntegrationUserInstall ApplicationIntegrationType = 1 +) + +// ApplicationInstallParams represents application's installation parameters +// for default in-app oauth2 authorization link. +type ApplicationInstallParams struct { + Scopes []string `json:"scopes"` + Permissions int64 `json:"permissions,string"` +} + +// ApplicationIntegrationTypeConfig represents application's configuration for a particular integration type. +type ApplicationIntegrationTypeConfig struct { + OAuth2InstallParams *ApplicationInstallParams `json:"oauth2_install_params,omitempty"` +} + +// Application stores values for a Discord Application +type Application struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Icon string `json:"icon,omitempty"` + Description string `json:"description,omitempty"` + RPCOrigins []string `json:"rpc_origins,omitempty"` + BotPublic bool `json:"bot_public,omitempty"` + BotRequireCodeGrant bool `json:"bot_require_code_grant,omitempty"` + TermsOfServiceURL string `json:"terms_of_service_url"` + PrivacyProxyURL string `json:"privacy_policy_url"` + Owner *User `json:"owner"` + Summary string `json:"summary"` + VerifyKey string `json:"verify_key"` + Team *Team `json:"team"` + GuildID string `json:"guild_id"` + PrimarySKUID string `json:"primary_sku_id"` + Slug string `json:"slug"` + CoverImage string `json:"cover_image"` + Flags int `json:"flags,omitempty"` + IntegrationTypesConfig map[ApplicationIntegrationType]*ApplicationIntegrationTypeConfig `json:"integration_types,omitempty"` +} + +// ApplicationRoleConnectionMetadataType represents the type of application role connection metadata. +type ApplicationRoleConnectionMetadataType int + +// Application role connection metadata types. +const ( + ApplicationRoleConnectionMetadataIntegerLessThanOrEqual ApplicationRoleConnectionMetadataType = 1 + ApplicationRoleConnectionMetadataIntegerGreaterThanOrEqual ApplicationRoleConnectionMetadataType = 2 + ApplicationRoleConnectionMetadataIntegerEqual ApplicationRoleConnectionMetadataType = 3 + ApplicationRoleConnectionMetadataIntegerNotEqual ApplicationRoleConnectionMetadataType = 4 + ApplicationRoleConnectionMetadataDatetimeLessThanOrEqual ApplicationRoleConnectionMetadataType = 5 + ApplicationRoleConnectionMetadataDatetimeGreaterThanOrEqual ApplicationRoleConnectionMetadataType = 6 + ApplicationRoleConnectionMetadataBooleanEqual ApplicationRoleConnectionMetadataType = 7 + ApplicationRoleConnectionMetadataBooleanNotEqual ApplicationRoleConnectionMetadataType = 8 +) + +// ApplicationRoleConnectionMetadata stores application role connection metadata. +type ApplicationRoleConnectionMetadata struct { + Type ApplicationRoleConnectionMetadataType `json:"type"` + Key string `json:"key"` + Name string `json:"name"` + NameLocalizations map[Locale]string `json:"name_localizations"` + Description string `json:"description"` + DescriptionLocalizations map[Locale]string `json:"description_localizations"` +} + +// ApplicationRoleConnection represents the role connection that an application has attached to a user. +type ApplicationRoleConnection struct { + PlatformName string `json:"platform_name"` + PlatformUsername string `json:"platform_username"` + Metadata map[string]string `json:"metadata"` +} + +// UserConnection is a Connection returned from the UserConnections endpoint +type UserConnection struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Revoked bool `json:"revoked"` + Integrations []*Integration `json:"integrations"` +} + +// Integration stores integration information +type Integration struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Enabled bool `json:"enabled"` + Syncing bool `json:"syncing"` + RoleID string `json:"role_id"` + EnableEmoticons bool `json:"enable_emoticons"` + ExpireBehavior ExpireBehavior `json:"expire_behavior"` + ExpireGracePeriod int `json:"expire_grace_period"` + User *User `json:"user"` + Account IntegrationAccount `json:"account"` + SyncedAt time.Time `json:"synced_at"` +} + +// ExpireBehavior of Integration +// https://discord.com/developers/docs/resources/guild#integration-object-integration-expire-behaviors +type ExpireBehavior int + +// Block of valid ExpireBehaviors +const ( + ExpireBehaviorRemoveRole ExpireBehavior = 0 + ExpireBehaviorKick ExpireBehavior = 1 +) + +// IntegrationAccount is integration account information +// sent by the UserConnections endpoint +type IntegrationAccount struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// A VoiceRegion stores data for a specific voice region server. +// https://discord.com/developers/docs/resources/voice#voice-region-object +type VoiceRegion struct { + ID string `json:"id"` + Name string `json:"name"` + Optimal bool `json:"optimal"` + Deprecated bool `json:"deprecated"` + Custom bool `json:"custom"` +} + +// InviteTargetType indicates the type of target of an invite +// https://discord.com/developers/docs/resources/invite#invite-object-invite-target-types +type InviteTargetType uint8 + +// Invite target types +const ( + InviteTargetStream InviteTargetType = 1 + InviteTargetEmbeddedApplication InviteTargetType = 2 +) + +// A Invite stores all data related to a specific Discord Guild or Channel invite. +type Invite struct { + Guild *Guild `json:"guild"` + Channel *Channel `json:"channel"` + Inviter *User `json:"inviter"` + Code string `json:"code"` + CreatedAt time.Time `json:"created_at"` + MaxAge int `json:"max_age"` + Uses int `json:"uses"` + MaxUses int `json:"max_uses"` + Revoked bool `json:"revoked"` + Temporary bool `json:"temporary"` + Unique bool `json:"unique"` + TargetUser *User `json:"target_user"` + TargetType InviteTargetType `json:"target_type"` + TargetApplication *Application `json:"target_application"` + + // will only be filled when using InviteWithCounts + ApproximatePresenceCount int `json:"approximate_presence_count"` + ApproximateMemberCount int `json:"approximate_member_count"` + + ExpiresAt *time.Time `json:"expires_at"` +} + +// ChannelType is the type of a Channel +type ChannelType int + +// Block contains known ChannelType values +const ( + ChannelTypeGuildText ChannelType = 0 + ChannelTypeDM ChannelType = 1 + ChannelTypeGuildVoice ChannelType = 2 + ChannelTypeGroupDM ChannelType = 3 + ChannelTypeGuildCategory ChannelType = 4 + ChannelTypeGuildNews ChannelType = 5 + ChannelTypeGuildStore ChannelType = 6 + ChannelTypeGuildNewsThread ChannelType = 10 + ChannelTypeGuildPublicThread ChannelType = 11 + ChannelTypeGuildPrivateThread ChannelType = 12 + ChannelTypeGuildStageVoice ChannelType = 13 + ChannelTypeGuildDirectory ChannelType = 14 + ChannelTypeGuildForum ChannelType = 15 + ChannelTypeGuildMedia ChannelType = 16 +) + +// ChannelFlags represent flags of a channel/thread. +type ChannelFlags int + +// Block containing known ChannelFlags values. +const ( + // ChannelFlagPinned indicates whether the thread is pinned in the forum channel. + // NOTE: forum threads only. + ChannelFlagPinned ChannelFlags = 1 << 1 + // ChannelFlagRequireTag indicates whether a tag is required to be specified when creating a thread. + // NOTE: forum channels only. + ChannelFlagRequireTag ChannelFlags = 1 << 4 +) + +// ForumSortOrderType represents sort order of a forum channel. +type ForumSortOrderType int + +const ( + // ForumSortOrderLatestActivity sorts posts by activity. + ForumSortOrderLatestActivity ForumSortOrderType = 0 + // ForumSortOrderCreationDate sorts posts by creation time (from most recent to oldest). + ForumSortOrderCreationDate ForumSortOrderType = 1 +) + +// ForumLayout represents layout of a forum channel. +type ForumLayout int + +const ( + // ForumLayoutNotSet represents no default layout. + ForumLayoutNotSet ForumLayout = 0 + // ForumLayoutListView displays forum posts as a list. + ForumLayoutListView ForumLayout = 1 + // ForumLayoutGalleryView displays forum posts as a collection of tiles. + ForumLayoutGalleryView ForumLayout = 2 +) + +// A Channel holds all data related to an individual Discord channel. +type Channel struct { + // The ID of the channel. + ID string `json:"id"` + + // The ID of the guild to which the channel belongs, if it is in a guild. + // Else, this ID is empty (e.g. DM channels). + GuildID string `json:"guild_id"` + + // The name of the channel. + Name string `json:"name"` + + // The topic of the channel. + Topic string `json:"topic"` + + // The type of the channel. + Type ChannelType `json:"type"` + + // The ID of the last message sent in the channel. This is not + // guaranteed to be an ID of a valid message. + LastMessageID string `json:"last_message_id"` + + // The timestamp of the last pinned message in the channel. + // nil if the channel has no pinned messages. + LastPinTimestamp *time.Time `json:"last_pin_timestamp"` + + // An approximate count of messages in a thread, stops counting at 50 + MessageCount int `json:"message_count"` + // An approximate count of users in a thread, stops counting at 50 + MemberCount int `json:"member_count"` + + // Whether the channel is marked as NSFW. + NSFW bool `json:"nsfw"` + + // Icon of the group DM channel. + Icon string `json:"icon"` + + // The position of the channel, used for sorting in client. + Position int `json:"position"` + + // The bitrate of the channel, if it is a voice channel. + Bitrate int `json:"bitrate"` + + // The recipients of the channel. This is only populated in DM channels. + Recipients []*User `json:"recipients"` + + // The messages in the channel. This is only present in state-cached channels, + // and State.MaxMessageCount must be non-zero. + Messages []*Message `json:"-"` + + // A list of permission overwrites present for the channel. + PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites"` + + // The user limit of the voice channel. + UserLimit int `json:"user_limit"` + + // The ID of the parent channel, if the channel is under a category. For threads - id of the channel thread was created in. + ParentID string `json:"parent_id"` + + // Amount of seconds a user has to wait before sending another message or creating another thread (0-21600) + // bots, as well as users with the permission manage_messages or manage_channel, are unaffected + RateLimitPerUser int `json:"rate_limit_per_user"` + + // ID of the creator of the group DM or thread + OwnerID string `json:"owner_id"` + + // ApplicationID of the DM creator Zeroed if guild channel or not a bot user + ApplicationID string `json:"application_id"` + + // Thread-specific fields not needed by other channels + ThreadMetadata *ThreadMetadata `json:"thread_metadata,omitempty"` + // Thread member object for the current user, if they have joined the thread, only included on certain API endpoints + Member *ThreadMember `json:"thread_member"` + + // All thread members. State channels only. + Members []*ThreadMember `json:"-"` + + // Channel flags. + Flags ChannelFlags `json:"flags"` + + // The set of tags that can be used in a forum channel. + AvailableTags []ForumTag `json:"available_tags"` + + // The IDs of the set of tags that have been applied to a thread in a forum channel. + AppliedTags []string `json:"applied_tags"` + + // Emoji to use as the default reaction to a forum post. + DefaultReactionEmoji ForumDefaultReaction `json:"default_reaction_emoji"` + + // The initial RateLimitPerUser to set on newly created threads in a channel. + // This field is copied to the thread at creation time and does not live update. + DefaultThreadRateLimitPerUser int `json:"default_thread_rate_limit_per_user"` + + // The default sort order type used to order posts in forum channels. + // Defaults to null, which indicates a preferred sort order hasn't been set by a channel admin. + DefaultSortOrder *ForumSortOrderType `json:"default_sort_order"` + + // The default forum layout view used to display posts in forum channels. + // Defaults to ForumLayoutNotSet, which indicates a layout view has not been set by a channel admin. + DefaultForumLayout ForumLayout `json:"default_forum_layout"` +} + +// Mention returns a string which mentions the channel +func (c *Channel) Mention() string { + return fmt.Sprintf("<#%s>", c.ID) +} + +// IsThread is a helper function to determine if channel is a thread or not +func (c *Channel) IsThread() bool { + return c.Type == ChannelTypeGuildPublicThread || c.Type == ChannelTypeGuildPrivateThread || c.Type == ChannelTypeGuildNewsThread +} + +// A ChannelEdit holds Channel Field data for a channel edit. +type ChannelEdit struct { + Name string `json:"name,omitempty"` + Topic string `json:"topic,omitempty"` + NSFW *bool `json:"nsfw,omitempty"` + Position *int `json:"position,omitempty"` + Bitrate int `json:"bitrate,omitempty"` + UserLimit int `json:"user_limit,omitempty"` + PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"` + ParentID string `json:"parent_id,omitempty"` + RateLimitPerUser *int `json:"rate_limit_per_user,omitempty"` + Flags *ChannelFlags `json:"flags,omitempty"` + DefaultThreadRateLimitPerUser *int `json:"default_thread_rate_limit_per_user,omitempty"` + + // NOTE: threads only + + Archived *bool `json:"archived,omitempty"` + AutoArchiveDuration int `json:"auto_archive_duration,omitempty"` + Locked *bool `json:"locked,omitempty"` + Invitable *bool `json:"invitable,omitempty"` + + // NOTE: forum channels only + + AvailableTags *[]ForumTag `json:"available_tags,omitempty"` + DefaultReactionEmoji *ForumDefaultReaction `json:"default_reaction_emoji,omitempty"` + DefaultSortOrder *ForumSortOrderType `json:"default_sort_order,omitempty"` // TODO: null + DefaultForumLayout *ForumLayout `json:"default_forum_layout,omitempty"` + + // NOTE: forum threads only + AppliedTags *[]string `json:"applied_tags,omitempty"` +} + +// A ChannelFollow holds data returned after following a news channel +type ChannelFollow struct { + ChannelID string `json:"channel_id"` + WebhookID string `json:"webhook_id"` +} + +// PermissionOverwriteType represents the type of resource on which +// a permission overwrite acts. +type PermissionOverwriteType int + +// The possible permission overwrite types. +const ( + PermissionOverwriteTypeRole PermissionOverwriteType = 0 + PermissionOverwriteTypeMember PermissionOverwriteType = 1 +) + +// A PermissionOverwrite holds permission overwrite data for a Channel +type PermissionOverwrite struct { + ID string `json:"id"` + Type PermissionOverwriteType `json:"type"` + Deny int64 `json:"deny,string"` + Allow int64 `json:"allow,string"` +} + +// ThreadStart stores all parameters you can use with MessageThreadStartComplex or ThreadStartComplex +type ThreadStart struct { + Name string `json:"name"` + AutoArchiveDuration int `json:"auto_archive_duration,omitempty"` + Type ChannelType `json:"type,omitempty"` + Invitable bool `json:"invitable"` + RateLimitPerUser int `json:"rate_limit_per_user,omitempty"` + + // NOTE: forum threads only + AppliedTags []string `json:"applied_tags,omitempty"` +} + +// ThreadMetadata contains a number of thread-specific channel fields that are not needed by other channel types. +type ThreadMetadata struct { + // Whether the thread is archived + Archived bool `json:"archived"` + // Duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 + AutoArchiveDuration int `json:"auto_archive_duration"` + // Timestamp when the thread's archive status was last changed, used for calculating recent activity + ArchiveTimestamp time.Time `json:"archive_timestamp"` + // Whether the thread is locked; when a thread is locked, only users with MANAGE_THREADS can unarchive it + Locked bool `json:"locked"` + // Whether non-moderators can add other non-moderators to a thread; only available on private threads + Invitable bool `json:"invitable"` +} + +// ThreadMember is used to indicate whether a user has joined a thread or not. +// NOTE: ID and UserID are empty (omitted) on the member sent within each thread in the GUILD_CREATE event. +type ThreadMember struct { + // The id of the thread + ID string `json:"id,omitempty"` + // The id of the user + UserID string `json:"user_id,omitempty"` + // The time the current user last joined the thread + JoinTimestamp time.Time `json:"join_timestamp"` + // Any user-thread settings, currently only used for notifications + Flags int `json:"flags"` + // Additional information about the user. + // NOTE: only present if the withMember parameter is set to true + // when calling Session.ThreadMembers or Session.ThreadMember. + Member *Member `json:"member,omitempty"` +} + +// ThreadsList represents a list of threads alongisde with thread member objects for the current user. +type ThreadsList struct { + Threads []*Channel `json:"threads"` + Members []*ThreadMember `json:"members"` + HasMore bool `json:"has_more"` +} + +// AddedThreadMember holds information about the user who was added to the thread +type AddedThreadMember struct { + *ThreadMember + Member *Member `json:"member"` + Presence *Presence `json:"presence"` +} + +// ForumDefaultReaction specifies emoji to use as the default reaction to a forum post. +// NOTE: Exactly one of EmojiID and EmojiName must be set. +type ForumDefaultReaction struct { + // The id of a guild's custom emoji. + EmojiID string `json:"emoji_id,omitempty"` + // The unicode character of the emoji. + EmojiName string `json:"emoji_name,omitempty"` +} + +// ForumTag represents a tag that is able to be applied to a thread in a forum channel. +type ForumTag struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Moderated bool `json:"moderated"` + EmojiID string `json:"emoji_id,omitempty"` + EmojiName string `json:"emoji_name,omitempty"` +} + +// Emoji struct holds data related to Emoji's +type Emoji struct { + ID string `json:"id"` + Name string `json:"name"` + Roles []string `json:"roles"` + User *User `json:"user"` + RequireColons bool `json:"require_colons"` + Managed bool `json:"managed"` + Animated bool `json:"animated"` + Available bool `json:"available"` +} + +// EmojiRegex is the regex used to find and identify emojis in messages +var ( + EmojiRegex = regexp.MustCompile(`<(a|):[A-Za-z0-9_~]+:[0-9]{18,20}>`) +) + +// MessageFormat returns a correctly formatted Emoji for use in Message content and embeds +func (e *Emoji) MessageFormat() string { + if e.ID != "" && e.Name != "" { + if e.Animated { + return "" + } + + return "<:" + e.APIName() + ">" + } + + return e.APIName() +} + +// APIName returns an correctly formatted API name for use in the MessageReactions endpoints. +func (e *Emoji) APIName() string { + if e.ID != "" && e.Name != "" { + return e.Name + ":" + e.ID + } + if e.Name != "" { + return e.Name + } + return e.ID +} + +// EmojiParams represents parameters needed to create or update an Emoji. +type EmojiParams struct { + // Name of the emoji + Name string `json:"name,omitempty"` + // A base64 encoded emoji image, has to be smaller than 256KB. + // NOTE: can be only set on creation. + Image string `json:"image,omitempty"` + // Roles for which this emoji will be available. + // NOTE: can not be used with application emoji endpoints. + Roles []string `json:"roles,omitempty"` +} + +// StickerFormat is the file format of the Sticker. +type StickerFormat int + +// Defines all known Sticker types. +const ( + StickerFormatTypePNG StickerFormat = 1 + StickerFormatTypeAPNG StickerFormat = 2 + StickerFormatTypeLottie StickerFormat = 3 + StickerFormatTypeGIF StickerFormat = 4 +) + +// StickerType is the type of sticker. +type StickerType int + +// Defines Sticker types. +const ( + StickerTypeStandard StickerType = 1 + StickerTypeGuild StickerType = 2 +) + +// Sticker represents a sticker object that can be sent in a Message. +type Sticker struct { + ID string `json:"id"` + PackID string `json:"pack_id"` + Name string `json:"name"` + Description string `json:"description"` + Tags string `json:"tags"` + Type StickerType `json:"type"` + FormatType StickerFormat `json:"format_type"` + Available bool `json:"available"` + GuildID string `json:"guild_id"` + User *User `json:"user"` + SortValue int `json:"sort_value"` +} + +// StickerItem represents the smallest amount of data required to render a sticker. A partial sticker object. +type StickerItem struct { + ID string `json:"id"` + Name string `json:"name"` + FormatType StickerFormat `json:"format_type"` +} + +// StickerPack represents a pack of standard stickers. +type StickerPack struct { + ID string `json:"id"` + Stickers []*Sticker `json:"stickers"` + Name string `json:"name"` + SKUID string `json:"sku_id"` + CoverStickerID string `json:"cover_sticker_id"` + Description string `json:"description"` + BannerAssetID string `json:"banner_asset_id"` +} + +// VerificationLevel type definition +type VerificationLevel int + +// Constants for VerificationLevel levels from 0 to 4 inclusive +const ( + VerificationLevelNone VerificationLevel = 0 + VerificationLevelLow VerificationLevel = 1 + VerificationLevelMedium VerificationLevel = 2 + VerificationLevelHigh VerificationLevel = 3 + VerificationLevelVeryHigh VerificationLevel = 4 +) + +// ExplicitContentFilterLevel type definition +type ExplicitContentFilterLevel int + +// Constants for ExplicitContentFilterLevel levels from 0 to 2 inclusive +const ( + ExplicitContentFilterDisabled ExplicitContentFilterLevel = 0 + ExplicitContentFilterMembersWithoutRoles ExplicitContentFilterLevel = 1 + ExplicitContentFilterAllMembers ExplicitContentFilterLevel = 2 +) + +// GuildNSFWLevel type definition +type GuildNSFWLevel int + +// Constants for GuildNSFWLevel levels from 0 to 3 inclusive +const ( + GuildNSFWLevelDefault GuildNSFWLevel = 0 + GuildNSFWLevelExplicit GuildNSFWLevel = 1 + GuildNSFWLevelSafe GuildNSFWLevel = 2 + GuildNSFWLevelAgeRestricted GuildNSFWLevel = 3 +) + +// MfaLevel type definition +type MfaLevel int + +// Constants for MfaLevel levels from 0 to 1 inclusive +const ( + MfaLevelNone MfaLevel = 0 + MfaLevelElevated MfaLevel = 1 +) + +// PremiumTier type definition +type PremiumTier int + +// Constants for PremiumTier levels from 0 to 3 inclusive +const ( + PremiumTierNone PremiumTier = 0 + PremiumTier1 PremiumTier = 1 + PremiumTier2 PremiumTier = 2 + PremiumTier3 PremiumTier = 3 +) + +// A Guild holds all data related to a specific Discord Guild. Guilds are also +// sometimes referred to as Servers in the Discord client. +type Guild struct { + // The ID of the guild. + ID string `json:"id"` + + // The name of the guild. (2–100 characters) + Name string `json:"name"` + + // The hash of the guild's icon. Use Session.GuildIcon + // to retrieve the icon itself. + Icon string `json:"icon"` + + // The voice region of the guild. + Region string `json:"region"` + + // The ID of the AFK voice channel. + AfkChannelID string `json:"afk_channel_id"` + + // The user ID of the owner of the guild. + OwnerID string `json:"owner_id"` + + // If we are the owner of the guild + Owner bool `json:"owner"` + + // The time at which the current user joined the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + JoinedAt time.Time `json:"joined_at"` + + // The hash of the guild's discovery splash. + DiscoverySplash string `json:"discovery_splash"` + + // The hash of the guild's splash. + Splash string `json:"splash"` + + // The timeout, in seconds, before a user is considered AFK in voice. + AfkTimeout int `json:"afk_timeout"` + + // The number of members in the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + MemberCount int `json:"member_count"` + + // The verification level required for the guild. + VerificationLevel VerificationLevel `json:"verification_level"` + + // Whether the guild is considered large. This is + // determined by a member threshold in the identify packet, + // and is currently hard-coded at 250 members in the library. + Large bool `json:"large"` + + // The default message notification setting for the guild. + DefaultMessageNotifications MessageNotifications `json:"default_message_notifications"` + + // A list of roles in the guild. + Roles []*Role `json:"roles"` + + // A list of the custom emojis present in the guild. + Emojis []*Emoji `json:"emojis"` + + // A list of the custom stickers present in the guild. + Stickers []*Sticker `json:"stickers"` + + // A list of the members in the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + Members []*Member `json:"members"` + + // A list of partial presence objects for members in the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + Presences []*Presence `json:"presences"` + + // The maximum number of presences for the guild (the default value, currently 25000, is in effect when null is returned) + MaxPresences int `json:"max_presences"` + + // The maximum number of members for the guild + MaxMembers int `json:"max_members"` + + // A list of channels in the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + Channels []*Channel `json:"channels"` + + // A list of all active threads in the guild that current user has permission to view + // This field is only present in GUILD_CREATE events and websocket + // update events and thus is only present in state-cached guilds. + Threads []*Channel `json:"threads"` + + // A list of voice states for the guild. + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + VoiceStates []*VoiceState `json:"voice_states"` + + // Whether this guild is currently unavailable (most likely due to outage). + // This field is only present in GUILD_CREATE events and websocket + // update events, and thus is only present in state-cached guilds. + Unavailable bool `json:"unavailable"` + + // The explicit content filter level + ExplicitContentFilter ExplicitContentFilterLevel `json:"explicit_content_filter"` + + // The NSFW Level of the guild + NSFWLevel GuildNSFWLevel `json:"nsfw_level"` + + // The list of enabled guild features + Features []GuildFeature `json:"features"` + + // Required MFA level for the guild + MfaLevel MfaLevel `json:"mfa_level"` + + // The application id of the guild if bot created. + ApplicationID string `json:"application_id"` + + // Whether or not the Server Widget is enabled + WidgetEnabled bool `json:"widget_enabled"` + + // The Channel ID for the Server Widget + WidgetChannelID string `json:"widget_channel_id"` + + // The Channel ID to which system messages are sent (eg join and leave messages) + SystemChannelID string `json:"system_channel_id"` + + // The System channel flags + SystemChannelFlags SystemChannelFlag `json:"system_channel_flags"` + + // The ID of the rules channel ID, used for rules. + RulesChannelID string `json:"rules_channel_id"` + + // the vanity url code for the guild + VanityURLCode string `json:"vanity_url_code"` + + // the description for the guild + Description string `json:"description"` + + // The hash of the guild's banner + Banner string `json:"banner"` + + // The premium tier of the guild + PremiumTier PremiumTier `json:"premium_tier"` + + // The total number of users currently boosting this server + PremiumSubscriptionCount int `json:"premium_subscription_count"` + + // The preferred locale of a guild with the "PUBLIC" feature; used in server discovery and notices from Discord; defaults to "en-US" + PreferredLocale string `json:"preferred_locale"` + + // The id of the channel where admins and moderators of guilds with the "PUBLIC" feature receive notices from Discord + PublicUpdatesChannelID string `json:"public_updates_channel_id"` + + // The maximum amount of users in a video channel + MaxVideoChannelUsers int `json:"max_video_channel_users"` + + // Approximate number of members in this guild, returned from the GET /guild/ endpoint when with_counts is true + ApproximateMemberCount int `json:"approximate_member_count"` + + // Approximate number of non-offline members in this guild, returned from the GET /guild/ endpoint when with_counts is true + ApproximatePresenceCount int `json:"approximate_presence_count"` + + // Permissions of our user + Permissions int64 `json:"permissions,string"` + + // Stage instances in the guild + StageInstances []*StageInstance `json:"stage_instances"` +} + +// A GuildPreview holds data related to a specific public Discord Guild, even if the user is not in the guild. +type GuildPreview struct { + // The ID of the guild. + ID string `json:"id"` + + // The name of the guild. (2–100 characters) + Name string `json:"name"` + + // The hash of the guild's icon. Use Session.GuildIcon + // to retrieve the icon itself. + Icon string `json:"icon"` + + // The hash of the guild's splash. + Splash string `json:"splash"` + + // The hash of the guild's discovery splash. + DiscoverySplash string `json:"discovery_splash"` + + // A list of the custom emojis present in the guild. + Emojis []*Emoji `json:"emojis"` + + // The list of enabled guild features + Features []string `json:"features"` + + // Approximate number of members in this guild + // NOTE: this field is only filled when using GuildWithCounts + ApproximateMemberCount int `json:"approximate_member_count"` + + // Approximate number of non-offline members in this guild + // NOTE: this field is only filled when using GuildWithCounts + ApproximatePresenceCount int `json:"approximate_presence_count"` + + // the description for the guild + Description string `json:"description"` +} + +// IconURL returns a URL to the guild's icon. +// +// size: The size of the desired icon image as a power of two +// Image size can be any power of two between 16 and 4096. +func (g *GuildPreview) IconURL(size string) string { + return iconURL(g.Icon, EndpointGuildIcon(g.ID, g.Icon), EndpointGuildIconAnimated(g.ID, g.Icon), size) +} + +// GuildScheduledEvent is a representation of a scheduled event in a guild. Only for retrieval of the data. +// https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event +type GuildScheduledEvent struct { + // The ID of the scheduled event + ID string `json:"id"` + // The guild id which the scheduled event belongs to + GuildID string `json:"guild_id"` + // The channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL + ChannelID string `json:"channel_id"` + // The id of the user that created the scheduled event + CreatorID string `json:"creator_id"` + // The name of the scheduled event (1-100 characters) + Name string `json:"name"` + // The description of the scheduled event (1-1000 characters) + Description string `json:"description"` + // The time the scheduled event will start + ScheduledStartTime time.Time `json:"scheduled_start_time"` + // The time the scheduled event will end, required only when entity_type is EXTERNAL + ScheduledEndTime *time.Time `json:"scheduled_end_time"` + // The privacy level of the scheduled event + PrivacyLevel GuildScheduledEventPrivacyLevel `json:"privacy_level"` + // The status of the scheduled event + Status GuildScheduledEventStatus `json:"status"` + // Type of the entity where event would be hosted + // See field requirements + // https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-field-requirements-by-entity-type + EntityType GuildScheduledEventEntityType `json:"entity_type"` + // The id of an entity associated with a guild scheduled event + EntityID string `json:"entity_id"` + // Additional metadata for the guild scheduled event + EntityMetadata GuildScheduledEventEntityMetadata `json:"entity_metadata"` + // The user that created the scheduled event + Creator *User `json:"creator"` + // The number of users subscribed to the scheduled event + UserCount int `json:"user_count"` + // The cover image hash of the scheduled event + // see https://discord.com/developers/docs/reference#image-formatting for more + // information about image formatting + Image string `json:"image"` +} + +// GuildScheduledEventParams are the parameters allowed for creating or updating a scheduled event +// https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event +type GuildScheduledEventParams struct { + // The channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL + ChannelID string `json:"channel_id,omitempty"` + // The name of the scheduled event (1-100 characters) + Name string `json:"name,omitempty"` + // The description of the scheduled event (1-1000 characters) + Description string `json:"description,omitempty"` + // The time the scheduled event will start + ScheduledStartTime *time.Time `json:"scheduled_start_time,omitempty"` + // The time the scheduled event will end, required only when entity_type is EXTERNAL + ScheduledEndTime *time.Time `json:"scheduled_end_time,omitempty"` + // The privacy level of the scheduled event + PrivacyLevel GuildScheduledEventPrivacyLevel `json:"privacy_level,omitempty"` + // The status of the scheduled event + Status GuildScheduledEventStatus `json:"status,omitempty"` + // Type of the entity where event would be hosted + // See field requirements + // https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-field-requirements-by-entity-type + EntityType GuildScheduledEventEntityType `json:"entity_type,omitempty"` + // Additional metadata for the guild scheduled event + EntityMetadata *GuildScheduledEventEntityMetadata `json:"entity_metadata,omitempty"` + // The cover image hash of the scheduled event + // see https://discord.com/developers/docs/reference#image-formatting for more + // information about image formatting + Image string `json:"image,omitempty"` +} + +// MarshalJSON is a helper function to marshal GuildScheduledEventParams +func (p GuildScheduledEventParams) MarshalJSON() ([]byte, error) { + type guildScheduledEventParams GuildScheduledEventParams + + if p.EntityType == GuildScheduledEventEntityTypeExternal && p.ChannelID == "" { + return Marshal(struct { + guildScheduledEventParams + ChannelID json.RawMessage `json:"channel_id"` + }{ + guildScheduledEventParams: guildScheduledEventParams(p), + ChannelID: json.RawMessage("null"), + }) + } + + return Marshal(guildScheduledEventParams(p)) +} + +// GuildScheduledEventEntityMetadata holds additional metadata for guild scheduled event. +type GuildScheduledEventEntityMetadata struct { + // location of the event (1-100 characters) + // required for events with 'entity_type': EXTERNAL + Location string `json:"location"` +} + +// GuildScheduledEventPrivacyLevel is the privacy level of a scheduled event. +// https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-privacy-level +type GuildScheduledEventPrivacyLevel int + +const ( + // GuildScheduledEventPrivacyLevelGuildOnly makes the scheduled + // event is only accessible to guild members + GuildScheduledEventPrivacyLevelGuildOnly GuildScheduledEventPrivacyLevel = 2 +) + +// GuildScheduledEventStatus is the status of a scheduled event +// Valid Guild Scheduled Event Status Transitions : +// SCHEDULED --> ACTIVE --> COMPLETED +// SCHEDULED --> CANCELED +// https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-status +type GuildScheduledEventStatus int + +const ( + // GuildScheduledEventStatusScheduled represents the current event is in scheduled state + GuildScheduledEventStatusScheduled GuildScheduledEventStatus = 1 + // GuildScheduledEventStatusActive represents the current event is in active state + GuildScheduledEventStatusActive GuildScheduledEventStatus = 2 + // GuildScheduledEventStatusCompleted represents the current event is in completed state + GuildScheduledEventStatusCompleted GuildScheduledEventStatus = 3 + // GuildScheduledEventStatusCanceled represents the current event is in canceled state + GuildScheduledEventStatusCanceled GuildScheduledEventStatus = 4 +) + +// GuildScheduledEventEntityType is the type of entity associated with a guild scheduled event. +// https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-types +type GuildScheduledEventEntityType int + +const ( + // GuildScheduledEventEntityTypeStageInstance represents a stage channel + GuildScheduledEventEntityTypeStageInstance GuildScheduledEventEntityType = 1 + // GuildScheduledEventEntityTypeVoice represents a voice channel + GuildScheduledEventEntityTypeVoice GuildScheduledEventEntityType = 2 + // GuildScheduledEventEntityTypeExternal represents an external event + GuildScheduledEventEntityTypeExternal GuildScheduledEventEntityType = 3 +) + +// GuildScheduledEventUser is a user subscribed to a scheduled event. +// https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-user-object +type GuildScheduledEventUser struct { + GuildScheduledEventID string `json:"guild_scheduled_event_id"` + User *User `json:"user"` + Member *Member `json:"member"` +} + +// GuildOnboardingMode defines the criteria used to satisfy constraints that are required for enabling onboarding. +// https://discord.com/developers/docs/resources/guild#guild-onboarding-object-onboarding-mode +type GuildOnboardingMode int + +// Block containing known GuildOnboardingMode values. +const ( + // GuildOnboardingModeDefault counts default channels towards constraints. + GuildOnboardingModeDefault GuildOnboardingMode = 0 + // GuildOnboardingModeAdvanced counts default channels and questions towards constraints. + GuildOnboardingModeAdvanced GuildOnboardingMode = 1 +) + +// GuildOnboarding represents the onboarding flow for a guild. +// https://discord.com/developers/docs/resources/guild#guild-onboarding-object +type GuildOnboarding struct { + // ID of the guild this onboarding flow is part of. + GuildID string `json:"guild_id,omitempty"` + + // Prompts shown during onboarding and in the customize community (Channels & Roles) tab. + Prompts *[]GuildOnboardingPrompt `json:"prompts,omitempty"` + + // Channel IDs that members get opted into automatically. + DefaultChannelIDs []string `json:"default_channel_ids,omitempty"` + + // Whether onboarding is enabled in the guild. + Enabled *bool `json:"enabled,omitempty"` + + // Mode of onboarding. + Mode *GuildOnboardingMode `json:"mode,omitempty"` +} + +// GuildOnboardingPromptType is the type of an onboarding prompt. +// https://discord.com/developers/docs/resources/guild#guild-onboarding-object-prompt-types +type GuildOnboardingPromptType int + +// Block containing known GuildOnboardingPromptType values. +const ( + GuildOnboardingPromptTypeMultipleChoice GuildOnboardingPromptType = 0 + GuildOnboardingPromptTypeDropdown GuildOnboardingPromptType = 1 +) + +// GuildOnboardingPrompt is a prompt shown during onboarding and in the customize community (Channels & Roles) tab. +// https://discord.com/developers/docs/resources/guild#guild-onboarding-object-onboarding-prompt-structure +type GuildOnboardingPrompt struct { + // ID of the prompt. + // NOTE: always requires to be a valid snowflake (e.g. "0"), see + // https://github.com/discord/discord-api-docs/issues/6320 for more information. + ID string `json:"id,omitempty"` + + // Type of the prompt. + Type GuildOnboardingPromptType `json:"type"` + + // Options available within the prompt. + Options []GuildOnboardingPromptOption `json:"options"` + + // Title of the prompt. + Title string `json:"title"` + + // Indicates whether users are limited to selecting one option for the prompt. + SingleSelect bool `json:"single_select"` + + // Indicates whether the prompt is required before a user completes the onboarding flow. + Required bool `json:"required"` + + // Indicates whether the prompt is present in the onboarding flow. + // If false, the prompt will only appear in the customize community (Channels & Roles) tab. + InOnboarding bool `json:"in_onboarding"` +} + +// GuildOnboardingPromptOption is an option available within an onboarding prompt. +// https://discord.com/developers/docs/resources/guild#guild-onboarding-object-prompt-option-structure +type GuildOnboardingPromptOption struct { + // ID of the prompt option. + ID string `json:"id,omitempty"` + + // IDs for channels a member is added to when the option is selected. + ChannelIDs []string `json:"channel_ids"` + + // IDs for roles assigned to a member when the option is selected. + RoleIDs []string `json:"role_ids"` + + // Emoji of the option. + // NOTE: when creating or updating a prompt option + // EmojiID, EmojiName and EmojiAnimated should be used instead. + Emoji *Emoji `json:"emoji,omitempty"` + + // Title of the option. + Title string `json:"title"` + + // Description of the option. + Description string `json:"description"` + + // ID of the option's emoji. + // NOTE: only used when creating or updating a prompt option. + EmojiID string `json:"emoji_id,omitempty"` + // Name of the option's emoji. + // NOTE: only used when creating or updating a prompt option. + EmojiName string `json:"emoji_name,omitempty"` + // Whether the option's emoji is animated. + // NOTE: only used when creating or updating a prompt option. + EmojiAnimated *bool `json:"emoji_animated,omitempty"` +} + +// A GuildTemplate represents a replicable template for guild creation +type GuildTemplate struct { + // The unique code for the guild template + Code string `json:"code"` + + // The name of the template + Name string `json:"name,omitempty"` + + // The description for the template + Description *string `json:"description,omitempty"` + + // The number of times this template has been used + UsageCount int `json:"usage_count"` + + // The ID of the user who created the template + CreatorID string `json:"creator_id"` + + // The user who created the template + Creator *User `json:"creator"` + + // The timestamp of when the template was created + CreatedAt time.Time `json:"created_at"` + + // The timestamp of when the template was last synced + UpdatedAt time.Time `json:"updated_at"` + + // The ID of the guild the template was based on + SourceGuildID string `json:"source_guild_id"` + + // The guild 'snapshot' this template contains + SerializedSourceGuild *Guild `json:"serialized_source_guild"` + + // Whether the template has unsynced changes + IsDirty bool `json:"is_dirty"` +} + +// GuildTemplateParams stores the data needed to create or update a GuildTemplate. +type GuildTemplateParams struct { + // The name of the template (1-100 characters) + Name string `json:"name,omitempty"` + // The description of the template (0-120 characters) + Description string `json:"description,omitempty"` +} + +// MessageNotifications is the notification level for a guild +// https://discord.com/developers/docs/resources/guild#guild-object-default-message-notification-level +type MessageNotifications int + +// Block containing known MessageNotifications values +const ( + MessageNotificationsAllMessages MessageNotifications = 0 + MessageNotificationsOnlyMentions MessageNotifications = 1 +) + +// SystemChannelFlag is the type of flags in the system channel (see SystemChannelFlag* consts) +// https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags +type SystemChannelFlag int + +// Block containing known SystemChannelFlag values +const ( + SystemChannelFlagsSuppressJoinNotifications SystemChannelFlag = 1 << 0 + SystemChannelFlagsSuppressPremium SystemChannelFlag = 1 << 1 + SystemChannelFlagsSuppressGuildReminderNotifications SystemChannelFlag = 1 << 2 + SystemChannelFlagsSuppressJoinNotificationReplies SystemChannelFlag = 1 << 3 +) + +// IconURL returns a URL to the guild's icon. +// +// size: The size of the desired icon image as a power of two +// Image size can be any power of two between 16 and 4096. +func (g *Guild) IconURL(size string) string { + return iconURL(g.Icon, EndpointGuildIcon(g.ID, g.Icon), EndpointGuildIconAnimated(g.ID, g.Icon), size) +} + +// BannerURL returns a URL to the guild's banner. +// +// size: The size of the desired banner image as a power of two +// Image size can be any power of two between 16 and 4096. +func (g *Guild) BannerURL(size string) string { + return bannerURL(g.Banner, EndpointGuildBanner(g.ID, g.Banner), EndpointGuildBannerAnimated(g.ID, g.Banner), size) +} + +// A UserGuild holds a brief version of a Guild +type UserGuild struct { + ID string `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + Owner bool `json:"owner"` + Permissions int64 `json:"permissions,string"` + Features []GuildFeature `json:"features"` + + // Approximate number of members in this guild. + // NOTE: this field is only filled when withCounts is true. + ApproximateMemberCount int `json:"approximate_member_count"` + + // Approximate number of non-offline members in this guild. + // NOTE: this field is only filled when withCounts is true. + ApproximatePresenceCount int `json:"approximate_presence_count"` +} + +// GuildFeature indicates the presence of a feature in a guild +type GuildFeature string + +// Constants for GuildFeature +const ( + GuildFeatureAnimatedBanner GuildFeature = "ANIMATED_BANNER" + GuildFeatureAnimatedIcon GuildFeature = "ANIMATED_ICON" + GuildFeatureApplicationCommandPermissionV2 GuildFeature = "APPLICATION_COMMAND_PERMISSIONS_V2" + GuildFeatureAutoModeration GuildFeature = "AUTO_MODERATION" + GuildFeatureBanner GuildFeature = "BANNER" + GuildFeatureCommunity GuildFeature = "COMMUNITY" + GuildFeatureCreatorMonetizableProvisional GuildFeature = "CREATOR_MONETIZABLE_PROVISIONAL" + GuildFeatureCreatorStorePage GuildFeature = "CREATOR_STORE_PAGE" + GuildFeatureDeveloperSupportServer GuildFeature = "DEVELOPER_SUPPORT_SERVER" + GuildFeatureDiscoverable GuildFeature = "DISCOVERABLE" + GuildFeatureFeaturable GuildFeature = "FEATURABLE" + GuildFeatureInvitesDisabled GuildFeature = "INVITES_DISABLED" + GuildFeatureInviteSplash GuildFeature = "INVITE_SPLASH" + GuildFeatureMemberVerificationGateEnabled GuildFeature = "MEMBER_VERIFICATION_GATE_ENABLED" + GuildFeatureMoreSoundboard GuildFeature = "MORE_SOUNDBOARD" + GuildFeatureMoreStickers GuildFeature = "MORE_STICKERS" + GuildFeatureNews GuildFeature = "NEWS" + GuildFeaturePartnered GuildFeature = "PARTNERED" + GuildFeaturePreviewEnabled GuildFeature = "PREVIEW_ENABLED" + GuildFeatureRaidAlertsDisabled GuildFeature = "RAID_ALERTS_DISABLED" + GuildFeatureRoleIcons GuildFeature = "ROLE_ICONS" + GuildFeatureRoleSubscriptionsAvailableForPurchase GuildFeature = "ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE" + GuildFeatureRoleSubscriptionsEnabled GuildFeature = "ROLE_SUBSCRIPTIONS_ENABLED" + GuildFeatureSoundboard GuildFeature = "SOUNDBOARD" + GuildFeatureTicketedEventsEnabled GuildFeature = "TICKETED_EVENTS_ENABLED" + GuildFeatureVanityURL GuildFeature = "VANITY_URL" + GuildFeatureVerified GuildFeature = "VERIFIED" + GuildFeatureVipRegions GuildFeature = "VIP_REGIONS" + GuildFeatureWelcomeScreenEnabled GuildFeature = "WELCOME_SCREEN_ENABLED" +) + +// A GuildParams stores all the data needed to update discord guild settings +type GuildParams struct { + Name string `json:"name,omitempty"` + Region string `json:"region,omitempty"` + VerificationLevel *VerificationLevel `json:"verification_level,omitempty"` + DefaultMessageNotifications int `json:"default_message_notifications,omitempty"` // TODO: Separate type? + ExplicitContentFilter int `json:"explicit_content_filter,omitempty"` + AfkChannelID string `json:"afk_channel_id,omitempty"` + AfkTimeout int `json:"afk_timeout,omitempty"` + Icon string `json:"icon,omitempty"` + OwnerID string `json:"owner_id,omitempty"` + Splash string `json:"splash,omitempty"` + DiscoverySplash string `json:"discovery_splash,omitempty"` + Banner string `json:"banner,omitempty"` + SystemChannelID string `json:"system_channel_id,omitempty"` + SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` + RulesChannelID string `json:"rules_channel_id,omitempty"` + PublicUpdatesChannelID string `json:"public_updates_channel_id,omitempty"` + PreferredLocale Locale `json:"preferred_locale,omitempty"` + Features []GuildFeature `json:"features,omitempty"` + Description string `json:"description,omitempty"` + PremiumProgressBarEnabled *bool `json:"premium_progress_bar_enabled,omitempty"` +} + +// A Role stores information about Discord guild member roles. +type Role struct { + // The ID of the role. + ID string `json:"id"` + + // The name of the role. + Name string `json:"name"` + + // Whether this role is managed by an integration, and + // thus cannot be manually added to, or taken from, members. + Managed bool `json:"managed"` + + // Whether this role is mentionable. + Mentionable bool `json:"mentionable"` + + // Whether this role is hoisted (shows up separately in member list). + Hoist bool `json:"hoist"` + + // The hex color of this role. + Color int `json:"color"` + + // The position of this role in the guild's role hierarchy. + Position int `json:"position"` + + // The permissions of the role on the guild (doesn't include channel overrides). + // This is a combination of bit masks; the presence of a certain permission can + // be checked by performing a bitwise AND between this int and the permission. + Permissions int64 `json:"permissions,string"` + + // The hash of the role icon. Use Role.IconURL to retrieve the icon's URL. + Icon string `json:"icon"` + + // The emoji assigned to this role. + UnicodeEmoji string `json:"unicode_emoji"` + + // The flags of the role, which describe its extra features. + // This is a combination of bit masks; the presence of a certain flag can + // be checked by performing a bitwise AND between this int and the flag. + Flags RoleFlags `json:"flags"` +} + +// RoleFlags represent the flags of a Role. +// https://discord.com/developers/docs/topics/permissions#role-object-role-flags +type RoleFlags int + +// Block containing known RoleFlags values. +const ( + // RoleFlagInPrompt indicates whether the Role is selectable by members in an onboarding prompt. + RoleFlagInPrompt RoleFlags = 1 << 0 +) + +// Mention returns a string which mentions the role +func (r *Role) Mention() string { + return fmt.Sprintf("<@&%s>", r.ID) +} + +// IconURL returns the URL of the role's icon. +// +// size: The size of the desired role icon as a power of two +// Image size can be any power of two between 16 and 4096. +func (r *Role) IconURL(size string) string { + if r.Icon == "" { + return "" + } + + URL := EndpointRoleIcon(r.ID, r.Icon) + + if size != "" { + return URL + "?size=" + size + } + return URL +} + +// RoleParams represents the parameters needed to create or update a Role +type RoleParams struct { + // The role's name + Name string `json:"name,omitempty"` + // The color the role should have (as a decimal, not hex) + Color *int `json:"color,omitempty"` + // Whether to display the role's users separately + Hoist *bool `json:"hoist,omitempty"` + // The overall permissions number of the role + Permissions *int64 `json:"permissions,omitempty,string"` + // Whether this role is mentionable + Mentionable *bool `json:"mentionable,omitempty"` + // The role's unicode emoji. + // NOTE: can only be set if the guild has the ROLE_ICONS feature. + UnicodeEmoji *string `json:"unicode_emoji,omitempty"` + // The role's icon image encoded in base64. + // NOTE: can only be set if the guild has the ROLE_ICONS feature. + Icon *string `json:"icon,omitempty"` +} + +// Roles are a collection of Role +type Roles []*Role + +func (r Roles) Len() int { + return len(r) +} + +func (r Roles) Less(i, j int) bool { + return r[i].Position > r[j].Position +} + +func (r Roles) Swap(i, j int) { + r[i], r[j] = r[j], r[i] +} + +// A VoiceState stores the voice states of Guilds +type VoiceState struct { + GuildID string `json:"guild_id"` + ChannelID string `json:"channel_id"` + UserID string `json:"user_id"` + Member *Member `json:"member"` + SessionID string `json:"session_id"` + Deaf bool `json:"deaf"` + Mute bool `json:"mute"` + SelfDeaf bool `json:"self_deaf"` + SelfMute bool `json:"self_mute"` + SelfStream bool `json:"self_stream"` + SelfVideo bool `json:"self_video"` + Suppress bool `json:"suppress"` + RequestToSpeakTimestamp *time.Time `json:"request_to_speak_timestamp"` +} + +// A Presence stores the online, offline, or idle and game status of Guild members. +type Presence struct { + User *User `json:"user"` + Status Status `json:"status"` + Activities []*Activity `json:"activities"` + Since *int `json:"since"` + ClientStatus ClientStatus `json:"client_status"` +} + +// A TimeStamps struct contains start and end times used in the rich presence "playing .." Game +type TimeStamps struct { + EndTimestamp int64 `json:"end,omitempty"` + StartTimestamp int64 `json:"start,omitempty"` +} + +// UnmarshalJSON unmarshals JSON into TimeStamps struct +func (t *TimeStamps) UnmarshalJSON(b []byte) error { + temp := struct { + End float64 `json:"end,omitempty"` + Start float64 `json:"start,omitempty"` + }{} + err := Unmarshal(b, &temp) + if err != nil { + return err + } + t.EndTimestamp = int64(temp.End) + t.StartTimestamp = int64(temp.Start) + return nil +} + +// An Assets struct contains assets and labels used in the rich presence "playing .." Game +type Assets struct { + LargeImageID string `json:"large_image,omitempty"` + SmallImageID string `json:"small_image,omitempty"` + LargeText string `json:"large_text,omitempty"` + SmallText string `json:"small_text,omitempty"` +} + +// MemberFlags represent flags of a guild member. +// https://discord.com/developers/docs/resources/guild#guild-member-object-guild-member-flags +type MemberFlags int + +// Block containing known MemberFlags values. +const ( + // MemberFlagDidRejoin indicates whether the Member has left and rejoined the guild. + MemberFlagDidRejoin MemberFlags = 1 << 0 + // MemberFlagCompletedOnboarding indicates whether the Member has completed onboarding. + MemberFlagCompletedOnboarding MemberFlags = 1 << 1 + // MemberFlagBypassesVerification indicates whether the Member is exempt from guild verification requirements. + MemberFlagBypassesVerification MemberFlags = 1 << 2 + // MemberFlagStartedOnboarding indicates whether the Member has started onboarding. + MemberFlagStartedOnboarding MemberFlags = 1 << 3 +) + +// A Member stores user information for Guild members. A guild +// member represents a certain user's presence in a guild. +type Member struct { + // The guild ID on which the member exists. + GuildID string `json:"guild_id"` + + // The time at which the member joined the guild. + JoinedAt time.Time `json:"joined_at"` + + // The nickname of the member, if they have one. + Nick string `json:"nick"` + + // Whether the member is deafened at a guild level. + Deaf bool `json:"deaf"` + + // Whether the member is muted at a guild level. + Mute bool `json:"mute"` + + // The hash of the avatar for the guild member, if any. + Avatar string `json:"avatar"` + + // The hash of the banner for the guild member, if any. + Banner string `json:"banner"` + + // The underlying user on which the member is based. + User *User `json:"user"` + + // A list of IDs of the roles which are possessed by the member. + Roles []string `json:"roles"` + + // When the user used their Nitro boost on the server + PremiumSince *time.Time `json:"premium_since"` + + // The flags of this member. This is a combination of bit masks; the presence of a certain + // flag can be checked by performing a bitwise AND between this int and the flag. + Flags MemberFlags `json:"flags"` + + // Is true while the member hasn't accepted the membership screen. + Pending bool `json:"pending"` + + // Total permissions of the member in the channel, including overrides, returned when in the interaction object. + Permissions int64 `json:"permissions,string"` + + // The time at which the member's timeout will expire. + // Time in the past or nil if the user is not timed out. + CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"` +} + +// Mention creates a member mention +func (m *Member) Mention() string { + return "<@!" + m.User.ID + ">" +} + +// AvatarURL returns the URL of the member's avatar +// +// size: The size of the user's avatar as a power of two +// if size is an empty string, no size parameter will +// be added to the URL. +func (m *Member) AvatarURL(size string) string { + if m.Avatar == "" { + return m.User.AvatarURL(size) + } + // The default/empty avatar case should be handled by the above condition + return avatarURL(m.Avatar, "", EndpointGuildMemberAvatar(m.GuildID, m.User.ID, m.Avatar), + EndpointGuildMemberAvatarAnimated(m.GuildID, m.User.ID, m.Avatar), size) + +} + +// BannerURL returns the URL of the member's banner image. +// +// size: The size of the desired banner image as a power of two +// Image size can be any power of two between 16 and 4096. +func (m *Member) BannerURL(size string) string { + if m.Banner == "" { + return m.User.BannerURL(size) + } + return bannerURL( + m.Banner, + EndpointGuildMemberBanner(m.GuildID, m.User.ID, m.Banner), + EndpointGuildMemberBannerAnimated(m.GuildID, m.User.ID, m.Banner), + size, + ) +} + +// DisplayName returns the member's guild nickname if they have one, +// otherwise it returns their discord display name. +func (m *Member) DisplayName() string { + if m.Nick != "" { + return m.Nick + } + return m.User.DisplayName() +} + +// ClientStatus stores the online, offline, idle, or dnd status of each device of a Guild member. +type ClientStatus struct { + Desktop Status `json:"desktop"` + Mobile Status `json:"mobile"` + Web Status `json:"web"` +} + +// Status type definition +type Status string + +// Constants for Status with the different current available status +const ( + StatusOnline Status = "online" + StatusIdle Status = "idle" + StatusDoNotDisturb Status = "dnd" + StatusInvisible Status = "invisible" + StatusOffline Status = "offline" +) + +// A TooManyRequests struct holds information received from Discord +// when receiving a HTTP 429 response. +type TooManyRequests struct { + Bucket string `json:"bucket"` + Message string `json:"message"` + RetryAfter time.Duration `json:"retry_after"` +} + +// UnmarshalJSON helps support translation of a milliseconds-based float +// into a time.Duration on TooManyRequests. +func (t *TooManyRequests) UnmarshalJSON(b []byte) error { + u := struct { + Bucket string `json:"bucket"` + Message string `json:"message"` + RetryAfter float64 `json:"retry_after"` + }{} + err := Unmarshal(b, &u) + if err != nil { + return err + } + + t.Bucket = u.Bucket + t.Message = u.Message + whole, frac := math.Modf(u.RetryAfter) + t.RetryAfter = time.Duration(whole)*time.Second + time.Duration(frac*1000)*time.Millisecond + return nil +} + +// A ReadState stores data on the read state of channels. +type ReadState struct { + MentionCount int `json:"mention_count"` + LastMessageID string `json:"last_message_id"` + ID string `json:"id"` +} + +// A GuildRole stores data for guild roles. +type GuildRole struct { + Role *Role `json:"role"` + GuildID string `json:"guild_id"` +} + +// A GuildBan stores data for a guild ban. +type GuildBan struct { + Reason string `json:"reason"` + User *User `json:"user"` +} + +// AutoModerationRule stores data for an auto moderation rule. +type AutoModerationRule struct { + ID string `json:"id,omitempty"` + GuildID string `json:"guild_id,omitempty"` + Name string `json:"name,omitempty"` + CreatorID string `json:"creator_id,omitempty"` + EventType AutoModerationRuleEventType `json:"event_type,omitempty"` + TriggerType AutoModerationRuleTriggerType `json:"trigger_type,omitempty"` + TriggerMetadata *AutoModerationTriggerMetadata `json:"trigger_metadata,omitempty"` + Actions []AutoModerationAction `json:"actions,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + ExemptRoles *[]string `json:"exempt_roles,omitempty"` + ExemptChannels *[]string `json:"exempt_channels,omitempty"` +} + +// AutoModerationRuleEventType indicates in what event context a rule should be checked. +type AutoModerationRuleEventType int + +// Auto moderation rule event types. +const ( + // AutoModerationEventMessageSend is checked when a member sends or edits a message in the guild + AutoModerationEventMessageSend AutoModerationRuleEventType = 1 +) + +// AutoModerationRuleTriggerType represents the type of content which can trigger the rule. +type AutoModerationRuleTriggerType int + +// Auto moderation rule trigger types. +const ( + AutoModerationEventTriggerKeyword AutoModerationRuleTriggerType = 1 + AutoModerationEventTriggerHarmfulLink AutoModerationRuleTriggerType = 2 + AutoModerationEventTriggerSpam AutoModerationRuleTriggerType = 3 + AutoModerationEventTriggerKeywordPreset AutoModerationRuleTriggerType = 4 +) + +// AutoModerationKeywordPreset represents an internally pre-defined wordset. +type AutoModerationKeywordPreset uint + +// Auto moderation keyword presets. +const ( + AutoModerationKeywordPresetProfanity AutoModerationKeywordPreset = 1 + AutoModerationKeywordPresetSexualContent AutoModerationKeywordPreset = 2 + AutoModerationKeywordPresetSlurs AutoModerationKeywordPreset = 3 +) + +// AutoModerationTriggerMetadata represents additional metadata used to determine whether rule should be triggered. +type AutoModerationTriggerMetadata struct { + // Substrings which will be searched for in content. + // NOTE: should be only used with keyword trigger type. + KeywordFilter []string `json:"keyword_filter,omitempty"` + // Regular expression patterns which will be matched against content (maximum of 10). + // NOTE: should be only used with keyword trigger type. + RegexPatterns []string `json:"regex_patterns,omitempty"` + + // Internally pre-defined wordsets which will be searched for in content. + // NOTE: should be only used with keyword preset trigger type. + Presets []AutoModerationKeywordPreset `json:"presets,omitempty"` + + // Substrings which should not trigger the rule. + // NOTE: should be only used with keyword or keyword preset trigger type. + AllowList *[]string `json:"allow_list,omitempty"` + + // Total number of unique role and user mentions allowed per message. + // NOTE: should be only used with mention spam trigger type. + MentionTotalLimit int `json:"mention_total_limit,omitempty"` +} + +// AutoModerationActionType represents an action which will execute whenever a rule is triggered. +type AutoModerationActionType int + +// Auto moderation actions types. +const ( + AutoModerationRuleActionBlockMessage AutoModerationActionType = 1 + AutoModerationRuleActionSendAlertMessage AutoModerationActionType = 2 + AutoModerationRuleActionTimeout AutoModerationActionType = 3 +) + +// AutoModerationActionMetadata represents additional metadata needed during execution for a specific action type. +type AutoModerationActionMetadata struct { + // Channel to which user content should be logged. + // NOTE: should be only used with send alert message action type. + ChannelID string `json:"channel_id,omitempty"` + + // Timeout duration in seconds (maximum of 2419200 - 4 weeks). + // NOTE: should be only used with timeout action type. + Duration int `json:"duration_seconds,omitempty"` + + // Additional explanation that will be shown to members whenever their message is blocked (maximum of 150 characters). + // NOTE: should be only used with block message action type. + CustomMessage string `json:"custom_message,omitempty"` +} + +// AutoModerationAction stores data for an auto moderation action. +type AutoModerationAction struct { + Type AutoModerationActionType `json:"type"` + Metadata *AutoModerationActionMetadata `json:"metadata,omitempty"` +} + +// A GuildEmbed stores data for a guild embed. +type GuildEmbed struct { + Enabled *bool `json:"enabled,omitempty"` + ChannelID string `json:"channel_id,omitempty"` +} + +// A GuildAuditLog stores data for a guild audit log. +// https://discord.com/developers/docs/resources/audit-log#audit-log-object-audit-log-structure +type GuildAuditLog struct { + Webhooks []*Webhook `json:"webhooks,omitempty"` + Users []*User `json:"users,omitempty"` + AuditLogEntries []*AuditLogEntry `json:"audit_log_entries"` + Integrations []*Integration `json:"integrations"` +} + +// AuditLogEntry for a GuildAuditLog +// https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-entry-structure +type AuditLogEntry struct { + TargetID string `json:"target_id"` + Changes []*AuditLogChange `json:"changes"` + UserID string `json:"user_id"` + ID string `json:"id"` + ActionType *AuditLogAction `json:"action_type"` + Options *AuditLogOptions `json:"options"` + Reason string `json:"reason"` +} + +// AuditLogChange for an AuditLogEntry +type AuditLogChange struct { + NewValue interface{} `json:"new_value"` + OldValue interface{} `json:"old_value"` + Key *AuditLogChangeKey `json:"key"` +} + +// AuditLogChangeKey value for AuditLogChange +// https://discord.com/developers/docs/resources/audit-log#audit-log-change-object-audit-log-change-key +type AuditLogChangeKey string + +// Block of valid AuditLogChangeKey +const ( + // AuditLogChangeKeyAfkChannelID is sent when afk channel changed (snowflake) - guild + AuditLogChangeKeyAfkChannelID AuditLogChangeKey = "afk_channel_id" + // AuditLogChangeKeyAfkTimeout is sent when afk timeout duration changed (int) - guild + AuditLogChangeKeyAfkTimeout AuditLogChangeKey = "afk_timeout" + // AuditLogChangeKeyAllow is sent when a permission on a text or voice channel was allowed for a role (string) - role + AuditLogChangeKeyAllow AuditLogChangeKey = "allow" + // AudirChangeKeyApplicationID is sent when application id of the added or removed webhook or bot (snowflake) - channel + AuditLogChangeKeyApplicationID AuditLogChangeKey = "application_id" + // AuditLogChangeKeyArchived is sent when thread was archived/unarchived (bool) - thread + AuditLogChangeKeyArchived AuditLogChangeKey = "archived" + // AuditLogChangeKeyAsset is sent when asset is changed (string) - sticker + AuditLogChangeKeyAsset AuditLogChangeKey = "asset" + // AuditLogChangeKeyAutoArchiveDuration is sent when auto archive duration changed (int) - thread + AuditLogChangeKeyAutoArchiveDuration AuditLogChangeKey = "auto_archive_duration" + // AuditLogChangeKeyAvailable is sent when availability of sticker changed (bool) - sticker + AuditLogChangeKeyAvailable AuditLogChangeKey = "available" + // AuditLogChangeKeyAvatarHash is sent when user avatar changed (string) - user + AuditLogChangeKeyAvatarHash AuditLogChangeKey = "avatar_hash" + // AuditLogChangeKeyBannerHash is sent when guild banner changed (string) - guild + AuditLogChangeKeyBannerHash AuditLogChangeKey = "banner_hash" + // AuditLogChangeKeyBitrate is sent when voice channel bitrate changed (int) - channel + AuditLogChangeKeyBitrate AuditLogChangeKey = "bitrate" + // AuditLogChangeKeyChannelID is sent when channel for invite code or guild scheduled event changed (snowflake) - invite or guild scheduled event + AuditLogChangeKeyChannelID AuditLogChangeKey = "channel_id" + // AuditLogChangeKeyCode is sent when invite code changed (string) - invite + AuditLogChangeKeyCode AuditLogChangeKey = "code" + // AuditLogChangeKeyColor is sent when role color changed (int) - role + AuditLogChangeKeyColor AuditLogChangeKey = "color" + // AuditLogChangeKeyCommunicationDisabledUntil is sent when member timeout state changed (ISO8601 timestamp) - member + AuditLogChangeKeyCommunicationDisabledUntil AuditLogChangeKey = "communication_disabled_until" + // AuditLogChangeKeyDeaf is sent when user server deafened/undeafened (bool) - member + AuditLogChangeKeyDeaf AuditLogChangeKey = "deaf" + // AuditLogChangeKeyDefaultAutoArchiveDuration is sent when default auto archive duration for newly created threads changed (int) - channel + AuditLogChangeKeyDefaultAutoArchiveDuration AuditLogChangeKey = "default_auto_archive_duration" + // AuditLogChangeKeyDefaultMessageNotification is sent when default message notification level changed (int) - guild + AuditLogChangeKeyDefaultMessageNotification AuditLogChangeKey = "default_message_notifications" + // AuditLogChangeKeyDeny is sent when a permission on a text or voice channel was denied for a role (string) - role + AuditLogChangeKeyDeny AuditLogChangeKey = "deny" + // AuditLogChangeKeyDescription is sent when description changed (string) - guild, sticker, or guild scheduled event + AuditLogChangeKeyDescription AuditLogChangeKey = "description" + // AuditLogChangeKeyDiscoverySplashHash is sent when discovery splash changed (string) - guild + AuditLogChangeKeyDiscoverySplashHash AuditLogChangeKey = "discovery_splash_hash" + // AuditLogChangeKeyEnableEmoticons is sent when integration emoticons enabled/disabled (bool) - integration + AuditLogChangeKeyEnableEmoticons AuditLogChangeKey = "enable_emoticons" + // AuditLogChangeKeyEntityType is sent when entity type of guild scheduled event was changed (int) - guild scheduled event + AuditLogChangeKeyEntityType AuditLogChangeKey = "entity_type" + // AuditLogChangeKeyExpireBehavior is sent when integration expiring subscriber behavior changed (int) - integration + AuditLogChangeKeyExpireBehavior AuditLogChangeKey = "expire_behavior" + // AuditLogChangeKeyExpireGracePeriod is sent when integration expire grace period changed (int) - integration + AuditLogChangeKeyExpireGracePeriod AuditLogChangeKey = "expire_grace_period" + // AuditLogChangeKeyExplicitContentFilter is sent when change in whose messages are scanned and deleted for explicit content in the server is made (int) - guild + AuditLogChangeKeyExplicitContentFilter AuditLogChangeKey = "explicit_content_filter" + // AuditLogChangeKeyFormatType is sent when format type of sticker changed (int - sticker format type) - sticker + AuditLogChangeKeyFormatType AuditLogChangeKey = "format_type" + // AuditLogChangeKeyGuildID is sent when guild sticker is in changed (snowflake) - sticker + AuditLogChangeKeyGuildID AuditLogChangeKey = "guild_id" + // AuditLogChangeKeyHoist is sent when role is now displayed/no longer displayed separate from online users (bool) - role + AuditLogChangeKeyHoist AuditLogChangeKey = "hoist" + // AuditLogChangeKeyIconHash is sent when icon changed (string) - guild or role + AuditLogChangeKeyIconHash AuditLogChangeKey = "icon_hash" + // AuditLogChangeKeyID is sent when the id of the changed entity - sometimes used in conjunction with other keys (snowflake) - any + AuditLogChangeKeyID AuditLogChangeKey = "id" + // AuditLogChangeKeyInvitable is sent when private thread is now invitable/uninvitable (bool) - thread + AuditLogChangeKeyInvitable AuditLogChangeKey = "invitable" + // AuditLogChangeKeyInviterID is sent when person who created invite code changed (snowflake) - invite + AuditLogChangeKeyInviterID AuditLogChangeKey = "inviter_id" + // AuditLogChangeKeyLocation is sent when channel id for guild scheduled event changed (string) - guild scheduled event + AuditLogChangeKeyLocation AuditLogChangeKey = "location" + // AuditLogChangeKeyLocked is sent when thread was locked/unlocked (bool) - thread + AuditLogChangeKeyLocked AuditLogChangeKey = "locked" + // AuditLogChangeKeyMaxAge is sent when invite code expiration time changed (int) - invite + AuditLogChangeKeyMaxAge AuditLogChangeKey = "max_age" + // AuditLogChangeKeyMaxUses is sent when max number of times invite code can be used changed (int) - invite + AuditLogChangeKeyMaxUses AuditLogChangeKey = "max_uses" + // AuditLogChangeKeyMentionable is sent when role is now mentionable/unmentionable (bool) - role + AuditLogChangeKeyMentionable AuditLogChangeKey = "mentionable" + // AuditLogChangeKeyMfaLevel is sent when two-factor auth requirement changed (int - mfa level) - guild + AuditLogChangeKeyMfaLevel AuditLogChangeKey = "mfa_level" + // AuditLogChangeKeyMute is sent when user server muted/unmuted (bool) - member + AuditLogChangeKeyMute AuditLogChangeKey = "mute" + // AuditLogChangeKeyName is sent when name changed (string) - any + AuditLogChangeKeyName AuditLogChangeKey = "name" + // AuditLogChangeKeyNick is sent when user nickname changed (string) - member + AuditLogChangeKeyNick AuditLogChangeKey = "nick" + // AuditLogChangeKeyNSFW is sent when channel nsfw restriction changed (bool) - channel + AuditLogChangeKeyNSFW AuditLogChangeKey = "nsfw" + // AuditLogChangeKeyOwnerID is sent when owner changed (snowflake) - guild + AuditLogChangeKeyOwnerID AuditLogChangeKey = "owner_id" + // AuditLogChangeKeyPermissionOverwrite is sent when permissions on a channel changed (array of channel overwrite objects) - channel + AuditLogChangeKeyPermissionOverwrite AuditLogChangeKey = "permission_overwrites" + // AuditLogChangeKeyPermissions is sent when permissions for a role changed (string) - role + AuditLogChangeKeyPermissions AuditLogChangeKey = "permissions" + // AuditLogChangeKeyPosition is sent when text or voice channel position changed (int) - channel + AuditLogChangeKeyPosition AuditLogChangeKey = "position" + // AuditLogChangeKeyPreferredLocale is sent when preferred locale changed (string) - guild + AuditLogChangeKeyPreferredLocale AuditLogChangeKey = "preferred_locale" + // AuditLogChangeKeyPrivacylevel is sent when privacy level of the stage instance changed (integer - privacy level) - stage instance or guild scheduled event + AuditLogChangeKeyPrivacylevel AuditLogChangeKey = "privacy_level" + // AuditLogChangeKeyPruneDeleteDays is sent when number of days after which inactive and role-unassigned members are kicked changed (int) - guild + AuditLogChangeKeyPruneDeleteDays AuditLogChangeKey = "prune_delete_days" + // AuditLogChangeKeyPublicUpdatesChannelID is sent when id of the public updates channel changed (snowflake) - guild + AuditLogChangeKeyPublicUpdatesChannelID AuditLogChangeKey = "public_updates_channel_id" + // AuditLogChangeKeyRateLimitPerUser is sent when amount of seconds a user has to wait before sending another message changed (int) - channel + AuditLogChangeKeyRateLimitPerUser AuditLogChangeKey = "rate_limit_per_user" + // AuditLogChangeKeyRegion is sent when region changed (string) - guild + AuditLogChangeKeyRegion AuditLogChangeKey = "region" + // AuditLogChangeKeyRulesChannelID is sent when id of the rules channel changed (snowflake) - guild + AuditLogChangeKeyRulesChannelID AuditLogChangeKey = "rules_channel_id" + // AuditLogChangeKeySplashHash is sent when invite splash page artwork changed (string) - guild + AuditLogChangeKeySplashHash AuditLogChangeKey = "splash_hash" + // AuditLogChangeKeyStatus is sent when status of guild scheduled event was changed (int - guild scheduled event status) - guild scheduled event + AuditLogChangeKeyStatus AuditLogChangeKey = "status" + // AuditLogChangeKeySystemChannelID is sent when id of the system channel changed (snowflake) - guild + AuditLogChangeKeySystemChannelID AuditLogChangeKey = "system_channel_id" + // AuditLogChangeKeyTags is sent when related emoji of sticker changed (string) - sticker + AuditLogChangeKeyTags AuditLogChangeKey = "tags" + // AuditLogChangeKeyTemporary is sent when invite code is now temporary or never expires (bool) - invite + AuditLogChangeKeyTemporary AuditLogChangeKey = "temporary" + // TODO: remove when compatibility is not required + AuditLogChangeKeyTempoary = AuditLogChangeKeyTemporary + // AuditLogChangeKeyTopic is sent when text channel topic or stage instance topic changed (string) - channel or stage instance + AuditLogChangeKeyTopic AuditLogChangeKey = "topic" + // AuditLogChangeKeyType is sent when type of entity created (int or string) - any + AuditLogChangeKeyType AuditLogChangeKey = "type" + // AuditLogChangeKeyUnicodeEmoji is sent when role unicode emoji changed (string) - role + AuditLogChangeKeyUnicodeEmoji AuditLogChangeKey = "unicode_emoji" + // AuditLogChangeKeyUserLimit is sent when new user limit in a voice channel set (int) - voice channel + AuditLogChangeKeyUserLimit AuditLogChangeKey = "user_limit" + // AuditLogChangeKeyUses is sent when number of times invite code used changed (int) - invite + AuditLogChangeKeyUses AuditLogChangeKey = "uses" + // AuditLogChangeKeyVanityURLCode is sent when guild invite vanity url changed (string) - guild + AuditLogChangeKeyVanityURLCode AuditLogChangeKey = "vanity_url_code" + // AuditLogChangeKeyVerificationLevel is sent when required verification level changed (int - verification level) - guild + AuditLogChangeKeyVerificationLevel AuditLogChangeKey = "verification_level" + // AuditLogChangeKeyWidgetChannelID is sent when channel id of the server widget changed (snowflake) - guild + AuditLogChangeKeyWidgetChannelID AuditLogChangeKey = "widget_channel_id" + // AuditLogChangeKeyWidgetEnabled is sent when server widget enabled/disabled (bool) - guild + AuditLogChangeKeyWidgetEnabled AuditLogChangeKey = "widget_enabled" + // AuditLogChangeKeyRoleAdd is sent when new role added (array of partial role objects) - guild + AuditLogChangeKeyRoleAdd AuditLogChangeKey = "$add" + // AuditLogChangeKeyRoleRemove is sent when role removed (array of partial role objects) - guild + AuditLogChangeKeyRoleRemove AuditLogChangeKey = "$remove" +) + +// AuditLogOptions optional data for the AuditLog +// https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-optional-audit-entry-info +type AuditLogOptions struct { + DeleteMemberDays string `json:"delete_member_days"` + MembersRemoved string `json:"members_removed"` + ChannelID string `json:"channel_id"` + MessageID string `json:"message_id"` + Count string `json:"count"` + ID string `json:"id"` + Type *AuditLogOptionsType `json:"type"` + RoleName string `json:"role_name"` + ApplicationID string `json:"application_id"` + AutoModerationRuleName string `json:"auto_moderation_rule_name"` + AutoModerationRuleTriggerType string `json:"auto_moderation_rule_trigger_type"` + IntegrationType string `json:"integration_type"` +} + +// AuditLogOptionsType of the AuditLogOption +// https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-optional-audit-entry-info +type AuditLogOptionsType string + +// Valid Types for AuditLogOptionsType +const ( + AuditLogOptionsTypeRole AuditLogOptionsType = "0" + AuditLogOptionsTypeMember AuditLogOptionsType = "1" +) + +// AuditLogAction is the Action of the AuditLog (see AuditLogAction* consts) +// https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-events +type AuditLogAction int + +// Block contains Discord Audit Log Action Types +const ( + AuditLogActionGuildUpdate AuditLogAction = 1 + + AuditLogActionChannelCreate AuditLogAction = 10 + AuditLogActionChannelUpdate AuditLogAction = 11 + AuditLogActionChannelDelete AuditLogAction = 12 + AuditLogActionChannelOverwriteCreate AuditLogAction = 13 + AuditLogActionChannelOverwriteUpdate AuditLogAction = 14 + AuditLogActionChannelOverwriteDelete AuditLogAction = 15 + + AuditLogActionMemberKick AuditLogAction = 20 + AuditLogActionMemberPrune AuditLogAction = 21 + AuditLogActionMemberBanAdd AuditLogAction = 22 + AuditLogActionMemberBanRemove AuditLogAction = 23 + AuditLogActionMemberUpdate AuditLogAction = 24 + AuditLogActionMemberRoleUpdate AuditLogAction = 25 + AuditLogActionMemberMove AuditLogAction = 26 + AuditLogActionMemberDisconnect AuditLogAction = 27 + AuditLogActionBotAdd AuditLogAction = 28 + + AuditLogActionRoleCreate AuditLogAction = 30 + AuditLogActionRoleUpdate AuditLogAction = 31 + AuditLogActionRoleDelete AuditLogAction = 32 + + AuditLogActionInviteCreate AuditLogAction = 40 + AuditLogActionInviteUpdate AuditLogAction = 41 + AuditLogActionInviteDelete AuditLogAction = 42 + + AuditLogActionWebhookCreate AuditLogAction = 50 + AuditLogActionWebhookUpdate AuditLogAction = 51 + AuditLogActionWebhookDelete AuditLogAction = 52 + + AuditLogActionEmojiCreate AuditLogAction = 60 + AuditLogActionEmojiUpdate AuditLogAction = 61 + AuditLogActionEmojiDelete AuditLogAction = 62 + + AuditLogActionMessageDelete AuditLogAction = 72 + AuditLogActionMessageBulkDelete AuditLogAction = 73 + AuditLogActionMessagePin AuditLogAction = 74 + AuditLogActionMessageUnpin AuditLogAction = 75 + + AuditLogActionIntegrationCreate AuditLogAction = 80 + AuditLogActionIntegrationUpdate AuditLogAction = 81 + AuditLogActionIntegrationDelete AuditLogAction = 82 + AuditLogActionStageInstanceCreate AuditLogAction = 83 + AuditLogActionStageInstanceUpdate AuditLogAction = 84 + AuditLogActionStageInstanceDelete AuditLogAction = 85 + + AuditLogActionStickerCreate AuditLogAction = 90 + AuditLogActionStickerUpdate AuditLogAction = 91 + AuditLogActionStickerDelete AuditLogAction = 92 + + AuditLogGuildScheduledEventCreate AuditLogAction = 100 + AuditLogGuildScheduledEventUpdate AuditLogAction = 101 + AuditLogGuildScheduledEventDelete AuditLogAction = 102 + + AuditLogActionThreadCreate AuditLogAction = 110 + AuditLogActionThreadUpdate AuditLogAction = 111 + AuditLogActionThreadDelete AuditLogAction = 112 + + AuditLogActionApplicationCommandPermissionUpdate AuditLogAction = 121 + + AuditLogActionAutoModerationRuleCreate AuditLogAction = 140 + AuditLogActionAutoModerationRuleUpdate AuditLogAction = 141 + AuditLogActionAutoModerationRuleDelete AuditLogAction = 142 + AuditLogActionAutoModerationBlockMessage AuditLogAction = 143 + AuditLogActionAutoModerationFlagToChannel AuditLogAction = 144 + AuditLogActionAutoModerationUserCommunicationDisabled AuditLogAction = 145 + + AuditLogActionCreatorMonetizationRequestCreated AuditLogAction = 150 + AuditLogActionCreatorMonetizationTermsAccepted AuditLogAction = 151 + + AuditLogActionOnboardingPromptCreate AuditLogAction = 163 + AuditLogActionOnboardingPromptUpdate AuditLogAction = 164 + AuditLogActionOnboardingPromptDelete AuditLogAction = 165 + AuditLogActionOnboardingCreate AuditLogAction = 166 + AuditLogActionOnboardingUpdate AuditLogAction = 167 + + AuditLogActionHomeSettingsCreate = 190 + AuditLogActionHomeSettingsUpdate = 191 +) + +// GuildMemberParams stores data needed to update a member +// https://discord.com/developers/docs/resources/guild#modify-guild-member +type GuildMemberParams struct { + // Value to set user's nickname to. + Nick string `json:"nick,omitempty"` + // Array of role ids the member is assigned. + Roles *[]string `json:"roles,omitempty"` + // ID of channel to move user to (if they are connected to voice). + // Set to "" to remove user from a voice channel. + ChannelID *string `json:"channel_id,omitempty"` + // Whether the user is muted in voice channels. + Mute *bool `json:"mute,omitempty"` + // Whether the user is deafened in voice channels. + Deaf *bool `json:"deaf,omitempty"` + // When the user's timeout will expire and the user will be able + // to communicate in the guild again (up to 28 days in the future). + // Set to time.Time{} to remove timeout. + CommunicationDisabledUntil *time.Time `json:"communication_disabled_until,omitempty"` +} + +// MarshalJSON is a helper function to marshal GuildMemberParams. +func (p GuildMemberParams) MarshalJSON() (res []byte, err error) { + type guildMemberParams GuildMemberParams + v := struct { + guildMemberParams + ChannelID json.RawMessage `json:"channel_id,omitempty"` + CommunicationDisabledUntil json.RawMessage `json:"communication_disabled_until,omitempty"` + }{guildMemberParams: guildMemberParams(p)} + + if p.ChannelID != nil { + if *p.ChannelID == "" { + v.ChannelID = json.RawMessage(`null`) + } else { + res, err = json.Marshal(p.ChannelID) + if err != nil { + return + } + v.ChannelID = res + } + } + + if p.CommunicationDisabledUntil != nil { + if p.CommunicationDisabledUntil.IsZero() { + v.CommunicationDisabledUntil = json.RawMessage(`null`) + } else { + res, err = json.Marshal(p.CommunicationDisabledUntil) + if err != nil { + return + } + v.CommunicationDisabledUntil = res + } + } + + return json.Marshal(v) +} + +// GuildMemberAddParams stores data needed to add a user to a guild. +// NOTE: All fields are optional, except AccessToken. +type GuildMemberAddParams struct { + // Valid access_token for the user. + AccessToken string `json:"access_token"` + // Value to set users nickname to. + Nick string `json:"nick,omitempty"` + // A list of role ID's to set on the member. + Roles []string `json:"roles,omitempty"` + // Whether the user is muted. + Mute bool `json:"mute,omitempty"` + // Whether the user is deafened. + Deaf bool `json:"deaf,omitempty"` +} + +// An APIErrorMessage is an api error message returned from discord +type APIErrorMessage struct { + Code int `json:"code"` + Message string `json:"message"` +} + +// MessageReaction stores the data for a message reaction. +type MessageReaction struct { + UserID string `json:"user_id"` + MessageID string `json:"message_id"` + Emoji Emoji `json:"emoji"` + ChannelID string `json:"channel_id"` + GuildID string `json:"guild_id,omitempty"` +} + +// GatewayBotResponse stores the data for the gateway/bot response +type GatewayBotResponse struct { + URL string `json:"url"` + Shards int `json:"shards"` + SessionStartLimit SessionInformation `json:"session_start_limit"` +} + +// SessionInformation provides the information for max concurrency sharding +type SessionInformation struct { + Total int `json:"total,omitempty"` + Remaining int `json:"remaining,omitempty"` + ResetAfter int `json:"reset_after,omitempty"` + MaxConcurrency int `json:"max_concurrency,omitempty"` +} + +// GatewayStatusUpdate is sent by the client to indicate a presence or status update +// https://discord.com/developers/docs/topics/gateway#update-status-gateway-status-update-structure +type GatewayStatusUpdate struct { + Since int `json:"since"` + Game Activity `json:"game"` + Status string `json:"status"` + AFK bool `json:"afk"` +} + +// Activity defines the Activity sent with GatewayStatusUpdate +// https://discord.com/developers/docs/topics/gateway#activity-object +type Activity struct { + Name string `json:"name"` + Type ActivityType `json:"type"` + URL string `json:"url,omitempty"` + CreatedAt time.Time `json:"created_at"` + ApplicationID string `json:"application_id,omitempty"` + State string `json:"state,omitempty"` + Details string `json:"details,omitempty"` + Timestamps TimeStamps `json:"timestamps,omitempty"` + Emoji Emoji `json:"emoji,omitempty"` + Party Party `json:"party,omitempty"` + Assets Assets `json:"assets,omitempty"` + Secrets Secrets `json:"secrets,omitempty"` + Instance bool `json:"instance,omitempty"` + Flags int `json:"flags,omitempty"` +} + +// UnmarshalJSON is a custom unmarshaljson to make CreatedAt a time.Time instead of an int +func (activity *Activity) UnmarshalJSON(b []byte) error { + temp := struct { + Name string `json:"name"` + Type ActivityType `json:"type"` + URL string `json:"url,omitempty"` + CreatedAt int64 `json:"created_at"` + ApplicationID json.Number `json:"application_id,omitempty"` + State string `json:"state,omitempty"` + Details string `json:"details,omitempty"` + Timestamps TimeStamps `json:"timestamps,omitempty"` + Emoji Emoji `json:"emoji,omitempty"` + Party Party `json:"party,omitempty"` + Assets Assets `json:"assets,omitempty"` + Secrets Secrets `json:"secrets,omitempty"` + Instance bool `json:"instance,omitempty"` + Flags int `json:"flags,omitempty"` + }{} + err := Unmarshal(b, &temp) + if err != nil { + return err + } + activity.ApplicationID = temp.ApplicationID.String() + activity.CreatedAt = time.Unix(0, temp.CreatedAt*1000000) + activity.Assets = temp.Assets + activity.Details = temp.Details + activity.Emoji = temp.Emoji + activity.Flags = temp.Flags + activity.Instance = temp.Instance + activity.Name = temp.Name + activity.Party = temp.Party + activity.Secrets = temp.Secrets + activity.State = temp.State + activity.Timestamps = temp.Timestamps + activity.Type = temp.Type + activity.URL = temp.URL + return nil +} + +// Party defines the Party field in the Activity struct +// https://discord.com/developers/docs/topics/gateway#activity-object +type Party struct { + ID string `json:"id,omitempty"` + Size []int `json:"size,omitempty"` +} + +// Secrets defines the Secrets field for the Activity struct +// https://discord.com/developers/docs/topics/gateway#activity-object +type Secrets struct { + Join string `json:"join,omitempty"` + Spectate string `json:"spectate,omitempty"` + Match string `json:"match,omitempty"` +} + +// ActivityType is the type of Activity (see ActivityType* consts) in the Activity struct +// https://discord.com/developers/docs/topics/gateway#activity-object-activity-types +type ActivityType int + +// Valid ActivityType values +const ( + ActivityTypeGame ActivityType = 0 + ActivityTypeStreaming ActivityType = 1 + ActivityTypeListening ActivityType = 2 + ActivityTypeWatching ActivityType = 3 + ActivityTypeCustom ActivityType = 4 + ActivityTypeCompeting ActivityType = 5 +) + +// Identify is sent during initial handshake with the discord gateway. +// https://discord.com/developers/docs/topics/gateway#identify +type Identify struct { + Token string `json:"token"` + Properties IdentifyProperties `json:"properties"` + Compress bool `json:"compress"` + LargeThreshold int `json:"large_threshold"` + Shard *[2]int `json:"shard,omitempty"` + Presence GatewayStatusUpdate `json:"presence,omitempty"` + Intents Intent `json:"intents"` +} + +// IdentifyProperties contains the "properties" portion of an Identify packet +// https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties +type IdentifyProperties struct { + OS string `json:"$os"` + Browser string `json:"$browser"` + Device string `json:"$device"` + Referer string `json:"$referer"` + ReferringDomain string `json:"$referring_domain"` +} + +// StageInstance holds information about a live stage. +// https://discord.com/developers/docs/resources/stage-instance#stage-instance-resource +type StageInstance struct { + // The id of this Stage instance + ID string `json:"id"` + // The guild id of the associated Stage channel + GuildID string `json:"guild_id"` + // The id of the associated Stage channel + ChannelID string `json:"channel_id"` + // The topic of the Stage instance (1-120 characters) + Topic string `json:"topic"` + // The privacy level of the Stage instance + // https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-privacy-level + PrivacyLevel StageInstancePrivacyLevel `json:"privacy_level"` + // Whether or not Stage Discovery is disabled (deprecated) + DiscoverableDisabled bool `json:"discoverable_disabled"` + // The id of the scheduled event for this Stage instance + GuildScheduledEventID string `json:"guild_scheduled_event_id"` +} + +// StageInstanceParams represents the parameters needed to create or edit a stage instance +type StageInstanceParams struct { + // ChannelID represents the id of the Stage channel + ChannelID string `json:"channel_id,omitempty"` + // Topic of the Stage instance (1-120 characters) + Topic string `json:"topic,omitempty"` + // PrivacyLevel of the Stage instance (default GUILD_ONLY) + PrivacyLevel StageInstancePrivacyLevel `json:"privacy_level,omitempty"` + // SendStartNotification will notify @everyone that a Stage instance has started + SendStartNotification bool `json:"send_start_notification,omitempty"` +} + +// StageInstancePrivacyLevel represents the privacy level of a Stage instance +// https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-privacy-level +type StageInstancePrivacyLevel int + +const ( + // StageInstancePrivacyLevelPublic The Stage instance is visible publicly. (deprecated) + StageInstancePrivacyLevelPublic StageInstancePrivacyLevel = 1 + // StageInstancePrivacyLevelGuildOnly The Stage instance is visible to only guild members. + StageInstancePrivacyLevelGuildOnly StageInstancePrivacyLevel = 2 +) + +// PollLayoutType represents the layout of a poll. +type PollLayoutType int + +// Valid PollLayoutType values. +const ( + PollLayoutTypeDefault PollLayoutType = 1 +) + +// PollMedia contains common data used by question and answers. +type PollMedia struct { + Text string `json:"text,omitempty"` + Emoji *ComponentEmoji `json:"emoji,omitempty"` // TODO: rename the type +} + +// PollAnswer represents a single answer in a poll. +type PollAnswer struct { + // NOTE: should not be set on creation. + AnswerID int `json:"answer_id,omitempty"` + Media *PollMedia `json:"poll_media"` +} + +// PollAnswerCount stores counted poll votes for a single answer. +type PollAnswerCount struct { + ID int `json:"id"` + Count int `json:"count"` + MeVoted bool `json:"me_voted"` +} + +// PollResults contains voting results on a poll. +type PollResults struct { + Finalized bool `json:"is_finalized"` + AnswerCounts []*PollAnswerCount `json:"answer_counts"` +} + +// Poll contains all poll related data. +type Poll struct { + Question PollMedia `json:"question"` + Answers []PollAnswer `json:"answers"` + AllowMultiselect bool `json:"allow_multiselect"` + LayoutType PollLayoutType `json:"layout_type,omitempty"` + + // NOTE: should be set only on creation, when fetching use Expiry. + Duration int `json:"duration,omitempty"` + + // NOTE: available only when fetching. + + Results *PollResults `json:"results,omitempty"` + // NOTE: as Discord documentation notes, this field might be null even when fetching. + Expiry *time.Time `json:"expiry,omitempty"` +} + +// SKUType is the type of SKU (see SKUType* consts) +// https://discord.com/developers/docs/monetization/skus +type SKUType int + +// Valid SKUType values +const ( + SKUTypeDurable SKUType = 2 + SKUTypeConsumable SKUType = 3 + SKUTypeSubscription SKUType = 5 + // SKUTypeSubscriptionGroup is a system-generated group for each subscription SKU. + SKUTypeSubscriptionGroup SKUType = 6 +) + +// SKUFlags is a bitfield of flags used to differentiate user and server subscriptions (see SKUFlag* consts) +// https://discord.com/developers/docs/monetization/skus#sku-object-sku-flags +type SKUFlags int + +const ( + // SKUFlagAvailable indicates that the SKU is available for purchase. + SKUFlagAvailable SKUFlags = 1 << 2 + // SKUFlagGuildSubscription indicates that the SKU is a guild subscription. + SKUFlagGuildSubscription SKUFlags = 1 << 7 + // SKUFlagUserSubscription indicates that the SKU is a user subscription. + SKUFlagUserSubscription SKUFlags = 1 << 8 +) + +// SKU (stock-keeping units) represent premium offerings +type SKU struct { + // The ID of the SKU + ID string `json:"id"` + + // The Type of the SKU + Type SKUType `json:"type"` + + // The ID of the parent application + ApplicationID string `json:"application_id"` + + // Customer-facing name of the SKU. + Name string `json:"name"` + + // System-generated URL slug based on the SKU's name. + Slug string `json:"slug"` + + // SKUFlags combined as a bitfield. The presence of a certain flag can be checked + // by performing a bitwise AND operation between this int and the flag. + Flags SKUFlags `json:"flags"` +} + +// Subscription represents a user making recurring payments for at least one SKU over an ongoing period. +// https://discord.com/developers/docs/resources/subscription#subscription-object +type Subscription struct { + // ID of the subscription + ID string `json:"id"` + + // ID of the user who is subscribed + UserID string `json:"user_id"` + + // List of SKUs subscribed to + SKUIDs []string `json:"sku_ids"` + + // List of entitlements granted for this subscription + EntitlementIDs []string `json:"entitlement_ids"` + + // List of SKUs that this user will be subscribed to at renewal + RenewalSKUIDs []string `json:"renewal_sku_ids,omitempty"` + + // Start of the current subscription period + CurrentPeriodStart time.Time `json:"current_period_start"` + + // End of the current subscription period + CurrentPeriodEnd time.Time `json:"current_period_end"` + + // Current status of the subscription + Status SubscriptionStatus `json:"status"` + + // When the subscription was canceled. Only present if the subscription has been canceled. + CanceledAt *time.Time `json:"canceled_at,omitempty"` + + // ISO3166-1 alpha-2 country code of the payment source used to purchase the subscription. Missing unless queried with a private OAuth scope. + Country string `json:"country,omitempty"` +} + +// SubscriptionStatus is the current status of a Subscription Object +// https://discord.com/developers/docs/resources/subscription#subscription-statuses +type SubscriptionStatus int + +// Valid SubscriptionStatus values +const ( + SubscriptionStatusActive = 0 + SubscriptionStatusEnding = 1 + SubscriptionStatusInactive = 2 +) + +// EntitlementType is the type of entitlement (see EntitlementType* consts) +// https://discord.com/developers/docs/monetization/entitlements#entitlement-object-entitlement-types +type EntitlementType int + +// Valid EntitlementType values +const ( + EntitlementTypePurchase = 1 + EntitlementTypePremiumSubscription = 2 + EntitlementTypeDeveloperGift = 3 + EntitlementTypeTestModePurchase = 4 + EntitlementTypeFreePurchase = 5 + EntitlementTypeUserGift = 6 + EntitlementTypePremiumPurchase = 7 + EntitlementTypeApplicationSubscription = 8 +) + +// Entitlement represents that a user or guild has access to a premium offering +// in your application. +type Entitlement struct { + // The ID of the entitlement + ID string `json:"id"` + + // The ID of the SKU + SKUID string `json:"sku_id"` + + // The ID of the parent application + ApplicationID string `json:"application_id"` + + // The ID of the user that is granted access to the entitlement's sku + // Only available for user subscriptions. + UserID string `json:"user_id,omitempty"` + + // The type of the entitlement + Type EntitlementType `json:"type"` + + // The entitlement was deleted + Deleted bool `json:"deleted"` + + // The start date at which the entitlement is valid. + // Not present when using test entitlements. + StartsAt *time.Time `json:"starts_at,omitempty"` + + // The date at which the entitlement is no longer valid. + // Not present when using test entitlements or when receiving an ENTITLEMENT_CREATE event. + EndsAt *time.Time `json:"ends_at,omitempty"` + + // The ID of the guild that is granted access to the entitlement's sku. + // Only available for guild subscriptions. + GuildID string `json:"guild_id,omitempty"` + + // Whether or not the entitlement has been consumed. + // Only available for consumable items. + Consumed *bool `json:"consumed,omitempty"` + + // The SubscriptionID of the entitlement. + // Not present when using test entitlements. + SubscriptionID string `json:"subscription_id,omitempty"` +} + +// EntitlementOwnerType is the type of entitlement (see EntitlementOwnerType* consts) +type EntitlementOwnerType int + +// Valid EntitlementOwnerType values +const ( + EntitlementOwnerTypeGuildSubscription EntitlementOwnerType = 1 + EntitlementOwnerTypeUserSubscription EntitlementOwnerType = 2 +) + +// EntitlementTest is used to test granting an entitlement to a user or guild +type EntitlementTest struct { + // The ID of the SKU to grant the entitlement to + SKUID string `json:"sku_id"` + + // The ID of the guild or user to grant the entitlement to + OwnerID string `json:"owner_id"` + + // OwnerType is the type of which the entitlement should be created + OwnerType EntitlementOwnerType `json:"owner_type"` +} + +// EntitlementFilterOptions are the options for filtering Entitlements +type EntitlementFilterOptions struct { + // Optional user ID to look up for. + UserID string + + // Optional array of SKU IDs to check for. + SkuIDs []string + + // Optional timestamp to retrieve Entitlements before this time. + Before *time.Time + + // Optional timestamp to retrieve Entitlements after this time. + After *time.Time + + // Optional maximum number of entitlements to return (1-100, default 100). + Limit int + + // Optional guild ID to look up for. + GuildID string + + // Optional whether or not ended entitlements should be omitted. + ExcludeEnded bool +} + +// Constants for the different bit offsets of text channel permissions +const ( + // Deprecated: PermissionReadMessages has been replaced with PermissionViewChannel for text and voice channels + PermissionReadMessages = 1 << 10 + + // Allows for sending messages in a channel and creating threads in a forum (does not allow sending messages in threads). + PermissionSendMessages = 1 << 11 + + // Allows for sending of /tts messages. + PermissionSendTTSMessages = 1 << 12 + + // Allows for deletion of other users messages. + PermissionManageMessages = 1 << 13 + + // Links sent by users with this permission will be auto-embedded. + PermissionEmbedLinks = 1 << 14 + + // Allows for uploading images and files. + PermissionAttachFiles = 1 << 15 + + // Allows for reading of message history. + PermissionReadMessageHistory = 1 << 16 + + // Allows for using the @everyone tag to notify all users in a channel, and the @here tag to notify all online users in a channel. + PermissionMentionEveryone = 1 << 17 + + // Allows the usage of custom emojis from other servers. + PermissionUseExternalEmojis = 1 << 18 + + // Deprecated: PermissionUseSlashCommands has been replaced by PermissionUseApplicationCommands + PermissionUseSlashCommands = 1 << 31 + + // Allows members to use application commands, including slash commands and context menu commands. + PermissionUseApplicationCommands = 1 << 31 + + // Allows for deleting and archiving threads, and viewing all private threads. + PermissionManageThreads = 1 << 34 + + // Allows for creating public and announcement threads. + PermissionCreatePublicThreads = 1 << 35 + + // Allows for creating private threads. + PermissionCreatePrivateThreads = 1 << 36 + + // Allows the usage of custom stickers from other servers. + PermissionUseExternalStickers = 1 << 37 + + // Allows for sending messages in threads. + PermissionSendMessagesInThreads = 1 << 38 + + // Allows sending voice messages. + PermissionSendVoiceMessages = 1 << 46 + + // Allows sending polls. + PermissionSendPolls = 1 << 49 + + // Allows user-installed apps to send public responses. When disabled, users will still be allowed to use their apps but the responses will be ephemeral. This only applies to apps not also installed to the server. + PermissionUseExternalApps = 1 << 50 +) + +// Constants for the different bit offsets of voice permissions +const ( + // Allows for using priority speaker in a voice channel. + PermissionVoicePrioritySpeaker = 1 << 8 + + // Allows the user to go live. + PermissionVoiceStreamVideo = 1 << 9 + + // Allows for joining of a voice channel. + PermissionVoiceConnect = 1 << 20 + + // Allows for speaking in a voice channel. + PermissionVoiceSpeak = 1 << 21 + + // Allows for muting members in a voice channel. + PermissionVoiceMuteMembers = 1 << 22 + + // Allows for deafening of members in a voice channel. + PermissionVoiceDeafenMembers = 1 << 23 + + // Allows for moving of members between voice channels. + PermissionVoiceMoveMembers = 1 << 24 + + // Allows for using voice-activity-detection in a voice channel. + PermissionVoiceUseVAD = 1 << 25 + + // Allows for requesting to speak in stage channels. + PermissionVoiceRequestToSpeak = 1 << 32 + + // Deprecated: PermissionUseActivities has been replaced by PermissionUseEmbeddedActivities. + PermissionUseActivities = 1 << 39 + + // Allows for using Activities (applications with the EMBEDDED flag) in a voice channel. + PermissionUseEmbeddedActivities = 1 << 39 + + // Allows for using soundboard in a voice channel. + PermissionUseSoundboard = 1 << 42 + + // Allows the usage of custom soundboard sounds from other servers. + PermissionUseExternalSounds = 1 << 45 +) + +// Constants for general management. +const ( + // Allows for modification of own nickname. + PermissionChangeNickname = 1 << 26 + + // Allows for modification of other users nicknames. + PermissionManageNicknames = 1 << 27 + + // Allows management and editing of roles. + PermissionManageRoles = 1 << 28 + + // Allows management and editing of webhooks. + PermissionManageWebhooks = 1 << 29 + + // Deprecated: PermissionManageEmojis has been replaced by PermissionManageGuildExpressions. + PermissionManageEmojis = 1 << 30 + + // Allows for editing and deleting emojis, stickers, and soundboard sounds created by all users. + PermissionManageGuildExpressions = 1 << 30 + + // Allows for editing and deleting scheduled events created by all users. + PermissionManageEvents = 1 << 33 + + // Allows for viewing role subscription insights. + PermissionViewCreatorMonetizationAnalytics = 1 << 41 + + // Allows for creating emojis, stickers, and soundboard sounds, and editing and deleting those created by the current user. + PermissionCreateGuildExpressions = 1 << 43 + + // Allows for creating scheduled events, and editing and deleting those created by the current user. + PermissionCreateEvents = 1 << 44 +) + +// Constants for the different bit offsets of general permissions +const ( + // Allows creation of instant invites. + PermissionCreateInstantInvite = 1 << 0 + + // Allows kicking members. + PermissionKickMembers = 1 << 1 + + // Allows banning members. + PermissionBanMembers = 1 << 2 + + // Allows all permissions and bypasses channel permission overwrites. + PermissionAdministrator = 1 << 3 + + // Allows management and editing of channels. + PermissionManageChannels = 1 << 4 + + // Deprecated: PermissionManageServer has been replaced by PermissionManageGuild. + PermissionManageServer = 1 << 5 + + // Allows management and editing of the guild. + PermissionManageGuild = 1 << 5 + + // Allows for the addition of reactions to messages. + PermissionAddReactions = 1 << 6 + + // Allows for viewing of audit logs. + PermissionViewAuditLogs = 1 << 7 + + // Allows guild members to view a channel, which includes reading messages in text channels and joining voice channels. + PermissionViewChannel = 1 << 10 + + // Allows for viewing guild insights. + PermissionViewGuildInsights = 1 << 19 + + // Allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels. + PermissionModerateMembers = 1 << 40 + + PermissionAllText = PermissionViewChannel | + PermissionSendMessages | + PermissionSendTTSMessages | + PermissionManageMessages | + PermissionEmbedLinks | + PermissionAttachFiles | + PermissionReadMessageHistory | + PermissionMentionEveryone + PermissionAllVoice = PermissionViewChannel | + PermissionVoiceConnect | + PermissionVoiceSpeak | + PermissionVoiceMuteMembers | + PermissionVoiceDeafenMembers | + PermissionVoiceMoveMembers | + PermissionVoiceUseVAD | + PermissionVoicePrioritySpeaker + PermissionAllChannel = PermissionAllText | + PermissionAllVoice | + PermissionCreateInstantInvite | + PermissionManageRoles | + PermissionManageChannels | + PermissionAddReactions | + PermissionViewAuditLogs + PermissionAll = PermissionAllChannel | + PermissionKickMembers | + PermissionBanMembers | + PermissionManageServer | + PermissionAdministrator | + PermissionManageWebhooks | + PermissionManageEmojis +) + +// Block contains Discord JSON Error Response codes +const ( + ErrCodeGeneralError = 0 + + ErrCodeUnknownAccount = 10001 + ErrCodeUnknownApplication = 10002 + ErrCodeUnknownChannel = 10003 + ErrCodeUnknownGuild = 10004 + ErrCodeUnknownIntegration = 10005 + ErrCodeUnknownInvite = 10006 + ErrCodeUnknownMember = 10007 + ErrCodeUnknownMessage = 10008 + ErrCodeUnknownOverwrite = 10009 + ErrCodeUnknownProvider = 10010 + ErrCodeUnknownRole = 10011 + ErrCodeUnknownToken = 10012 + ErrCodeUnknownUser = 10013 + ErrCodeUnknownEmoji = 10014 + ErrCodeUnknownWebhook = 10015 + ErrCodeUnknownWebhookService = 10016 + ErrCodeUnknownSession = 10020 + ErrCodeUnknownBan = 10026 + ErrCodeUnknownSKU = 10027 + ErrCodeUnknownStoreListing = 10028 + ErrCodeUnknownEntitlement = 10029 + ErrCodeUnknownBuild = 10030 + ErrCodeUnknownLobby = 10031 + ErrCodeUnknownBranch = 10032 + ErrCodeUnknownStoreDirectoryLayout = 10033 + ErrCodeUnknownRedistributable = 10036 + ErrCodeUnknownGiftCode = 10038 + ErrCodeUnknownStream = 10049 + ErrCodeUnknownPremiumServerSubscribeCooldown = 10050 + ErrCodeUnknownGuildTemplate = 10057 + ErrCodeUnknownDiscoveryCategory = 10059 + ErrCodeUnknownSticker = 10060 + ErrCodeUnknownInteraction = 10062 + ErrCodeUnknownApplicationCommand = 10063 + ErrCodeUnknownApplicationCommandPermissions = 10066 + ErrCodeUnknownStageInstance = 10067 + ErrCodeUnknownGuildMemberVerificationForm = 10068 + ErrCodeUnknownGuildWelcomeScreen = 10069 + ErrCodeUnknownGuildScheduledEvent = 10070 + ErrCodeUnknownGuildScheduledEventUser = 10071 + ErrUnknownTag = 10087 + + ErrCodeBotsCannotUseEndpoint = 20001 + ErrCodeOnlyBotsCanUseEndpoint = 20002 + ErrCodeExplicitContentCannotBeSentToTheDesiredRecipients = 20009 + ErrCodeYouAreNotAuthorizedToPerformThisActionOnThisApplication = 20012 + ErrCodeThisActionCannotBePerformedDueToSlowmodeRateLimit = 20016 + ErrCodeOnlyTheOwnerOfThisAccountCanPerformThisAction = 20018 + ErrCodeMessageCannotBeEditedDueToAnnouncementRateLimits = 20022 + ErrCodeChannelHasHitWriteRateLimit = 20028 + ErrCodeTheWriteActionYouArePerformingOnTheServerHasHitTheWriteRateLimit = 20029 + ErrCodeStageTopicContainsNotAllowedWordsForPublicStages = 20031 + ErrCodeGuildPremiumSubscriptionLevelTooLow = 20035 + + ErrCodeMaximumGuildsReached = 30001 + ErrCodeMaximumPinsReached = 30003 + ErrCodeMaximumNumberOfRecipientsReached = 30004 + ErrCodeMaximumGuildRolesReached = 30005 + ErrCodeMaximumNumberOfWebhooksReached = 30007 + ErrCodeMaximumNumberOfEmojisReached = 30008 + ErrCodeTooManyReactions = 30010 + ErrCodeMaximumNumberOfGuildChannelsReached = 30013 + ErrCodeMaximumNumberOfAttachmentsInAMessageReached = 30015 + ErrCodeMaximumNumberOfInvitesReached = 30016 + ErrCodeMaximumNumberOfAnimatedEmojisReached = 30018 + ErrCodeMaximumNumberOfServerMembersReached = 30019 + ErrCodeMaximumNumberOfGuildDiscoverySubcategoriesReached = 30030 + ErrCodeGuildAlreadyHasATemplate = 30031 + ErrCodeMaximumNumberOfThreadParticipantsReached = 30033 + ErrCodeMaximumNumberOfBansForNonGuildMembersHaveBeenExceeded = 30035 + ErrCodeMaximumNumberOfBansFetchesHasBeenReached = 30037 + ErrCodeMaximumNumberOfUncompletedGuildScheduledEventsReached = 30038 + ErrCodeMaximumNumberOfStickersReached = 30039 + ErrCodeMaximumNumberOfPruneRequestsHasBeenReached = 30040 + ErrCodeMaximumNumberOfGuildWidgetSettingsUpdatesHasBeenReached = 30042 + ErrCodeMaximumNumberOfEditsToMessagesOlderThanOneHourReached = 30046 + ErrCodeMaximumNumberOfPinnedThreadsInForumChannelHasBeenReached = 30047 + ErrCodeMaximumNumberOfTagsInForumChannelHasBeenReached = 30048 + + ErrCodeUnauthorized = 40001 + ErrCodeActionRequiredVerifiedAccount = 40002 + ErrCodeOpeningDirectMessagesTooFast = 40003 + ErrCodeSendMessagesHasBeenTemporarilyDisabled = 40004 + ErrCodeRequestEntityTooLarge = 40005 + ErrCodeFeatureTemporarilyDisabledServerSide = 40006 + ErrCodeUserIsBannedFromThisGuild = 40007 + ErrCodeTargetIsNotConnectedToVoice = 40032 + ErrCodeMessageAlreadyCrossposted = 40033 + ErrCodeAnApplicationWithThatNameAlreadyExists = 40041 + ErrCodeInteractionHasAlreadyBeenAcknowledged = 40060 + ErrCodeTagNamesMustBeUnique = 40061 + + ErrCodeMissingAccess = 50001 + ErrCodeInvalidAccountType = 50002 + ErrCodeCannotExecuteActionOnDMChannel = 50003 + ErrCodeEmbedDisabled = 50004 + ErrCodeGuildWidgetDisabled = 50004 + ErrCodeCannotEditFromAnotherUser = 50005 + ErrCodeCannotSendEmptyMessage = 50006 + ErrCodeCannotSendMessagesToThisUser = 50007 + ErrCodeCannotSendMessagesInVoiceChannel = 50008 + ErrCodeChannelVerificationLevelTooHigh = 50009 + ErrCodeOAuth2ApplicationDoesNotHaveBot = 50010 + ErrCodeOAuth2ApplicationLimitReached = 50011 + ErrCodeInvalidOAuthState = 50012 + ErrCodeMissingPermissions = 50013 + ErrCodeInvalidAuthenticationToken = 50014 + ErrCodeTooFewOrTooManyMessagesToDelete = 50016 + ErrCodeCanOnlyPinMessageToOriginatingChannel = 50019 + ErrCodeInviteCodeWasEitherInvalidOrTaken = 50020 + ErrCodeCannotExecuteActionOnSystemMessage = 50021 + ErrCodeCannotExecuteActionOnThisChannelType = 50024 + ErrCodeInvalidOAuth2AccessTokenProvided = 50025 + ErrCodeMissingRequiredOAuth2Scope = 50026 + ErrCodeInvalidWebhookTokenProvided = 50027 + ErrCodeInvalidRole = 50028 + ErrCodeInvalidRecipients = 50033 + ErrCodeMessageProvidedTooOldForBulkDelete = 50034 + ErrCodeInvalidFormBody = 50035 + ErrCodeInviteAcceptedToGuildApplicationsBotNotIn = 50036 + ErrCodeInvalidAPIVersionProvided = 50041 + ErrCodeFileUploadedExceedsTheMaximumSize = 50045 + ErrCodeInvalidFileUploaded = 50046 + ErrCodeInvalidGuild = 50055 + ErrCodeInvalidMessageType = 50068 + ErrCodeCannotDeleteAChannelRequiredForCommunityGuilds = 50074 + ErrCodeInvalidStickerSent = 50081 + ErrCodePerformedOperationOnArchivedThread = 50083 + ErrCodeBeforeValueIsEarlierThanThreadCreationDate = 50085 + ErrCodeCommunityServerChannelsMustBeTextChannels = 50086 + ErrCodeThisServerIsNotAvailableInYourLocation = 50095 + ErrCodeThisServerNeedsMonetizationEnabledInOrderToPerformThisAction = 50097 + ErrCodeThisServerNeedsMoreBoostsToPerformThisAction = 50101 + ErrCodeTheRequestBodyContainsInvalidJSON = 50109 + + ErrCodeNoUsersWithDiscordTagExist = 80004 + + ErrCodeReactionBlocked = 90001 + + ErrCodeAPIResourceIsCurrentlyOverloaded = 130000 + + ErrCodeTheStageIsAlreadyOpen = 150006 + + ErrCodeCannotReplyWithoutPermissionToReadMessageHistory = 160002 + ErrCodeThreadAlreadyCreatedForThisMessage = 160004 + ErrCodeThreadIsLocked = 160005 + ErrCodeMaximumNumberOfActiveThreadsReached = 160006 + ErrCodeMaximumNumberOfActiveAnnouncementThreadsReached = 160007 + + ErrCodeInvalidJSONForUploadedLottieFile = 170001 + ErrCodeUploadedLottiesCannotContainRasterizedImages = 170002 + ErrCodeStickerMaximumFramerateExceeded = 170003 + ErrCodeStickerFrameCountExceedsMaximumOfOneThousandFrames = 170004 + ErrCodeLottieAnimationMaximumDimensionsExceeded = 170005 + ErrCodeStickerFrameRateOutOfRange = 170006 + ErrCodeStickerAnimationDurationExceedsMaximumOfFiveSeconds = 170007 + + ErrCodeCannotUpdateAFinishedEvent = 180000 + ErrCodeFailedToCreateStageNeededForStageEvent = 180002 + + ErrCodeCannotEnableOnboardingRequirementsAreNotMet = 350000 + ErrCodeCannotUpdateOnboardingWhileBelowRequirements = 350001 +) + +// Intent is the type of a Gateway Intent +// https://discord.com/developers/docs/topics/gateway#gateway-intents +type Intent int + +// Constants for the different bit offsets of intents +const ( + IntentGuilds Intent = 1 << 0 + IntentGuildMembers Intent = 1 << 1 + IntentGuildModeration Intent = 1 << 2 + IntentGuildEmojis Intent = 1 << 3 + IntentGuildIntegrations Intent = 1 << 4 + IntentGuildWebhooks Intent = 1 << 5 + IntentGuildInvites Intent = 1 << 6 + IntentGuildVoiceStates Intent = 1 << 7 + IntentGuildPresences Intent = 1 << 8 + IntentGuildMessages Intent = 1 << 9 + IntentGuildMessageReactions Intent = 1 << 10 + IntentGuildMessageTyping Intent = 1 << 11 + IntentDirectMessages Intent = 1 << 12 + IntentDirectMessageReactions Intent = 1 << 13 + IntentDirectMessageTyping Intent = 1 << 14 + IntentMessageContent Intent = 1 << 15 + IntentGuildScheduledEvents Intent = 1 << 16 + IntentAutoModerationConfiguration Intent = 1 << 20 + IntentAutoModerationExecution Intent = 1 << 21 + IntentGuildMessagePolls Intent = 1 << 24 + IntentDirectMessagePolls Intent = 1 << 25 + + // TODO: remove when compatibility is not needed + + IntentGuildBans Intent = IntentGuildModeration + + IntentsGuilds Intent = 1 << 0 + IntentsGuildMembers Intent = 1 << 1 + IntentsGuildBans Intent = 1 << 2 + IntentsGuildEmojis Intent = 1 << 3 + IntentsGuildIntegrations Intent = 1 << 4 + IntentsGuildWebhooks Intent = 1 << 5 + IntentsGuildInvites Intent = 1 << 6 + IntentsGuildVoiceStates Intent = 1 << 7 + IntentsGuildPresences Intent = 1 << 8 + IntentsGuildMessages Intent = 1 << 9 + IntentsGuildMessageReactions Intent = 1 << 10 + IntentsGuildMessageTyping Intent = 1 << 11 + IntentsDirectMessages Intent = 1 << 12 + IntentsDirectMessageReactions Intent = 1 << 13 + IntentsDirectMessageTyping Intent = 1 << 14 + IntentsMessageContent Intent = 1 << 15 + IntentsGuildScheduledEvents Intent = 1 << 16 + + IntentsAllWithoutPrivileged = IntentGuilds | + IntentGuildBans | + IntentGuildEmojis | + IntentGuildIntegrations | + IntentGuildWebhooks | + IntentGuildInvites | + IntentGuildVoiceStates | + IntentGuildMessages | + IntentGuildMessageReactions | + IntentGuildMessageTyping | + IntentDirectMessages | + IntentDirectMessageReactions | + IntentDirectMessageTyping | + IntentGuildScheduledEvents | + IntentAutoModerationConfiguration | + IntentAutoModerationExecution + + IntentsAll = IntentsAllWithoutPrivileged | + IntentGuildMembers | + IntentGuildPresences | + IntentMessageContent + + IntentsNone Intent = 0 +) + +// MakeIntent used to help convert a gateway intent value for use in the Identify structure; +// this was useful to help support the use of a pointer type when intents were optional. +// This is now a no-op, and is not necessary to use. +func MakeIntent(intents Intent) Intent { + return intents +} diff --git a/vendor/github.com/bwmarrin/discordgo/user.go b/vendor/github.com/bwmarrin/discordgo/user.go new file mode 100644 index 000000000..9cf480245 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/user.go @@ -0,0 +1,162 @@ +package discordgo + +import ( + "strconv" +) + +// UserFlags is the flags of "user" (see UserFlags* consts) +// https://discord.com/developers/docs/resources/user#user-object-user-flags +type UserFlags int + +// Valid UserFlags values +const ( + UserFlagDiscordEmployee UserFlags = 1 << 0 + UserFlagDiscordPartner UserFlags = 1 << 1 + UserFlagHypeSquadEvents UserFlags = 1 << 2 + UserFlagBugHunterLevel1 UserFlags = 1 << 3 + UserFlagHouseBravery UserFlags = 1 << 6 + UserFlagHouseBrilliance UserFlags = 1 << 7 + UserFlagHouseBalance UserFlags = 1 << 8 + UserFlagEarlySupporter UserFlags = 1 << 9 + UserFlagTeamUser UserFlags = 1 << 10 + UserFlagSystem UserFlags = 1 << 12 + UserFlagBugHunterLevel2 UserFlags = 1 << 14 + UserFlagVerifiedBot UserFlags = 1 << 16 + UserFlagVerifiedBotDeveloper UserFlags = 1 << 17 + UserFlagDiscordCertifiedModerator UserFlags = 1 << 18 + UserFlagBotHTTPInteractions UserFlags = 1 << 19 + UserFlagActiveBotDeveloper UserFlags = 1 << 22 +) + +// UserPremiumType is the type of premium (nitro) subscription a user has (see UserPremiumType* consts). +// https://discord.com/developers/docs/resources/user#user-object-premium-types +type UserPremiumType int + +// Valid UserPremiumType values. +const ( + UserPremiumTypeNone UserPremiumType = 0 + UserPremiumTypeNitroClassic UserPremiumType = 1 + UserPremiumTypeNitro UserPremiumType = 2 + UserPremiumTypeNitroBasic UserPremiumType = 3 +) + +// A User stores all data for an individual Discord user. +type User struct { + // The ID of the user. + ID string `json:"id"` + + // The email of the user. This is only present when + // the application possesses the email scope for the user. + Email string `json:"email"` + + // The user's username. + Username string `json:"username"` + + // The hash of the user's avatar. Use Session.UserAvatar + // to retrieve the avatar itself. + Avatar string `json:"avatar"` + + // The user's chosen language option. + Locale string `json:"locale"` + + // The discriminator of the user (4 numbers after name). + Discriminator string `json:"discriminator"` + + // The user's display name, if it is set. + // For bots, this is the application name. + GlobalName string `json:"global_name"` + + // The token of the user. This is only present for + // the user represented by the current session. + Token string `json:"token"` + + // Whether the user's email is verified. + Verified bool `json:"verified"` + + // Whether the user has multi-factor authentication enabled. + MFAEnabled bool `json:"mfa_enabled"` + + // The hash of the user's banner image. + Banner string `json:"banner"` + + // User's banner color, encoded as an integer representation of hexadecimal color code + AccentColor int `json:"accent_color"` + + // Whether the user is a bot. + Bot bool `json:"bot"` + + // The public flags on a user's account. + // This is a combination of bit masks; the presence of a certain flag can + // be checked by performing a bitwise AND between this int and the flag. + PublicFlags UserFlags `json:"public_flags"` + + // The type of Nitro subscription on a user's account. + // Only available when the request is authorized via a Bearer token. + PremiumType UserPremiumType `json:"premium_type"` + + // Whether the user is an Official Discord System user (part of the urgent message system). + System bool `json:"system"` + + // The flags on a user's account. + // Only available when the request is authorized via a Bearer token. + Flags int `json:"flags"` +} + +// String returns a unique identifier of the form username#discriminator +// or just username, if the discriminator is set to "0". +func (u *User) String() string { + // If the user has been migrated from the legacy username system, their discriminator is "0". + // See https://support-dev.discord.com/hc/en-us/articles/13667755828631 + if u.Discriminator == "0" { + return u.Username + } + + return u.Username + "#" + u.Discriminator +} + +// Mention return a string which mentions the user +func (u *User) Mention() string { + return "<@" + u.ID + ">" +} + +// AvatarURL returns a URL to the user's avatar. +// +// size: The size of the user's avatar as a power of two +// if size is an empty string, no size parameter will +// be added to the URL. +func (u *User) AvatarURL(size string) string { + return avatarURL( + u.Avatar, + EndpointDefaultUserAvatar(u.DefaultAvatarIndex()), + EndpointUserAvatar(u.ID, u.Avatar), + EndpointUserAvatarAnimated(u.ID, u.Avatar), + size, + ) +} + +// BannerURL returns the URL of the users's banner image. +// +// size: The size of the desired banner image as a power of two +// Image size can be any power of two between 16 and 4096. +func (u *User) BannerURL(size string) string { + return bannerURL(u.Banner, EndpointUserBanner(u.ID, u.Banner), EndpointUserBannerAnimated(u.ID, u.Banner), size) +} + +// DefaultAvatarIndex returns the index of the user's default avatar. +func (u *User) DefaultAvatarIndex() int { + if u.Discriminator == "0" { + id, _ := strconv.ParseUint(u.ID, 10, 64) + return int((id >> 22) % 6) + } + + id, _ := strconv.Atoi(u.Discriminator) + return id % 5 +} + +// DisplayName returns the user's global name if they have one, otherwise it returns their username. +func (u *User) DisplayName() string { + if u.GlobalName != "" { + return u.GlobalName + } + return u.Username +} diff --git a/vendor/github.com/bwmarrin/discordgo/util.go b/vendor/github.com/bwmarrin/discordgo/util.go new file mode 100644 index 000000000..957f30187 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/util.go @@ -0,0 +1,125 @@ +package discordgo + +import ( + "bytes" + "fmt" + "io" + "mime/multipart" + "net/textproto" + "strconv" + "strings" + "time" +) + +// SnowflakeTimestamp returns the creation time of a Snowflake ID relative to the creation of Discord. +func SnowflakeTimestamp(ID string) (t time.Time, err error) { + i, err := strconv.ParseInt(ID, 10, 64) + if err != nil { + return + } + timestamp := (i >> 22) + 1420070400000 + t = time.Unix(0, timestamp*1000000) + return +} + +// MultipartBodyWithJSON returns the contentType and body for a discord request +// data : The object to encode for payload_json in the multipart request +// files : Files to include in the request +func MultipartBodyWithJSON(data interface{}, files []*File) (requestContentType string, requestBody []byte, err error) { + body := &bytes.Buffer{} + bodywriter := multipart.NewWriter(body) + + payload, err := Marshal(data) + if err != nil { + return + } + + var p io.Writer + + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", `form-data; name="payload_json"`) + h.Set("Content-Type", "application/json") + + p, err = bodywriter.CreatePart(h) + if err != nil { + return + } + + if _, err = p.Write(payload); err != nil { + return + } + + for i, file := range files { + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="files[%d]"; filename="%s"`, i, quoteEscaper.Replace(file.Name))) + contentType := file.ContentType + if contentType == "" { + contentType = "application/octet-stream" + } + h.Set("Content-Type", contentType) + + p, err = bodywriter.CreatePart(h) + if err != nil { + return + } + + if _, err = io.Copy(p, file.Reader); err != nil { + return + } + } + + err = bodywriter.Close() + if err != nil { + return + } + + return bodywriter.FormDataContentType(), body.Bytes(), nil +} + +func avatarURL(avatarHash, defaultAvatarURL, staticAvatarURL, animatedAvatarURL, size string) string { + var URL string + if avatarHash == "" { + URL = defaultAvatarURL + } else if strings.HasPrefix(avatarHash, "a_") { + URL = animatedAvatarURL + } else { + URL = staticAvatarURL + } + + if size != "" { + return URL + "?size=" + size + } + return URL +} + +func bannerURL(bannerHash, staticBannerURL, animatedBannerURL, size string) string { + var URL string + if bannerHash == "" { + return "" + } else if strings.HasPrefix(bannerHash, "a_") { + URL = animatedBannerURL + } else { + URL = staticBannerURL + } + + if size != "" { + return URL + "?size=" + size + } + return URL +} + +func iconURL(iconHash, staticIconURL, animatedIconURL, size string) string { + var URL string + if iconHash == "" { + return "" + } else if strings.HasPrefix(iconHash, "a_") { + URL = animatedIconURL + } else { + URL = staticIconURL + } + + if size != "" { + return URL + "?size=" + size + } + return URL +} diff --git a/vendor/github.com/bwmarrin/discordgo/voice.go b/vendor/github.com/bwmarrin/discordgo/voice.go new file mode 100644 index 000000000..e9c89bee1 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/voice.go @@ -0,0 +1,950 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains code related to Discord voice suppport + +package discordgo + +import ( + "encoding/binary" + "encoding/json" + "fmt" + "net" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" + "golang.org/x/crypto/nacl/secretbox" +) + +// ------------------------------------------------------------------------------------------------ +// Code related to both VoiceConnection Websocket and UDP connections. +// ------------------------------------------------------------------------------------------------ + +// A VoiceConnection struct holds all the data and functions related to a Discord Voice Connection. +type VoiceConnection struct { + sync.RWMutex + + Debug bool // If true, print extra logging -- DEPRECATED + LogLevel int + Ready bool // If true, voice is ready to send/receive audio + UserID string + GuildID string + ChannelID string + deaf bool + mute bool + speaking bool + reconnecting bool // If true, voice connection is trying to reconnect + + OpusSend chan []byte // Chan for sending opus audio + OpusRecv chan *Packet // Chan for receiving opus audio + + wsConn *websocket.Conn + wsMutex sync.Mutex + udpConn *net.UDPConn + session *Session + + sessionID string + token string + endpoint string + + // Used to send a close signal to goroutines + close chan struct{} + + // Used to allow blocking until connected + connected chan bool + + // Used to pass the sessionid from onVoiceStateUpdate + // sessionRecv chan string UNUSED ATM + + op4 voiceOP4 + op2 voiceOP2 + + voiceSpeakingUpdateHandlers []VoiceSpeakingUpdateHandler +} + +// VoiceSpeakingUpdateHandler type provides a function definition for the +// VoiceSpeakingUpdate event +type VoiceSpeakingUpdateHandler func(vc *VoiceConnection, vs *VoiceSpeakingUpdate) + +// Speaking sends a speaking notification to Discord over the voice websocket. +// This must be sent as true prior to sending audio and should be set to false +// once finished sending audio. +// b : Send true if speaking, false if not. +func (v *VoiceConnection) Speaking(b bool) (err error) { + + v.log(LogDebug, "called (%t)", b) + + type voiceSpeakingData struct { + Speaking bool `json:"speaking"` + Delay int `json:"delay"` + } + + type voiceSpeakingOp struct { + Op int `json:"op"` // Always 5 + Data voiceSpeakingData `json:"d"` + } + + if v.wsConn == nil { + return fmt.Errorf("no VoiceConnection websocket") + } + + data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}} + v.wsMutex.Lock() + err = v.wsConn.WriteJSON(data) + v.wsMutex.Unlock() + + v.Lock() + defer v.Unlock() + if err != nil { + v.speaking = false + v.log(LogError, "Speaking() write json error, %s", err) + return + } + + v.speaking = b + + return +} + +// ChangeChannel sends Discord a request to change channels within a Guild +// !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin +func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) { + + v.log(LogInformational, "called") + + data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}} + v.session.wsMutex.Lock() + err = v.session.wsConn.WriteJSON(data) + v.session.wsMutex.Unlock() + if err != nil { + return + } + v.ChannelID = channelID + v.deaf = deaf + v.mute = mute + v.speaking = false + + return +} + +// Disconnect disconnects from this voice channel and closes the websocket +// and udp connections to Discord. +func (v *VoiceConnection) Disconnect() (err error) { + + // Send a OP4 with a nil channel to disconnect + v.Lock() + if v.sessionID != "" { + data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} + v.session.wsMutex.Lock() + err = v.session.wsConn.WriteJSON(data) + v.session.wsMutex.Unlock() + v.sessionID = "" + } + v.Unlock() + + // Close websocket and udp connections + v.Close() + + v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID) + + v.session.Lock() + delete(v.session.VoiceConnections, v.GuildID) + v.session.Unlock() + + return +} + +// Close closes the voice ws and udp connections +func (v *VoiceConnection) Close() { + + v.log(LogInformational, "called") + + v.Lock() + defer v.Unlock() + + v.Ready = false + v.speaking = false + + if v.close != nil { + v.log(LogInformational, "closing v.close") + close(v.close) + v.close = nil + } + + if v.udpConn != nil { + v.log(LogInformational, "closing udp") + err := v.udpConn.Close() + if err != nil { + v.log(LogError, "error closing udp connection, %s", err) + } + v.udpConn = nil + } + + if v.wsConn != nil { + v.log(LogInformational, "sending close frame") + + // To cleanly close a connection, a client should send a close + // frame and wait for the server to close the connection. + v.wsMutex.Lock() + err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) + v.wsMutex.Unlock() + if err != nil { + v.log(LogError, "error closing websocket, %s", err) + } + + // TODO: Wait for Discord to actually close the connection. + time.Sleep(1 * time.Second) + + v.log(LogInformational, "closing websocket") + err = v.wsConn.Close() + if err != nil { + v.log(LogError, "error closing websocket, %s", err) + } + + v.wsConn = nil + } +} + +// AddHandler adds a Handler for VoiceSpeakingUpdate events. +func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) { + v.Lock() + defer v.Unlock() + + v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h) +} + +// VoiceSpeakingUpdate is a struct for a VoiceSpeakingUpdate event. +type VoiceSpeakingUpdate struct { + UserID string `json:"user_id"` + SSRC int `json:"ssrc"` + Speaking bool `json:"speaking"` +} + +// ------------------------------------------------------------------------------------------------ +// Unexported Internal Functions Below. +// ------------------------------------------------------------------------------------------------ + +// A voiceOP4 stores the data for the voice operation 4 websocket event +// which provides us with the NaCl SecretBox encryption key +type voiceOP4 struct { + SecretKey [32]byte `json:"secret_key"` + Mode string `json:"mode"` +} + +// A voiceOP2 stores the data for the voice operation 2 websocket event +// which is sort of like the voice READY packet +type voiceOP2 struct { + SSRC uint32 `json:"ssrc"` + Port int `json:"port"` + Modes []string `json:"modes"` + HeartbeatInterval time.Duration `json:"heartbeat_interval"` + IP string `json:"ip"` +} + +// WaitUntilConnected waits for the Voice Connection to +// become ready, if it does not become ready it returns an err +func (v *VoiceConnection) waitUntilConnected() error { + + v.log(LogInformational, "called") + + i := 0 + for { + v.RLock() + ready := v.Ready + v.RUnlock() + if ready { + return nil + } + + if i > 10 { + return fmt.Errorf("timeout waiting for voice") + } + + time.Sleep(1 * time.Second) + i++ + } +} + +// Open opens a voice connection. This should be called +// after VoiceChannelJoin is used and the data VOICE websocket events +// are captured. +func (v *VoiceConnection) open() (err error) { + + v.log(LogInformational, "called") + + v.Lock() + defer v.Unlock() + + // Don't open a websocket if one is already open + if v.wsConn != nil { + v.log(LogWarning, "refusing to overwrite non-nil websocket") + return + } + + // TODO temp? loop to wait for the SessionID + i := 0 + for { + if v.sessionID != "" { + break + } + + if i > 20 { // only loop for up to 1 second total + return fmt.Errorf("did not receive voice Session ID in time") + } + // Release the lock, so sessionID can be populated upon receiving a VoiceStateUpdate event. + v.Unlock() + time.Sleep(50 * time.Millisecond) + i++ + v.Lock() + } + + // Connect to VoiceConnection Websocket + vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80") + v.log(LogInformational, "connecting to voice endpoint %s", vg) + v.wsConn, _, err = v.session.Dialer.Dial(vg, nil) + if err != nil { + v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err) + v.log(LogDebug, "voice struct: %#v\n", v) + return + } + + type voiceHandshakeData struct { + ServerID string `json:"server_id"` + UserID string `json:"user_id"` + SessionID string `json:"session_id"` + Token string `json:"token"` + } + type voiceHandshakeOp struct { + Op int `json:"op"` // Always 0 + Data voiceHandshakeData `json:"d"` + } + data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}} + + v.wsMutex.Lock() + err = v.wsConn.WriteJSON(data) + v.wsMutex.Unlock() + if err != nil { + v.log(LogWarning, "error sending init packet, %s", err) + return + } + + v.close = make(chan struct{}) + go v.wsListen(v.wsConn, v.close) + + // add loop/check for Ready bool here? + // then return false if not ready? + // but then wsListen will also err. + + return +} + +// wsListen listens on the voice websocket for messages and passes them +// to the voice event handler. This is automatically called by the Open func +func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) { + + v.log(LogInformational, "called") + + for { + _, message, err := v.wsConn.ReadMessage() + if err != nil { + // 4014 indicates a manual disconnection by someone in the guild; + // we shouldn't reconnect. + if websocket.IsCloseError(err, 4014) { + v.log(LogInformational, "received 4014 manual disconnection") + + // Abandon the voice WS connection + v.Lock() + v.wsConn = nil + v.Unlock() + + // Wait for VOICE_SERVER_UPDATE. + // When the bot is moved by the user to another voice channel, + // VOICE_SERVER_UPDATE is received after the code 4014. + for i := 0; i < 5; i++ { // TODO: temp, wait for VoiceServerUpdate. + <-time.After(1 * time.Second) + + v.RLock() + reconnected := v.wsConn != nil + v.RUnlock() + if !reconnected { + continue + } + v.log(LogInformational, "successfully reconnected after 4014 manual disconnection") + return + } + + // When VOICE_SERVER_UPDATE is not received, disconnect as usual. + v.log(LogInformational, "disconnect due to 4014 manual disconnection") + + v.session.Lock() + delete(v.session.VoiceConnections, v.GuildID) + v.session.Unlock() + + v.Close() + + return + } + + // Detect if we have been closed manually. If a Close() has already + // happened, the websocket we are listening on will be different to the + // current session. + v.RLock() + sameConnection := v.wsConn == wsConn + v.RUnlock() + if sameConnection { + + v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err) + + // Start reconnect goroutine then exit. + go v.reconnect() + } + return + } + + // Pass received message to voice event handler + select { + case <-close: + return + default: + go v.onEvent(message) + } + } +} + +// wsEvent handles any voice websocket events. This is only called by the +// wsListen() function. +func (v *VoiceConnection) onEvent(message []byte) { + + v.log(LogDebug, "received: %s", string(message)) + + var e Event + if err := json.Unmarshal(message, &e); err != nil { + v.log(LogError, "unmarshall error, %s", err) + return + } + + switch e.Operation { + + case 2: // READY + + if err := json.Unmarshal(e.RawData, &v.op2); err != nil { + v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData)) + return + } + + // Start the voice websocket heartbeat to keep the connection alive + go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval) + // TODO monitor a chan/bool to verify this was successful + + // Start the UDP connection + err := v.udpOpen() + if err != nil { + v.log(LogError, "error opening udp connection, %s", err) + return + } + + // Start the opusSender. + // TODO: Should we allow 48000/960 values to be user defined? + if v.OpusSend == nil { + v.OpusSend = make(chan []byte, 2) + } + go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960) + + // Start the opusReceiver + if !v.deaf { + if v.OpusRecv == nil { + v.OpusRecv = make(chan *Packet, 2) + } + + go v.opusReceiver(v.udpConn, v.close, v.OpusRecv) + } + + return + + case 3: // HEARTBEAT response + // add code to use this to track latency? + return + + case 4: // udp encryption secret key + v.Lock() + defer v.Unlock() + + v.op4 = voiceOP4{} + if err := json.Unmarshal(e.RawData, &v.op4); err != nil { + v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData)) + return + } + return + + case 5: + if len(v.voiceSpeakingUpdateHandlers) == 0 { + return + } + + voiceSpeakingUpdate := &VoiceSpeakingUpdate{} + if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil { + v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData)) + return + } + + for _, h := range v.voiceSpeakingUpdateHandlers { + h(v, voiceSpeakingUpdate) + } + + default: + v.log(LogDebug, "unknown voice operation, %d, %s", e.Operation, string(e.RawData)) + } + + return +} + +type voiceHeartbeatOp struct { + Op int `json:"op"` // Always 3 + Data int `json:"d"` +} + +// NOTE :: When a guild voice server changes how do we shut this down +// properly, so a new connection can be setup without fuss? +// +// wsHeartbeat sends regular heartbeats to voice Discord so it knows the client +// is still connected. If you do not send these heartbeats Discord will +// disconnect the websocket connection after a few seconds. +func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) { + + if close == nil || wsConn == nil { + return + } + + var err error + ticker := time.NewTicker(i * time.Millisecond) + defer ticker.Stop() + for { + v.log(LogDebug, "sending heartbeat packet") + v.wsMutex.Lock() + err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())}) + v.wsMutex.Unlock() + if err != nil { + v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err) + return + } + + select { + case <-ticker.C: + // continue loop and send heartbeat + case <-close: + return + } + } +} + +// ------------------------------------------------------------------------------------------------ +// Code related to the VoiceConnection UDP connection +// ------------------------------------------------------------------------------------------------ + +type voiceUDPData struct { + Address string `json:"address"` // Public IP of machine running this code + Port uint16 `json:"port"` // UDP Port of machine running this code + Mode string `json:"mode"` // always "xsalsa20_poly1305" +} + +type voiceUDPD struct { + Protocol string `json:"protocol"` // Always "udp" ? + Data voiceUDPData `json:"data"` +} + +type voiceUDPOp struct { + Op int `json:"op"` // Always 1 + Data voiceUDPD `json:"d"` +} + +// udpOpen opens a UDP connection to the voice server and completes the +// initial required handshake. This connection is left open in the session +// and can be used to send or receive audio. This should only be called +// from voice.wsEvent OP2 +func (v *VoiceConnection) udpOpen() (err error) { + + v.Lock() + defer v.Unlock() + + if v.wsConn == nil { + return fmt.Errorf("nil voice websocket") + } + + if v.udpConn != nil { + return fmt.Errorf("udp connection already open") + } + + if v.close == nil { + return fmt.Errorf("nil close channel") + } + + if v.endpoint == "" { + return fmt.Errorf("empty endpoint") + } + + host := v.op2.IP + ":" + strconv.Itoa(v.op2.Port) + addr, err := net.ResolveUDPAddr("udp", host) + if err != nil { + v.log(LogWarning, "error resolving udp host %s, %s", host, err) + return + } + + v.log(LogInformational, "connecting to udp addr %s", addr.String()) + v.udpConn, err = net.DialUDP("udp", nil, addr) + if err != nil { + v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err) + return + } + + // Create a 74 byte array to store the packet data + sb := make([]byte, 74) + binary.BigEndian.PutUint16(sb, 1) // Packet type (0x1 is request, 0x2 is response) + binary.BigEndian.PutUint16(sb[2:], 70) // Packet length (excluding type and length fields) + binary.BigEndian.PutUint32(sb[4:], v.op2.SSRC) // The SSRC code from the Op 2 VoiceConnection event + + // And send that data over the UDP connection to Discord. + _, err = v.udpConn.Write(sb) + if err != nil { + v.log(LogWarning, "udp write error to %s, %s", addr.String(), err) + return + } + + // Create a 74 byte array and listen for the initial handshake response + // from Discord. Once we get it parse the IP and PORT information out + // of the response. This should be our public IP and PORT as Discord + // saw us. + rb := make([]byte, 74) + rlen, _, err := v.udpConn.ReadFromUDP(rb) + if err != nil { + v.log(LogWarning, "udp read error, %s, %s", addr.String(), err) + return + } + + if rlen < 74 { + v.log(LogWarning, "received udp packet too small") + return fmt.Errorf("received udp packet too small") + } + + // Loop over position 8 through 71 to grab the IP address. + var ip string + for i := 8; i < len(rb)-2; i++ { + if rb[i] == 0 { + break + } + ip += string(rb[i]) + } + + // Grab port from position 72 and 73 + port := binary.BigEndian.Uint16(rb[len(rb)-2:]) + + // Take the data from above and send it back to Discord to finalize + // the UDP connection handshake. + data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}} + + v.wsMutex.Lock() + err = v.wsConn.WriteJSON(data) + v.wsMutex.Unlock() + if err != nil { + v.log(LogWarning, "udp write error, %#v, %s", data, err) + return + } + + // start udpKeepAlive + go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second) + // TODO: find a way to check that it fired off okay + + return +} + +// udpKeepAlive sends a udp packet to keep the udp connection open +// This is still a bit of a "proof of concept" +func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) { + + if udpConn == nil || close == nil { + return + } + + var err error + var sequence uint64 + + packet := make([]byte, 8) + + ticker := time.NewTicker(i) + defer ticker.Stop() + for { + + binary.LittleEndian.PutUint64(packet, sequence) + sequence++ + + _, err = udpConn.Write(packet) + if err != nil { + v.log(LogError, "write error, %s", err) + return + } + + select { + case <-ticker.C: + // continue loop and send keepalive + case <-close: + return + } + } +} + +// opusSender will listen on the given channel and send any +// pre-encoded opus audio to Discord. Supposedly. +func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) { + + if udpConn == nil || close == nil { + return + } + + // VoiceConnection is now ready to receive audio packets + // TODO: this needs reviewed as I think there must be a better way. + v.Lock() + v.Ready = true + v.Unlock() + defer func() { + v.Lock() + v.Ready = false + v.Unlock() + }() + + var sequence uint16 + var timestamp uint32 + var recvbuf []byte + var ok bool + udpHeader := make([]byte, 12) + var nonce [24]byte + + // build the parts that don't change in the udpHeader + udpHeader[0] = 0x80 + udpHeader[1] = 0x78 + binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC) + + // start a send loop that loops until buf chan is closed + ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000))) + defer ticker.Stop() + for { + + // Get data from chan. If chan is closed, return. + select { + case <-close: + return + case recvbuf, ok = <-opus: + if !ok { + return + } + // else, continue loop + } + + v.RLock() + speaking := v.speaking + v.RUnlock() + if !speaking { + err := v.Speaking(true) + if err != nil { + v.log(LogError, "error sending speaking packet, %s", err) + } + } + + // Add sequence and timestamp to udpPacket + binary.BigEndian.PutUint16(udpHeader[2:], sequence) + binary.BigEndian.PutUint32(udpHeader[4:], timestamp) + + // encrypt the opus data + copy(nonce[:], udpHeader) + v.RLock() + sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey) + v.RUnlock() + + // block here until we're exactly at the right time :) + // Then send rtp audio packet to Discord over UDP + select { + case <-close: + return + case <-ticker.C: + // continue + } + _, err := udpConn.Write(sendbuf) + + if err != nil { + v.log(LogError, "udp write error, %s", err) + v.log(LogDebug, "voice struct: %#v\n", v) + return + } + + if (sequence) == 0xFFFF { + sequence = 0 + } else { + sequence++ + } + + if (timestamp + uint32(size)) >= 0xFFFFFFFF { + timestamp = 0 + } else { + timestamp += uint32(size) + } + } +} + +// A Packet contains the headers and content of a received voice packet. +type Packet struct { + SSRC uint32 + Sequence uint16 + Timestamp uint32 + Type []byte + Opus []byte + PCM []int16 +} + +// opusReceiver listens on the UDP socket for incoming packets +// and sends them across the given channel +// NOTE :: This function may change names later. +func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) { + + if udpConn == nil || close == nil { + return + } + + recvbuf := make([]byte, 1024) + var nonce [24]byte + + for { + rlen, err := udpConn.Read(recvbuf) + if err != nil { + // Detect if we have been closed manually. If a Close() has already + // happened, the udp connection we are listening on will be different + // to the current session. + v.RLock() + sameConnection := v.udpConn == udpConn + v.RUnlock() + if sameConnection { + + v.log(LogError, "udp read error, %s, %s", v.endpoint, err) + v.log(LogDebug, "voice struct: %#v\n", v) + + go v.reconnect() + } + return + } + + select { + case <-close: + return + default: + // continue loop + } + + // For now, skip anything except audio. + if rlen < 12 || (recvbuf[0] != 0x80 && recvbuf[0] != 0x90) { + continue + } + + // build a audio packet struct + p := Packet{} + p.Type = recvbuf[0:2] + p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4]) + p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8]) + p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12]) + // decrypt opus data + copy(nonce[:], recvbuf[0:12]) + + if opus, ok := secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey); ok { + p.Opus = opus + } else { + continue + } + + // extension bit set, and not a RTCP packet + if ((recvbuf[0] & 0x10) == 0x10) && ((recvbuf[1] & 0x80) == 0) { + // get extended header length + extlen := binary.BigEndian.Uint16(p.Opus[2:4]) + // 4 bytes (ext header header) + 4*extlen (ext header data) + shift := int(4 + 4*extlen) + if len(p.Opus) > shift { + p.Opus = p.Opus[shift:] + } + } + + if c != nil { + select { + case c <- &p: + case <-close: + return + } + } + } +} + +// Reconnect will close down a voice connection then immediately try to +// reconnect to that session. +// NOTE : This func is messy and a WIP while I find what works. +// It will be cleaned up once a proven stable option is flushed out. +// aka: this is ugly shit code, please don't judge too harshly. +func (v *VoiceConnection) reconnect() { + + v.log(LogInformational, "called") + + v.Lock() + if v.reconnecting { + v.log(LogInformational, "already reconnecting to channel %s, exiting", v.ChannelID) + v.Unlock() + return + } + v.reconnecting = true + v.Unlock() + + defer func() { + v.Lock() + v.reconnecting = false + v.Unlock() + }() + + // Close any currently open connections + v.Close() + + wait := time.Duration(1) + for { + + <-time.After(wait * time.Second) + wait *= 2 + if wait > 600 { + wait = 600 + } + + if v.session.DataReady == false || v.session.wsConn == nil { + v.log(LogInformational, "cannot reconnect to channel %s with unready session", v.ChannelID) + continue + } + + v.log(LogInformational, "trying to reconnect to channel %s", v.ChannelID) + + _, err := v.session.ChannelVoiceJoin(v.GuildID, v.ChannelID, v.mute, v.deaf) + if err == nil { + v.log(LogInformational, "successfully reconnected to channel %s", v.ChannelID) + return + } + + v.log(LogInformational, "error reconnecting to channel %s, %s", v.ChannelID, err) + + // if the reconnect above didn't work lets just send a disconnect + // packet to reset things. + // Send a OP4 with a nil channel to disconnect + data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} + v.session.wsMutex.Lock() + err = v.session.wsConn.WriteJSON(data) + v.session.wsMutex.Unlock() + if err != nil { + v.log(LogError, "error sending disconnect packet, %s", err) + } + + } +} diff --git a/vendor/github.com/bwmarrin/discordgo/webhook.go b/vendor/github.com/bwmarrin/discordgo/webhook.go new file mode 100644 index 000000000..7e30b5b27 --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/webhook.go @@ -0,0 +1,55 @@ +package discordgo + +// Webhook stores the data for a webhook. +type Webhook struct { + ID string `json:"id"` + Type WebhookType `json:"type"` + GuildID string `json:"guild_id"` + ChannelID string `json:"channel_id"` + User *User `json:"user"` + Name string `json:"name"` + Avatar string `json:"avatar"` + Token string `json:"token"` + + // ApplicationID is the bot/OAuth2 application that created this webhook + ApplicationID string `json:"application_id,omitempty"` +} + +// WebhookType is the type of Webhook (see WebhookType* consts) in the Webhook struct +// https://discord.com/developers/docs/resources/webhook#webhook-object-webhook-types +type WebhookType int + +// Valid WebhookType values +const ( + WebhookTypeIncoming WebhookType = 1 + WebhookTypeChannelFollower WebhookType = 2 +) + +// WebhookParams is a struct for webhook params, used in the WebhookExecute command. +type WebhookParams struct { + Content string `json:"content,omitempty"` + Username string `json:"username,omitempty"` + AvatarURL string `json:"avatar_url,omitempty"` + TTS bool `json:"tts,omitempty"` + Files []*File `json:"-"` + Components []MessageComponent `json:"components"` + Embeds []*MessageEmbed `json:"embeds,omitempty"` + Attachments []*MessageAttachment `json:"attachments,omitempty"` + AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"` + // Only MessageFlagsSuppressEmbeds and MessageFlagsEphemeral can be set. + // MessageFlagsEphemeral can only be set when using Followup Message Create endpoint. + Flags MessageFlags `json:"flags,omitempty"` + // Name of the thread to create. + // NOTE: can only be set if the webhook channel is a forum. + ThreadName string `json:"thread_name,omitempty"` +} + +// WebhookEdit stores data for editing of a webhook message. +type WebhookEdit struct { + Content *string `json:"content,omitempty"` + Components *[]MessageComponent `json:"components,omitempty"` + Embeds *[]*MessageEmbed `json:"embeds,omitempty"` + Files []*File `json:"-"` + Attachments *[]*MessageAttachment `json:"attachments,omitempty"` + AllowedMentions *MessageAllowedMentions `json:"allowed_mentions,omitempty"` +} diff --git a/vendor/github.com/bwmarrin/discordgo/wsapi.go b/vendor/github.com/bwmarrin/discordgo/wsapi.go new file mode 100644 index 000000000..d101c542a --- /dev/null +++ b/vendor/github.com/bwmarrin/discordgo/wsapi.go @@ -0,0 +1,989 @@ +// Discordgo - Discord bindings for Go +// Available at https://github.com/bwmarrin/discordgo + +// Copyright 2015-2016 Bruce Marriner . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains low level functions for interacting with the Discord +// data websocket interface. + +package discordgo + +import ( + "bytes" + "compress/zlib" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sync/atomic" + "time" + + "github.com/gorilla/websocket" +) + +// ErrWSAlreadyOpen is thrown when you attempt to open +// a websocket that already is open. +var ErrWSAlreadyOpen = errors.New("web socket already opened") + +// ErrWSNotFound is thrown when you attempt to use a websocket +// that doesn't exist +var ErrWSNotFound = errors.New("no websocket connection exists") + +// ErrWSShardBounds is thrown when you try to use a shard ID that is +// more than the total shard count +var ErrWSShardBounds = errors.New("ShardID must be less than ShardCount") + +type resumePacket struct { + Op int `json:"op"` + Data struct { + Token string `json:"token"` + SessionID string `json:"session_id"` + Sequence int64 `json:"seq"` + } `json:"d"` +} + +// Open creates a websocket connection to Discord. +// See: https://discord.com/developers/docs/topics/gateway#connecting +func (s *Session) Open() error { + s.log(LogInformational, "called") + + var err error + + // Prevent Open or other major Session functions from + // being called while Open is still running. + s.Lock() + defer s.Unlock() + + // If the websock is already open, bail out here. + if s.wsConn != nil { + return ErrWSAlreadyOpen + } + + // Get the gateway to use for the Websocket connection + if s.gateway == "" { + s.gateway, err = s.Gateway() + if err != nil { + return err + } + + // Add the version and encoding to the URL + s.gateway = s.gateway + "?v=" + APIVersion + "&encoding=json" + } + + // Connect to the Gateway + s.log(LogInformational, "connecting to gateway %s", s.gateway) + header := http.Header{} + header.Add("accept-encoding", "zlib") + s.wsConn, _, err = s.Dialer.Dial(s.gateway, header) + if err != nil { + s.log(LogError, "error connecting to gateway %s, %s", s.gateway, err) + s.gateway = "" // clear cached gateway + s.wsConn = nil // Just to be safe. + return err + } + + s.wsConn.SetCloseHandler(func(code int, text string) error { + return nil + }) + + defer func() { + // because of this, all code below must set err to the error + // when exiting with an error :) Maybe someone has a better + // way :) + if err != nil { + s.wsConn.Close() + s.wsConn = nil + } + }() + + // The first response from Discord should be an Op 10 (Hello) Packet. + // When processed by onEvent the heartbeat goroutine will be started. + mt, m, err := s.wsConn.ReadMessage() + if err != nil { + return err + } + e, err := s.onEvent(mt, m) + if err != nil { + return err + } + if e.Operation != 10 { + err = fmt.Errorf("expecting Op 10, got Op %d instead", e.Operation) + return err + } + s.log(LogInformational, "Op 10 Hello Packet received from Discord") + s.LastHeartbeatAck = time.Now().UTC() + var h helloOp + if err = json.Unmarshal(e.RawData, &h); err != nil { + err = fmt.Errorf("error unmarshalling helloOp, %s", err) + return err + } + + // Now we send either an Op 2 Identity if this is a brand new + // connection or Op 6 Resume if we are resuming an existing connection. + sequence := atomic.LoadInt64(s.sequence) + if s.sessionID == "" && sequence == 0 { + + // Send Op 2 Identity Packet + err = s.identify() + if err != nil { + err = fmt.Errorf("error sending identify packet to gateway, %s, %s", s.gateway, err) + return err + } + + } else { + + // Send Op 6 Resume Packet + p := resumePacket{} + p.Op = 6 + p.Data.Token = s.Token + p.Data.SessionID = s.sessionID + p.Data.Sequence = sequence + + s.log(LogInformational, "sending resume packet to gateway") + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(p) + s.wsMutex.Unlock() + if err != nil { + err = fmt.Errorf("error sending gateway resume packet, %s, %s", s.gateway, err) + return err + } + + } + + // A basic state is a hard requirement for Voice. + // We create it here so the below READY/RESUMED packet can populate + // the state :) + // XXX: Move to New() func? + if s.State == nil { + state := NewState() + state.TrackChannels = false + state.TrackEmojis = false + state.TrackMembers = false + state.TrackRoles = false + state.TrackVoice = false + s.State = state + } + + // Now Discord should send us a READY or RESUMED packet. + mt, m, err = s.wsConn.ReadMessage() + if err != nil { + return err + } + e, err = s.onEvent(mt, m) + if err != nil { + return err + } + if e.Type != `READY` && e.Type != `RESUMED` { + // This is not fatal, but it does not follow their API documentation. + s.log(LogWarning, "Expected READY/RESUMED, instead got:\n%#v\n", e) + } + s.log(LogInformational, "First Packet:\n%#v\n", e) + + s.log(LogInformational, "We are now connected to Discord, emitting connect event") + s.handleEvent(connectEventType, &Connect{}) + + // A VoiceConnections map is a hard requirement for Voice. + // XXX: can this be moved to when opening a voice connection? + if s.VoiceConnections == nil { + s.log(LogInformational, "creating new VoiceConnections map") + s.VoiceConnections = make(map[string]*VoiceConnection) + } + + // Create listening chan outside of listen, as it needs to happen inside the + // mutex lock and needs to exist before calling heartbeat and listen + // go rountines. + s.listening = make(chan interface{}) + + // Start sending heartbeats and reading messages from Discord. + go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval) + go s.listen(s.wsConn, s.listening) + + s.log(LogInformational, "exiting") + return nil +} + +// listen polls the websocket connection for events, it will stop when the +// listening channel is closed, or an error occurs. +func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) { + + s.log(LogInformational, "called") + + for { + + messageType, message, err := wsConn.ReadMessage() + + if err != nil { + + // Detect if we have been closed manually. If a Close() has already + // happened, the websocket we are listening on will be different to + // the current session. + s.RLock() + sameConnection := s.wsConn == wsConn + s.RUnlock() + + if sameConnection { + + s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err) + // There has been an error reading, close the websocket so that + // OnDisconnect event is emitted. + err := s.Close() + if err != nil { + s.log(LogWarning, "error closing session connection, %s", err) + } + + s.log(LogInformational, "calling reconnect() now") + s.reconnect() + } + + return + } + + select { + + case <-listening: + return + + default: + s.onEvent(messageType, message) + + } + } +} + +type heartbeatOp struct { + Op int `json:"op"` + Data int64 `json:"d"` +} + +type helloOp struct { + HeartbeatInterval time.Duration `json:"heartbeat_interval"` +} + +// FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart. +const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond + +// HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send. +func (s *Session) HeartbeatLatency() time.Duration { + + return s.LastHeartbeatAck.Sub(s.LastHeartbeatSent) + +} + +// heartbeat sends regular heartbeats to Discord so it knows the client +// is still connected. If you do not send these heartbeats Discord will +// disconnect the websocket connection after a few seconds. +func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, heartbeatIntervalMsec time.Duration) { + + s.log(LogInformational, "called") + + if listening == nil || wsConn == nil { + return + } + + var err error + ticker := time.NewTicker(heartbeatIntervalMsec * time.Millisecond) + defer ticker.Stop() + + for { + s.RLock() + last := s.LastHeartbeatAck + s.RUnlock() + sequence := atomic.LoadInt64(s.sequence) + s.log(LogDebug, "sending gateway websocket heartbeat seq %d", sequence) + s.wsMutex.Lock() + s.LastHeartbeatSent = time.Now().UTC() + err = wsConn.WriteJSON(heartbeatOp{1, sequence}) + s.wsMutex.Unlock() + if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) { + if err != nil { + s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err) + } else { + s.log(LogError, "haven't gotten a heartbeat ACK in %v, triggering a reconnection", time.Now().UTC().Sub(last)) + } + s.Close() + s.reconnect() + return + } + s.Lock() + s.DataReady = true + s.Unlock() + + select { + case <-ticker.C: + // continue loop and send heartbeat + case <-listening: + return + } + } +} + +// UpdateStatusData is provided to UpdateStatusComplex() +type UpdateStatusData struct { + IdleSince *int `json:"since"` + Activities []*Activity `json:"activities"` + AFK bool `json:"afk"` + Status string `json:"status"` +} + +type updateStatusOp struct { + Op int `json:"op"` + Data UpdateStatusData `json:"d"` +} + +func newUpdateStatusData(idle int, activityType ActivityType, name, url string) *UpdateStatusData { + usd := &UpdateStatusData{ + Status: "online", + } + + if idle > 0 { + usd.IdleSince = &idle + } + + if name != "" { + usd.Activities = []*Activity{{ + Name: name, + Type: activityType, + URL: url, + }} + } + + return usd +} + +// UpdateGameStatus is used to update the user's status. +// If idle>0 then set status to idle. +// If name!="" then set game. +// if otherwise, set status to active, and no activity. +func (s *Session) UpdateGameStatus(idle int, name string) (err error) { + return s.UpdateStatusComplex(*newUpdateStatusData(idle, ActivityTypeGame, name, "")) +} + +// UpdateWatchStatus is used to update the user's watch status. +// If idle>0 then set status to idle. +// If name!="" then set movie/stream. +// if otherwise, set status to active, and no activity. +func (s *Session) UpdateWatchStatus(idle int, name string) (err error) { + return s.UpdateStatusComplex(*newUpdateStatusData(idle, ActivityTypeWatching, name, "")) +} + +// UpdateStreamingStatus is used to update the user's streaming status. +// If idle>0 then set status to idle. +// If name!="" then set game. +// If name!="" and url!="" then set the status type to streaming with the URL set. +// if otherwise, set status to active, and no game. +func (s *Session) UpdateStreamingStatus(idle int, name string, url string) (err error) { + gameType := ActivityTypeGame + if url != "" { + gameType = ActivityTypeStreaming + } + return s.UpdateStatusComplex(*newUpdateStatusData(idle, gameType, name, url)) +} + +// UpdateListeningStatus is used to set the user to "Listening to..." +// If name!="" then set to what user is listening to +// Else, set user to active and no activity. +func (s *Session) UpdateListeningStatus(name string) (err error) { + return s.UpdateStatusComplex(*newUpdateStatusData(0, ActivityTypeListening, name, "")) +} + +// UpdateCustomStatus is used to update the user's custom status. +// If state!="" then set the custom status. +// Else, set user to active and remove the custom status. +func (s *Session) UpdateCustomStatus(state string) (err error) { + data := UpdateStatusData{ + Status: "online", + } + + if state != "" { + // Discord requires a non-empty activity name, therefore we provide "Custom Status" as a placeholder. + data.Activities = []*Activity{{ + Name: "Custom Status", + Type: ActivityTypeCustom, + State: state, + }} + } + + return s.UpdateStatusComplex(data) +} + +// UpdateStatusComplex allows for sending the raw status update data untouched by discordgo. +func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) { + // The comment does say "untouched by discordgo", but we might need to lie a bit here. + // The Discord documentation lists `activities` as being nullable, but in practice this + // doesn't seem to be the case. I had filed an issue about this at + // https://github.com/discord/discord-api-docs/issues/2559, but as of writing this + // haven't had any movement on it, so at this point I'm assuming this is an error, + // and am fixing this bug accordingly. Because sending `null` for `activities` instantly + // disconnects us, I think that disallowing it from being sent in `UpdateStatusComplex` + // isn't that big of an issue. + if usd.Activities == nil { + usd.Activities = make([]*Activity, 0) + } + + s.RLock() + defer s.RUnlock() + if s.wsConn == nil { + return ErrWSNotFound + } + + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(updateStatusOp{3, usd}) + s.wsMutex.Unlock() + + return +} + +type requestGuildMembersData struct { + // TODO: Deprecated. Use string instead of []string + GuildIDs []string `json:"guild_id"` + Query *string `json:"query,omitempty"` + UserIDs *[]string `json:"user_ids,omitempty"` + Limit int `json:"limit"` + Nonce string `json:"nonce,omitempty"` + Presences bool `json:"presences"` +} + +type requestGuildMembersOp struct { + Op int `json:"op"` + Data requestGuildMembersData `json:"d"` +} + +// RequestGuildMembers requests guild members from the gateway +// The gateway responds with GuildMembersChunk events +// guildID : Single Guild ID to request members of +// query : String that username starts with, leave empty to return all members +// limit : Max number of items to return, or 0 to request all members matched +// nonce : Nonce to identify the Guild Members Chunk response +// presences : Whether to request presences of guild members +func (s *Session) RequestGuildMembers(guildID, query string, limit int, nonce string, presences bool) error { + return s.RequestGuildMembersBatch([]string{guildID}, query, limit, nonce, presences) +} + +// RequestGuildMembersList requests guild members from the gateway +// The gateway responds with GuildMembersChunk events +// guildID : Single Guild ID to request members of +// userIDs : IDs of users to fetch +// limit : Max number of items to return, or 0 to request all members matched +// nonce : Nonce to identify the Guild Members Chunk response +// presences : Whether to request presences of guild members +func (s *Session) RequestGuildMembersList(guildID string, userIDs []string, limit int, nonce string, presences bool) error { + return s.RequestGuildMembersBatchList([]string{guildID}, userIDs, limit, nonce, presences) +} + +// RequestGuildMembersBatch requests guild members from the gateway +// The gateway responds with GuildMembersChunk events +// guildID : Slice of guild IDs to request members of +// query : String that username starts with, leave empty to return all members +// limit : Max number of items to return, or 0 to request all members matched +// nonce : Nonce to identify the Guild Members Chunk response +// presences : Whether to request presences of guild members +// +// NOTE: this function is deprecated, please use RequestGuildMembers instead +func (s *Session) RequestGuildMembersBatch(guildIDs []string, query string, limit int, nonce string, presences bool) (err error) { + data := requestGuildMembersData{ + GuildIDs: guildIDs, + Query: &query, + Limit: limit, + Nonce: nonce, + Presences: presences, + } + err = s.requestGuildMembers(data) + return +} + +// RequestGuildMembersBatchList requests guild members from the gateway +// The gateway responds with GuildMembersChunk events +// guildID : Slice of guild IDs to request members of +// userIDs : IDs of users to fetch +// limit : Max number of items to return, or 0 to request all members matched +// nonce : Nonce to identify the Guild Members Chunk response +// presences : Whether to request presences of guild members +// +// NOTE: this function is deprecated, please use RequestGuildMembersList instead +func (s *Session) RequestGuildMembersBatchList(guildIDs []string, userIDs []string, limit int, nonce string, presences bool) (err error) { + data := requestGuildMembersData{ + GuildIDs: guildIDs, + UserIDs: &userIDs, + Limit: limit, + Nonce: nonce, + Presences: presences, + } + err = s.requestGuildMembers(data) + return +} + +// GatewayWriteStruct allows for sending raw gateway structs over the gateway. +func (s *Session) GatewayWriteStruct(data interface{}) (err error) { + s.RLock() + defer s.RUnlock() + if s.wsConn == nil { + return ErrWSNotFound + } + + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(data) + s.wsMutex.Unlock() + + return err +} + +func (s *Session) requestGuildMembers(data requestGuildMembersData) (err error) { + s.log(LogInformational, "called") + + s.RLock() + defer s.RUnlock() + if s.wsConn == nil { + return ErrWSNotFound + } + + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data}) + s.wsMutex.Unlock() + + return +} + +// onEvent is the "event handler" for all messages received on the +// Discord Gateway API websocket connection. +// +// If you use the AddHandler() function to register a handler for a +// specific event this function will pass the event along to that handler. +// +// If you use the AddHandler() function to register a handler for the +// "OnEvent" event then all events will be passed to that handler. +func (s *Session) onEvent(messageType int, message []byte) (*Event, error) { + + var err error + var reader io.Reader + reader = bytes.NewBuffer(message) + + // If this is a compressed message, uncompress it. + if messageType == websocket.BinaryMessage { + + z, err2 := zlib.NewReader(reader) + if err2 != nil { + s.log(LogError, "error uncompressing websocket message, %s", err) + return nil, err2 + } + + defer func() { + err3 := z.Close() + if err3 != nil { + s.log(LogWarning, "error closing zlib, %s", err) + } + }() + + reader = z + } + + // Decode the event into an Event struct. + var e *Event + decoder := json.NewDecoder(reader) + if err = decoder.Decode(&e); err != nil { + s.log(LogError, "error decoding websocket message, %s", err) + return e, err + } + + s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData)) + + // Ping request. + // Must respond with a heartbeat packet within 5 seconds + if e.Operation == 1 { + s.log(LogInformational, "sending heartbeat in response to Op1") + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)}) + s.wsMutex.Unlock() + if err != nil { + s.log(LogError, "error sending heartbeat in response to Op1") + return e, err + } + + return e, nil + } + + // Reconnect + // Must immediately disconnect from gateway and reconnect to new gateway. + if e.Operation == 7 { + s.log(LogInformational, "Closing and reconnecting in response to Op7") + s.CloseWithCode(websocket.CloseServiceRestart) + s.reconnect() + return e, nil + } + + // Invalid Session + // Must respond with a Identify packet. + if e.Operation == 9 { + + s.log(LogInformational, "sending identify packet to gateway in response to Op9") + + err = s.identify() + if err != nil { + s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err) + return e, err + } + + return e, nil + } + + if e.Operation == 10 { + // Op10 is handled by Open() + return e, nil + } + + if e.Operation == 11 { + s.Lock() + s.LastHeartbeatAck = time.Now().UTC() + s.Unlock() + s.log(LogDebug, "got heartbeat ACK") + return e, nil + } + + // Do not try to Dispatch a non-Dispatch Message + if e.Operation != 0 { + // But we probably should be doing something with them. + // TEMP + s.log(LogWarning, "unknown Op: %d, Seq: %d, Type: %s, Data: %s, message: %s", e.Operation, e.Sequence, e.Type, string(e.RawData), string(message)) + return e, nil + } + + // Store the message sequence + atomic.StoreInt64(s.sequence, e.Sequence) + + // Map event to registered event handlers and pass it along to any registered handlers. + if eh, ok := registeredInterfaceProviders[e.Type]; ok { + e.Struct = eh.New() + + // Attempt to unmarshal our event. + if err = json.Unmarshal(e.RawData, e.Struct); err != nil { + s.log(LogError, "error unmarshalling %s event, %s", e.Type, err) + } + + // Send event to any registered event handlers for it's type. + // Because the above doesn't cancel this, in case of an error + // the struct could be partially populated or at default values. + // However, most errors are due to a single field and I feel + // it's better to pass along what we received than nothing at all. + // TODO: Think about that decision :) + // Either way, READY events must fire, even with errors. + s.handleEvent(e.Type, e.Struct) + } else { + s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData)) + } + + // For legacy reasons, we send the raw event also, this could be useful for handling unknown events. + s.handleEvent(eventEventType, e) + + return e, nil +} + +// ------------------------------------------------------------------------------------------------ +// Code related to voice connections that initiate over the data websocket +// ------------------------------------------------------------------------------------------------ + +type voiceChannelJoinData struct { + GuildID *string `json:"guild_id"` + ChannelID *string `json:"channel_id"` + SelfMute bool `json:"self_mute"` + SelfDeaf bool `json:"self_deaf"` +} + +type voiceChannelJoinOp struct { + Op int `json:"op"` + Data voiceChannelJoinData `json:"d"` +} + +// ChannelVoiceJoin joins the session user to a voice channel. +// +// gID : Guild ID of the channel to join. +// cID : Channel ID of the channel to join. +// mute : If true, you will be set to muted upon joining. +// deaf : If true, you will be set to deafened upon joining. +func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) { + + s.log(LogInformational, "called") + + s.RLock() + voice, _ = s.VoiceConnections[gID] + s.RUnlock() + + if voice == nil { + voice = &VoiceConnection{} + s.Lock() + s.VoiceConnections[gID] = voice + s.Unlock() + } + + voice.Lock() + voice.GuildID = gID + voice.ChannelID = cID + voice.deaf = deaf + voice.mute = mute + voice.session = s + voice.Unlock() + + err = s.ChannelVoiceJoinManual(gID, cID, mute, deaf) + if err != nil { + return + } + + // doesn't exactly work perfect yet.. TODO + err = voice.waitUntilConnected() + if err != nil { + s.log(LogWarning, "error waiting for voice to connect, %s", err) + voice.Close() + return + } + + return +} + +// ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it. +// +// This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere. +// +// gID : Guild ID of the channel to join. +// cID : Channel ID of the channel to join, leave empty to disconnect. +// mute : If true, you will be set to muted upon joining. +// deaf : If true, you will be set to deafened upon joining. +func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) { + + s.log(LogInformational, "called") + + var channelID *string + if cID == "" { + channelID = nil + } else { + channelID = &cID + } + + // Send the request to Discord that we want to join the voice channel + data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, channelID, mute, deaf}} + s.wsMutex.Lock() + err = s.wsConn.WriteJSON(data) + s.wsMutex.Unlock() + return +} + +// onVoiceStateUpdate handles Voice State Update events on the data websocket. +func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) { + + // If we don't have a connection for the channel, don't bother + if st.ChannelID == "" { + return + } + + // Check if we have a voice connection to update + s.RLock() + voice, exists := s.VoiceConnections[st.GuildID] + s.RUnlock() + if !exists { + return + } + + // We only care about events that are about us. + if s.State.User.ID != st.UserID { + return + } + + // Store the SessionID for later use. + voice.Lock() + voice.UserID = st.UserID + voice.sessionID = st.SessionID + voice.ChannelID = st.ChannelID + voice.Unlock() +} + +// onVoiceServerUpdate handles the Voice Server Update data websocket event. +// +// This is also fired if the Guild's voice region changes while connected +// to a voice channel. In that case, need to re-establish connection to +// the new region endpoint. +func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) { + + s.log(LogInformational, "called") + + s.RLock() + voice, exists := s.VoiceConnections[st.GuildID] + s.RUnlock() + + // If no VoiceConnection exists, just skip this + if !exists { + return + } + + // If currently connected to voice ws/udp, then disconnect. + // Has no effect if not connected. + voice.Close() + + // Store values for later use + voice.Lock() + voice.token = st.Token + voice.endpoint = st.Endpoint + voice.GuildID = st.GuildID + voice.Unlock() + + // Open a connection to the voice server + err := voice.open() + if err != nil { + s.log(LogError, "onVoiceServerUpdate voice.open, %s", err) + } +} + +type identifyOp struct { + Op int `json:"op"` + Data Identify `json:"d"` +} + +// identify sends the identify packet to the gateway +func (s *Session) identify() error { + s.log(LogDebug, "called") + + // TODO: This is a temporary block of code to help + // maintain backwards compatibility + if s.Compress == false { + s.Identify.Compress = false + } + + // TODO: This is a temporary block of code to help + // maintain backwards compatibility + if s.Token != "" && s.Identify.Token == "" { + s.Identify.Token = s.Token + } + + // TODO: Below block should be refactored so ShardID and ShardCount + // can be deprecated and their usage moved to the Session.Identify + // struct + if s.ShardCount > 1 { + + if s.ShardID >= s.ShardCount { + return ErrWSShardBounds + } + + s.Identify.Shard = &[2]int{s.ShardID, s.ShardCount} + } + + // Send Identify packet to Discord + op := identifyOp{2, s.Identify} + s.log(LogDebug, "Identify Packet: \n%#v", op) + s.wsMutex.Lock() + err := s.wsConn.WriteJSON(op) + s.wsMutex.Unlock() + + return err +} + +func (s *Session) reconnect() { + + s.log(LogInformational, "called") + + var err error + + if s.ShouldReconnectOnError { + + wait := time.Duration(1) + + for { + s.log(LogInformational, "trying to reconnect to gateway") + + err = s.Open() + if err == nil { + s.log(LogInformational, "successfully reconnected to gateway") + + // I'm not sure if this is actually needed. + // if the gw reconnect works properly, voice should stay alive + // However, there seems to be cases where something "weird" + // happens. So we're doing this for now just to improve + // stability in those edge cases. + if s.ShouldReconnectVoiceOnSessionError { + s.RLock() + defer s.RUnlock() + for _, v := range s.VoiceConnections { + + s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID) + go v.reconnect() + + // This is here just to prevent violently spamming the + // voice reconnects + time.Sleep(1 * time.Second) + } + } + return + } + + // Certain race conditions can call reconnect() twice. If this happens, we + // just break out of the reconnect loop + if err == ErrWSAlreadyOpen { + s.log(LogInformational, "Websocket already exists, no need to reconnect") + return + } + + s.log(LogError, "error reconnecting to gateway, %s", err) + + <-time.After(wait * time.Second) + wait *= 2 + if wait > 600 { + wait = 600 + } + } + } +} + +// Close closes a websocket and stops all listening/heartbeat goroutines. +// TODO: Add support for Voice WS/UDP +func (s *Session) Close() error { + return s.CloseWithCode(websocket.CloseNormalClosure) +} + +// CloseWithCode closes a websocket using the provided closeCode and stops all +// listening/heartbeat goroutines. +// TODO: Add support for Voice WS/UDP connections +func (s *Session) CloseWithCode(closeCode int) (err error) { + + s.log(LogInformational, "called") + s.Lock() + + s.DataReady = false + + if s.listening != nil { + s.log(LogInformational, "closing listening channel") + close(s.listening) + s.listening = nil + } + + // TODO: Close all active Voice Connections too + // this should force stop any reconnecting voice channels too + + if s.wsConn != nil { + + s.log(LogInformational, "sending close frame") + // To cleanly close a connection, a client should send a close + // frame and wait for the server to close the connection. + s.wsMutex.Lock() + err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(closeCode, "")) + s.wsMutex.Unlock() + if err != nil { + s.log(LogInformational, "error closing websocket, %s", err) + } + + // TODO: Wait for Discord to actually close the connection. + time.Sleep(1 * time.Second) + + s.log(LogInformational, "closing gateway websocket") + err = s.wsConn.Close() + if err != nil { + s.log(LogInformational, "error closing websocket, %s", err) + } + + s.wsConn = nil + } + + s.Unlock() + + s.log(LogInformational, "emit disconnect event") + s.handleEvent(disconnectEventType, &Disconnect{}) + + return +} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.gitignore b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.gitignore new file mode 100644 index 000000000..fb5a5e83e --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.gitignore @@ -0,0 +1,3 @@ +.idea/ +coverage.out +tmp/ diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml new file mode 100644 index 000000000..5769aa141 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/.travis.yml @@ -0,0 +1,6 @@ +language: go + +go: + - '1.10' + - '1.11' + - tip diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt new file mode 100644 index 000000000..b1fef93b9 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Syfaro + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md new file mode 100644 index 000000000..932506113 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/README.md @@ -0,0 +1,121 @@ +# Golang bindings for the Telegram Bot API + +[![GoDoc](https://godoc.org/github.com/go-telegram-bot-api/telegram-bot-api?status.svg)](http://godoc.org/github.com/go-telegram-bot-api/telegram-bot-api) +[![Travis](https://travis-ci.org/go-telegram-bot-api/telegram-bot-api.svg)](https://travis-ci.org/go-telegram-bot-api/telegram-bot-api) + +All methods are fairly self explanatory, and reading the godoc page should +explain everything. If something isn't clear, open an issue or submit +a pull request. + +The scope of this project is just to provide a wrapper around the API +without any additional features. There are other projects for creating +something with plugins and command handlers without having to design +all that yourself. + +Join [the development group](https://telegram.me/go_telegram_bot_api) if +you want to ask questions or discuss development. + +## Example + +First, ensure the library is installed and up to date by running +`go get -u github.com/go-telegram-bot-api/telegram-bot-api`. + +This is a very simple bot that just displays any gotten updates, +then replies it to that chat. + +```go +package main + +import ( + "log" + + "github.com/go-telegram-bot-api/telegram-bot-api" +) + +func main() { + bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") + if err != nil { + log.Panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + + updates, err := bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message == nil { // ignore any non-Message Updates + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyToMessageID = update.Message.MessageID + + bot.Send(msg) + } +} +``` + +There are more examples on the [wiki](https://github.com/go-telegram-bot-api/telegram-bot-api/wiki) +with detailed information on how to do many differen kinds of things. +It's a great place to get started on using keyboards, commands, or other +kinds of reply markup. + +If you need to use webhooks (if you wish to run on Google App Engine), +you may use a slightly different method. + +```go +package main + +import ( + "log" + "net/http" + + "github.com/go-telegram-bot-api/telegram-bot-api" +) + +func main() { + bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") + if err != nil { + log.Fatal(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")) + if err != nil { + log.Fatal(err) + } + info, err := bot.GetWebhookInfo() + if err != nil { + log.Fatal(err) + } + if info.LastErrorDate != 0 { + log.Printf("Telegram callback failed: %s", info.LastErrorMessage) + } + updates := bot.ListenForWebhook("/" + bot.Token) + go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) + + for update := range updates { + log.Printf("%+v\n", update) + } +} +``` + +If you need, you may generate a self signed certficate, as this requires +HTTPS / TLS. The above example tells Telegram that this is your +certificate and that it should be trusted, even though it is not +properly signed. + + openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes + +Now that [Let's Encrypt](https://letsencrypt.org) is available, +you may wish to generate your free TLS certificate there. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go new file mode 100644 index 000000000..d56aaf825 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/bot.go @@ -0,0 +1,967 @@ +// Package tgbotapi has functions and types used for interacting with +// the Telegram Bot API. +package tgbotapi + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + + "github.com/technoweenie/multipartstreamer" +) + +// BotAPI allows you to interact with the Telegram Bot API. +type BotAPI struct { + Token string `json:"token"` + Debug bool `json:"debug"` + Buffer int `json:"buffer"` + + Self User `json:"-"` + Client *http.Client `json:"-"` + shutdownChannel chan interface{} +} + +// NewBotAPI creates a new BotAPI instance. +// +// It requires a token, provided by @BotFather on Telegram. +func NewBotAPI(token string) (*BotAPI, error) { + return NewBotAPIWithClient(token, &http.Client{}) +} + +// NewBotAPIWithClient creates a new BotAPI instance +// and allows you to pass a http.Client. +// +// It requires a token, provided by @BotFather on Telegram. +func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) { + bot := &BotAPI{ + Token: token, + Client: client, + Buffer: 100, + shutdownChannel: make(chan interface{}), + } + + self, err := bot.GetMe() + if err != nil { + return nil, err + } + + bot.Self = self + + return bot, nil +} + +// MakeRequest makes a request to a specific endpoint with our token. +func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) { + method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint) + + resp, err := bot.Client.PostForm(method, params) + if err != nil { + return APIResponse{}, err + } + defer resp.Body.Close() + + var apiResp APIResponse + bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp) + if err != nil { + return apiResp, err + } + + if bot.Debug { + log.Printf("%s resp: %s", endpoint, bytes) + } + + if !apiResp.Ok { + parameters := ResponseParameters{} + if apiResp.Parameters != nil { + parameters = *apiResp.Parameters + } + return apiResp, Error{apiResp.Description, parameters} + } + + return apiResp, nil +} + +// decodeAPIResponse decode response and return slice of bytes if debug enabled. +// If debug disabled, just decode http.Response.Body stream to APIResponse struct +// for efficient memory usage +func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) { + if !bot.Debug { + dec := json.NewDecoder(responseBody) + err = dec.Decode(resp) + return + } + + // if debug, read reponse body + data, err := ioutil.ReadAll(responseBody) + if err != nil { + return + } + + err = json.Unmarshal(data, resp) + if err != nil { + return + } + + return data, nil +} + +// makeMessageRequest makes a request to a method that returns a Message. +func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { + resp, err := bot.MakeRequest(endpoint, params) + if err != nil { + return Message{}, err + } + + var message Message + json.Unmarshal(resp.Result, &message) + + bot.debugLog(endpoint, params, message) + + return message, nil +} + +// UploadFile makes a request to the API with a file. +// +// Requires the parameter to hold the file not be in the params. +// File should be a string to a file path, a FileBytes struct, +// a FileReader struct, or a url.URL. +// +// Note that if your FileReader has a size set to -1, it will read +// the file into memory to calculate a size. +func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) { + ms := multipartstreamer.New() + + switch f := file.(type) { + case string: + ms.WriteFields(params) + + fileHandle, err := os.Open(f) + if err != nil { + return APIResponse{}, err + } + defer fileHandle.Close() + + fi, err := os.Stat(f) + if err != nil { + return APIResponse{}, err + } + + ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle) + case FileBytes: + ms.WriteFields(params) + + buf := bytes.NewBuffer(f.Bytes) + ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf) + case FileReader: + ms.WriteFields(params) + + if f.Size != -1 { + ms.WriteReader(fieldname, f.Name, f.Size, f.Reader) + + break + } + + data, err := ioutil.ReadAll(f.Reader) + if err != nil { + return APIResponse{}, err + } + + buf := bytes.NewBuffer(data) + + ms.WriteReader(fieldname, f.Name, int64(len(data)), buf) + case url.URL: + params[fieldname] = f.String() + + ms.WriteFields(params) + default: + return APIResponse{}, errors.New(ErrBadFileType) + } + + method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint) + + req, err := http.NewRequest("POST", method, nil) + if err != nil { + return APIResponse{}, err + } + + ms.SetupRequest(req) + + res, err := bot.Client.Do(req) + if err != nil { + return APIResponse{}, err + } + defer res.Body.Close() + + bytes, err := ioutil.ReadAll(res.Body) + if err != nil { + return APIResponse{}, err + } + + if bot.Debug { + log.Println(string(bytes)) + } + + var apiResp APIResponse + + err = json.Unmarshal(bytes, &apiResp) + if err != nil { + return APIResponse{}, err + } + + if !apiResp.Ok { + return APIResponse{}, errors.New(apiResp.Description) + } + + return apiResp, nil +} + +// GetFileDirectURL returns direct URL to file +// +// It requires the FileID. +func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { + file, err := bot.GetFile(FileConfig{fileID}) + + if err != nil { + return "", err + } + + return file.Link(bot.Token), nil +} + +// GetMe fetches the currently authenticated bot. +// +// This method is called upon creation to validate the token, +// and so you may get this data from BotAPI.Self without the need for +// another request. +func (bot *BotAPI) GetMe() (User, error) { + resp, err := bot.MakeRequest("getMe", nil) + if err != nil { + return User{}, err + } + + var user User + json.Unmarshal(resp.Result, &user) + + bot.debugLog("getMe", nil, user) + + return user, nil +} + +// IsMessageToMe returns true if message directed to this bot. +// +// It requires the Message. +func (bot *BotAPI) IsMessageToMe(message Message) bool { + return strings.Contains(message.Text, "@"+bot.Self.UserName) +} + +// Send will send a Chattable item to Telegram. +// +// It requires the Chattable to send. +func (bot *BotAPI) Send(c Chattable) (Message, error) { + switch c.(type) { + case Fileable: + return bot.sendFile(c.(Fileable)) + default: + return bot.sendChattable(c) + } +} + +// debugLog checks if the bot is currently running in debug mode, and if +// so will display information about the request and response in the +// debug log. +func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) { + if bot.Debug { + log.Printf("%s req : %+v\n", context, v) + log.Printf("%s resp: %+v\n", context, message) + } +} + +// sendExisting will send a Message with an existing file to Telegram. +func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) { + v, err := config.values() + + if err != nil { + return Message{}, err + } + + message, err := bot.makeMessageRequest(method, v) + if err != nil { + return Message{}, err + } + + return message, nil +} + +// uploadAndSend will send a Message with a new file to Telegram. +func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) { + params, err := config.params() + if err != nil { + return Message{}, err + } + + file := config.getFile() + + resp, err := bot.UploadFile(method, params, config.name(), file) + if err != nil { + return Message{}, err + } + + var message Message + json.Unmarshal(resp.Result, &message) + + bot.debugLog(method, nil, message) + + return message, nil +} + +// sendFile determines if the file is using an existing file or uploading +// a new file, then sends it as needed. +func (bot *BotAPI) sendFile(config Fileable) (Message, error) { + if config.useExistingFile() { + return bot.sendExisting(config.method(), config) + } + + return bot.uploadAndSend(config.method(), config) +} + +// sendChattable sends a Chattable. +func (bot *BotAPI) sendChattable(config Chattable) (Message, error) { + v, err := config.values() + if err != nil { + return Message{}, err + } + + message, err := bot.makeMessageRequest(config.method(), v) + + if err != nil { + return Message{}, err + } + + return message, nil +} + +// GetUserProfilePhotos gets a user's profile photos. +// +// It requires UserID. +// Offset and Limit are optional. +func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) { + v := url.Values{} + v.Add("user_id", strconv.Itoa(config.UserID)) + if config.Offset != 0 { + v.Add("offset", strconv.Itoa(config.Offset)) + } + if config.Limit != 0 { + v.Add("limit", strconv.Itoa(config.Limit)) + } + + resp, err := bot.MakeRequest("getUserProfilePhotos", v) + if err != nil { + return UserProfilePhotos{}, err + } + + var profilePhotos UserProfilePhotos + json.Unmarshal(resp.Result, &profilePhotos) + + bot.debugLog("GetUserProfilePhoto", v, profilePhotos) + + return profilePhotos, nil +} + +// GetFile returns a File which can download a file from Telegram. +// +// Requires FileID. +func (bot *BotAPI) GetFile(config FileConfig) (File, error) { + v := url.Values{} + v.Add("file_id", config.FileID) + + resp, err := bot.MakeRequest("getFile", v) + if err != nil { + return File{}, err + } + + var file File + json.Unmarshal(resp.Result, &file) + + bot.debugLog("GetFile", v, file) + + return file, nil +} + +// GetUpdates fetches updates. +// If a WebHook is set, this will not return any data! +// +// Offset, Limit, and Timeout are optional. +// To avoid stale items, set Offset to one higher than the previous item. +// Set Timeout to a large number to reduce requests so you can get updates +// instantly instead of having to wait between requests. +func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { + v := url.Values{} + if config.Offset != 0 { + v.Add("offset", strconv.Itoa(config.Offset)) + } + if config.Limit > 0 { + v.Add("limit", strconv.Itoa(config.Limit)) + } + if config.Timeout > 0 { + v.Add("timeout", strconv.Itoa(config.Timeout)) + } + + resp, err := bot.MakeRequest("getUpdates", v) + if err != nil { + return []Update{}, err + } + + var updates []Update + json.Unmarshal(resp.Result, &updates) + + bot.debugLog("getUpdates", v, updates) + + return updates, nil +} + +// RemoveWebhook unsets the webhook. +func (bot *BotAPI) RemoveWebhook() (APIResponse, error) { + return bot.MakeRequest("setWebhook", url.Values{}) +} + +// SetWebhook sets a webhook. +// +// If this is set, GetUpdates will not get any data! +// +// If you do not have a legitimate TLS certificate, you need to include +// your self signed certificate with the config. +func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) { + + if config.Certificate == nil { + v := url.Values{} + v.Add("url", config.URL.String()) + if config.MaxConnections != 0 { + v.Add("max_connections", strconv.Itoa(config.MaxConnections)) + } + + return bot.MakeRequest("setWebhook", v) + } + + params := make(map[string]string) + params["url"] = config.URL.String() + if config.MaxConnections != 0 { + params["max_connections"] = strconv.Itoa(config.MaxConnections) + } + + resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate) + if err != nil { + return APIResponse{}, err + } + + return resp, nil +} + +// GetWebhookInfo allows you to fetch information about a webhook and if +// one currently is set, along with pending update count and error messages. +func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { + resp, err := bot.MakeRequest("getWebhookInfo", url.Values{}) + if err != nil { + return WebhookInfo{}, err + } + + var info WebhookInfo + err = json.Unmarshal(resp.Result, &info) + + return info, err +} + +// GetUpdatesChan starts and returns a channel for getting updates. +func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) { + ch := make(chan Update, bot.Buffer) + + go func() { + for { + select { + case <-bot.shutdownChannel: + return + default: + } + + updates, err := bot.GetUpdates(config) + if err != nil { + log.Println(err) + log.Println("Failed to get updates, retrying in 3 seconds...") + time.Sleep(time.Second * 3) + + continue + } + + for _, update := range updates { + if update.UpdateID >= config.Offset { + config.Offset = update.UpdateID + 1 + ch <- update + } + } + } + }() + + return ch, nil +} + +// StopReceivingUpdates stops the go routine which receives updates +func (bot *BotAPI) StopReceivingUpdates() { + if bot.Debug { + log.Println("Stopping the update receiver routine...") + } + close(bot.shutdownChannel) +} + +// ListenForWebhook registers a http handler for a webhook. +func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { + ch := make(chan Update, bot.Buffer) + + http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + bytes, _ := ioutil.ReadAll(r.Body) + + var update Update + json.Unmarshal(bytes, &update) + + ch <- update + }) + + return ch +} + +// AnswerInlineQuery sends a response to an inline query. +// +// Note that you must respond to an inline query within 30 seconds. +func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) { + v := url.Values{} + + v.Add("inline_query_id", config.InlineQueryID) + v.Add("cache_time", strconv.Itoa(config.CacheTime)) + v.Add("is_personal", strconv.FormatBool(config.IsPersonal)) + v.Add("next_offset", config.NextOffset) + data, err := json.Marshal(config.Results) + if err != nil { + return APIResponse{}, err + } + v.Add("results", string(data)) + v.Add("switch_pm_text", config.SwitchPMText) + v.Add("switch_pm_parameter", config.SwitchPMParameter) + + bot.debugLog("answerInlineQuery", v, nil) + + return bot.MakeRequest("answerInlineQuery", v) +} + +// AnswerCallbackQuery sends a response to an inline query callback. +func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) { + v := url.Values{} + + v.Add("callback_query_id", config.CallbackQueryID) + if config.Text != "" { + v.Add("text", config.Text) + } + v.Add("show_alert", strconv.FormatBool(config.ShowAlert)) + if config.URL != "" { + v.Add("url", config.URL) + } + v.Add("cache_time", strconv.Itoa(config.CacheTime)) + + bot.debugLog("answerCallbackQuery", v, nil) + + return bot.MakeRequest("answerCallbackQuery", v) +} + +// KickChatMember kicks a user from a chat. Note that this only will work +// in supergroups, and requires the bot to be an admin. Also note they +// will be unable to rejoin until they are unbanned. +func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + v.Add("user_id", strconv.Itoa(config.UserID)) + + if config.UntilDate != 0 { + v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) + } + + bot.debugLog("kickChatMember", v, nil) + + return bot.MakeRequest("kickChatMember", v) +} + +// LeaveChat makes the bot leave the chat. +func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + + bot.debugLog("leaveChat", v, nil) + + return bot.MakeRequest("leaveChat", v) +} + +// GetChat gets information about a chat. +func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + + resp, err := bot.MakeRequest("getChat", v) + if err != nil { + return Chat{}, err + } + + var chat Chat + err = json.Unmarshal(resp.Result, &chat) + + bot.debugLog("getChat", v, chat) + + return chat, err +} + +// GetChatAdministrators gets a list of administrators in the chat. +// +// If none have been appointed, only the creator will be returned. +// Bots are not shown, even if they are an administrator. +func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + + resp, err := bot.MakeRequest("getChatAdministrators", v) + if err != nil { + return []ChatMember{}, err + } + + var members []ChatMember + err = json.Unmarshal(resp.Result, &members) + + bot.debugLog("getChatAdministrators", v, members) + + return members, err +} + +// GetChatMembersCount gets the number of users in a chat. +func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + + resp, err := bot.MakeRequest("getChatMembersCount", v) + if err != nil { + return -1, err + } + + var count int + err = json.Unmarshal(resp.Result, &count) + + bot.debugLog("getChatMembersCount", v, count) + + return count, err +} + +// GetChatMember gets a specific chat member. +func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + v.Add("user_id", strconv.Itoa(config.UserID)) + + resp, err := bot.MakeRequest("getChatMember", v) + if err != nil { + return ChatMember{}, err + } + + var member ChatMember + err = json.Unmarshal(resp.Result, &member) + + bot.debugLog("getChatMember", v, member) + + return member, err +} + +// UnbanChatMember unbans a user from a chat. Note that this only will work +// in supergroups and channels, and requires the bot to be an admin. +func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { + v := url.Values{} + + if config.SuperGroupUsername != "" { + v.Add("chat_id", config.SuperGroupUsername) + } else if config.ChannelUsername != "" { + v.Add("chat_id", config.ChannelUsername) + } else { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } + v.Add("user_id", strconv.Itoa(config.UserID)) + + bot.debugLog("unbanChatMember", v, nil) + + return bot.MakeRequest("unbanChatMember", v) +} + +// RestrictChatMember to restrict a user in a supergroup. The bot must be an +//administrator in the supergroup for this to work and must have the +//appropriate admin rights. Pass True for all boolean parameters to lift +//restrictions from a user. Returns True on success. +func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { + v := url.Values{} + + if config.SuperGroupUsername != "" { + v.Add("chat_id", config.SuperGroupUsername) + } else if config.ChannelUsername != "" { + v.Add("chat_id", config.ChannelUsername) + } else { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } + v.Add("user_id", strconv.Itoa(config.UserID)) + + if config.CanSendMessages != nil { + v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) + } + if config.CanSendMediaMessages != nil { + v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) + } + if config.CanSendOtherMessages != nil { + v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) + } + if config.CanAddWebPagePreviews != nil { + v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) + } + if config.UntilDate != 0 { + v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) + } + + bot.debugLog("restrictChatMember", v, nil) + + return bot.MakeRequest("restrictChatMember", v) +} + +// PromoteChatMember add admin rights to user +func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { + v := url.Values{} + + if config.SuperGroupUsername != "" { + v.Add("chat_id", config.SuperGroupUsername) + } else if config.ChannelUsername != "" { + v.Add("chat_id", config.ChannelUsername) + } else { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } + v.Add("user_id", strconv.Itoa(config.UserID)) + + if config.CanChangeInfo != nil { + v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) + } + if config.CanPostMessages != nil { + v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) + } + if config.CanEditMessages != nil { + v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) + } + if config.CanDeleteMessages != nil { + v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) + } + if config.CanInviteUsers != nil { + v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) + } + if config.CanRestrictMembers != nil { + v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) + } + if config.CanPinMessages != nil { + v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) + } + if config.CanPromoteMembers != nil { + v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) + } + + bot.debugLog("promoteChatMember", v, nil) + + return bot.MakeRequest("promoteChatMember", v) +} + +// GetGameHighScores allows you to get the high scores for a game. +func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { + v, _ := config.values() + + resp, err := bot.MakeRequest(config.method(), v) + if err != nil { + return []GameHighScore{}, err + } + + var highScores []GameHighScore + err = json.Unmarshal(resp.Result, &highScores) + + return highScores, err +} + +// AnswerShippingQuery allows you to reply to Update with shipping_query parameter. +func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { + v := url.Values{} + + v.Add("shipping_query_id", config.ShippingQueryID) + v.Add("ok", strconv.FormatBool(config.OK)) + if config.OK == true { + data, err := json.Marshal(config.ShippingOptions) + if err != nil { + return APIResponse{}, err + } + v.Add("shipping_options", string(data)) + } else { + v.Add("error_message", config.ErrorMessage) + } + + bot.debugLog("answerShippingQuery", v, nil) + + return bot.MakeRequest("answerShippingQuery", v) +} + +// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query. +func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { + v := url.Values{} + + v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) + v.Add("ok", strconv.FormatBool(config.OK)) + if config.OK != true { + v.Add("error", config.ErrorMessage) + } + + bot.debugLog("answerPreCheckoutQuery", v, nil) + + return bot.MakeRequest("answerPreCheckoutQuery", v) +} + +// DeleteMessage deletes a message in a chat +func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} + +// GetInviteLink get InviteLink for a chat +func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { + v := url.Values{} + + if config.SuperGroupUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.SuperGroupUsername) + } + + resp, err := bot.MakeRequest("exportChatInviteLink", v) + if err != nil { + return "", err + } + + var inviteLink string + err = json.Unmarshal(resp.Result, &inviteLink) + + return inviteLink, err +} + +// PinChatMessage pin message in supergroup +func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} + +// UnpinChatMessage unpin message in supergroup +func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} + +// SetChatTitle change title of chat. +func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} + +// SetChatDescription change description of chat. +func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} + +// SetChatPhoto change photo of chat. +func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { + params, err := config.params() + if err != nil { + return APIResponse{}, err + } + + file := config.getFile() + + return bot.UploadFile(config.method(), params, config.name(), file) +} + +// DeleteChatPhoto delete photo of chat. +func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { + v, err := config.values() + if err != nil { + return APIResponse{}, err + } + + bot.debugLog(config.method(), v, nil) + + return bot.MakeRequest(config.method(), v) +} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go new file mode 100644 index 000000000..181d4e434 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/configs.go @@ -0,0 +1,1264 @@ +package tgbotapi + +import ( + "encoding/json" + "io" + "net/url" + "strconv" +) + +// Telegram constants +const ( + // APIEndpoint is the endpoint for all API methods, + // with formatting for Sprintf. + APIEndpoint = "https://api.telegram.org/bot%s/%s" + // FileEndpoint is the endpoint for downloading a file from Telegram. + FileEndpoint = "https://api.telegram.org/file/bot%s/%s" +) + +// Constant values for ChatActions +const ( + ChatTyping = "typing" + ChatUploadPhoto = "upload_photo" + ChatRecordVideo = "record_video" + ChatUploadVideo = "upload_video" + ChatRecordAudio = "record_audio" + ChatUploadAudio = "upload_audio" + ChatUploadDocument = "upload_document" + ChatFindLocation = "find_location" +) + +// API errors +const ( + // ErrAPIForbidden happens when a token is bad + ErrAPIForbidden = "forbidden" +) + +// Constant values for ParseMode in MessageConfig +const ( + ModeMarkdown = "Markdown" + ModeHTML = "HTML" +) + +// Library errors +const ( + // ErrBadFileType happens when you pass an unknown type + ErrBadFileType = "bad file type" + ErrBadURL = "bad or empty url" +) + +// Chattable is any config type that can be sent. +type Chattable interface { + values() (url.Values, error) + method() string +} + +// Fileable is any config type that can be sent that includes a file. +type Fileable interface { + Chattable + params() (map[string]string, error) + name() string + getFile() interface{} + useExistingFile() bool +} + +// BaseChat is base type for all chat config types. +type BaseChat struct { + ChatID int64 // required + ChannelUsername string + ReplyToMessageID int + ReplyMarkup interface{} + DisableNotification bool +} + +// values returns url.Values representation of BaseChat +func (chat *BaseChat) values() (url.Values, error) { + v := url.Values{} + if chat.ChannelUsername != "" { + v.Add("chat_id", chat.ChannelUsername) + } else { + v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) + } + + if chat.ReplyToMessageID != 0 { + v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) + } + + if chat.ReplyMarkup != nil { + data, err := json.Marshal(chat.ReplyMarkup) + if err != nil { + return v, err + } + + v.Add("reply_markup", string(data)) + } + + v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) + + return v, nil +} + +// BaseFile is a base type for all file config types. +type BaseFile struct { + BaseChat + File interface{} + FileID string + UseExisting bool + MimeType string + FileSize int +} + +// params returns a map[string]string representation of BaseFile. +func (file BaseFile) params() (map[string]string, error) { + params := make(map[string]string) + + if file.ChannelUsername != "" { + params["chat_id"] = file.ChannelUsername + } else { + params["chat_id"] = strconv.FormatInt(file.ChatID, 10) + } + + if file.ReplyToMessageID != 0 { + params["reply_to_message_id"] = strconv.Itoa(file.ReplyToMessageID) + } + + if file.ReplyMarkup != nil { + data, err := json.Marshal(file.ReplyMarkup) + if err != nil { + return params, err + } + + params["reply_markup"] = string(data) + } + + if file.MimeType != "" { + params["mime_type"] = file.MimeType + } + + if file.FileSize > 0 { + params["file_size"] = strconv.Itoa(file.FileSize) + } + + params["disable_notification"] = strconv.FormatBool(file.DisableNotification) + + return params, nil +} + +// getFile returns the file. +func (file BaseFile) getFile() interface{} { + return file.File +} + +// useExistingFile returns if the BaseFile has already been uploaded. +func (file BaseFile) useExistingFile() bool { + return file.UseExisting +} + +// BaseEdit is base type of all chat edits. +type BaseEdit struct { + ChatID int64 + ChannelUsername string + MessageID int + InlineMessageID string + ReplyMarkup *InlineKeyboardMarkup +} + +func (edit BaseEdit) values() (url.Values, error) { + v := url.Values{} + + if edit.InlineMessageID == "" { + if edit.ChannelUsername != "" { + v.Add("chat_id", edit.ChannelUsername) + } else { + v.Add("chat_id", strconv.FormatInt(edit.ChatID, 10)) + } + v.Add("message_id", strconv.Itoa(edit.MessageID)) + } else { + v.Add("inline_message_id", edit.InlineMessageID) + } + + if edit.ReplyMarkup != nil { + data, err := json.Marshal(edit.ReplyMarkup) + if err != nil { + return v, err + } + v.Add("reply_markup", string(data)) + } + + return v, nil +} + +// MessageConfig contains information about a SendMessage request. +type MessageConfig struct { + BaseChat + Text string + ParseMode string + DisableWebPagePreview bool +} + +// values returns a url.Values representation of MessageConfig. +func (config MessageConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + v.Add("text", config.Text) + v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + + return v, nil +} + +// method returns Telegram API method name for sending Message. +func (config MessageConfig) method() string { + return "sendMessage" +} + +// ForwardConfig contains information about a ForwardMessage request. +type ForwardConfig struct { + BaseChat + FromChatID int64 // required + FromChannelUsername string + MessageID int // required +} + +// values returns a url.Values representation of ForwardConfig. +func (config ForwardConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) + v.Add("message_id", strconv.Itoa(config.MessageID)) + return v, nil +} + +// method returns Telegram API method name for sending Forward. +func (config ForwardConfig) method() string { + return "forwardMessage" +} + +// PhotoConfig contains information about a SendPhoto request. +type PhotoConfig struct { + BaseFile + Caption string + ParseMode string +} + +// Params returns a map[string]string representation of PhotoConfig. +func (config PhotoConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// Values returns a url.Values representation of PhotoConfig. +func (config PhotoConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// name returns the field name for the Photo. +func (config PhotoConfig) name() string { + return "photo" +} + +// method returns Telegram API method name for sending Photo. +func (config PhotoConfig) method() string { + return "sendPhoto" +} + +// AudioConfig contains information about a SendAudio request. +type AudioConfig struct { + BaseFile + Caption string + ParseMode string + Duration int + Performer string + Title string +} + +// values returns a url.Values representation of AudioConfig. +func (config AudioConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Duration != 0 { + v.Add("duration", strconv.Itoa(config.Duration)) + } + + if config.Performer != "" { + v.Add("performer", config.Performer) + } + if config.Title != "" { + v.Add("title", config.Title) + } + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// params returns a map[string]string representation of AudioConfig. +func (config AudioConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Duration != 0 { + params["duration"] = strconv.Itoa(config.Duration) + } + + if config.Performer != "" { + params["performer"] = config.Performer + } + if config.Title != "" { + params["title"] = config.Title + } + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// name returns the field name for the Audio. +func (config AudioConfig) name() string { + return "audio" +} + +// method returns Telegram API method name for sending Audio. +func (config AudioConfig) method() string { + return "sendAudio" +} + +// DocumentConfig contains information about a SendDocument request. +type DocumentConfig struct { + BaseFile + Caption string + ParseMode string +} + +// values returns a url.Values representation of DocumentConfig. +func (config DocumentConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// params returns a map[string]string representation of DocumentConfig. +func (config DocumentConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// name returns the field name for the Document. +func (config DocumentConfig) name() string { + return "document" +} + +// method returns Telegram API method name for sending Document. +func (config DocumentConfig) method() string { + return "sendDocument" +} + +// StickerConfig contains information about a SendSticker request. +type StickerConfig struct { + BaseFile +} + +// values returns a url.Values representation of StickerConfig. +func (config StickerConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + + return v, nil +} + +// params returns a map[string]string representation of StickerConfig. +func (config StickerConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + return params, nil +} + +// name returns the field name for the Sticker. +func (config StickerConfig) name() string { + return "sticker" +} + +// method returns Telegram API method name for sending Sticker. +func (config StickerConfig) method() string { + return "sendSticker" +} + +// VideoConfig contains information about a SendVideo request. +type VideoConfig struct { + BaseFile + Duration int + Caption string + ParseMode string +} + +// values returns a url.Values representation of VideoConfig. +func (config VideoConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Duration != 0 { + v.Add("duration", strconv.Itoa(config.Duration)) + } + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// params returns a map[string]string representation of VideoConfig. +func (config VideoConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// name returns the field name for the Video. +func (config VideoConfig) name() string { + return "video" +} + +// method returns Telegram API method name for sending Video. +func (config VideoConfig) method() string { + return "sendVideo" +} + +// AnimationConfig contains information about a SendAnimation request. +type AnimationConfig struct { + BaseFile + Duration int + Caption string + ParseMode string +} + +// values returns a url.Values representation of AnimationConfig. +func (config AnimationConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Duration != 0 { + v.Add("duration", strconv.Itoa(config.Duration)) + } + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// params returns a map[string]string representation of AnimationConfig. +func (config AnimationConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// name returns the field name for the Animation. +func (config AnimationConfig) name() string { + return "animation" +} + +// method returns Telegram API method name for sending Animation. +func (config AnimationConfig) method() string { + return "sendAnimation" +} + +// VideoNoteConfig contains information about a SendVideoNote request. +type VideoNoteConfig struct { + BaseFile + Duration int + Length int +} + +// values returns a url.Values representation of VideoNoteConfig. +func (config VideoNoteConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Duration != 0 { + v.Add("duration", strconv.Itoa(config.Duration)) + } + + // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response + if config.Length != 0 { + v.Add("length", strconv.Itoa(config.Length)) + } + + return v, nil +} + +// params returns a map[string]string representation of VideoNoteConfig. +func (config VideoNoteConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Length != 0 { + params["length"] = strconv.Itoa(config.Length) + } + if config.Duration != 0 { + params["duration"] = strconv.Itoa(config.Duration) + } + + return params, nil +} + +// name returns the field name for the VideoNote. +func (config VideoNoteConfig) name() string { + return "video_note" +} + +// method returns Telegram API method name for sending VideoNote. +func (config VideoNoteConfig) method() string { + return "sendVideoNote" +} + +// VoiceConfig contains information about a SendVoice request. +type VoiceConfig struct { + BaseFile + Caption string + ParseMode string + Duration int +} + +// values returns a url.Values representation of VoiceConfig. +func (config VoiceConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add(config.name(), config.FileID) + if config.Duration != 0 { + v.Add("duration", strconv.Itoa(config.Duration)) + } + if config.Caption != "" { + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + } + + return v, nil +} + +// params returns a map[string]string representation of VoiceConfig. +func (config VoiceConfig) params() (map[string]string, error) { + params, _ := config.BaseFile.params() + + if config.Duration != 0 { + params["duration"] = strconv.Itoa(config.Duration) + } + if config.Caption != "" { + params["caption"] = config.Caption + if config.ParseMode != "" { + params["parse_mode"] = config.ParseMode + } + } + + return params, nil +} + +// name returns the field name for the Voice. +func (config VoiceConfig) name() string { + return "voice" +} + +// method returns Telegram API method name for sending Voice. +func (config VoiceConfig) method() string { + return "sendVoice" +} + +// MediaGroupConfig contains information about a sendMediaGroup request. +type MediaGroupConfig struct { + BaseChat + InputMedia []interface{} +} + +func (config MediaGroupConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + data, err := json.Marshal(config.InputMedia) + if err != nil { + return v, err + } + + v.Add("media", string(data)) + + return v, nil +} + +func (config MediaGroupConfig) method() string { + return "sendMediaGroup" +} + +// LocationConfig contains information about a SendLocation request. +type LocationConfig struct { + BaseChat + Latitude float64 // required + Longitude float64 // required +} + +// values returns a url.Values representation of LocationConfig. +func (config LocationConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) + v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) + + return v, nil +} + +// method returns Telegram API method name for sending Location. +func (config LocationConfig) method() string { + return "sendLocation" +} + +// VenueConfig contains information about a SendVenue request. +type VenueConfig struct { + BaseChat + Latitude float64 // required + Longitude float64 // required + Title string // required + Address string // required + FoursquareID string +} + +func (config VenueConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) + v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) + v.Add("title", config.Title) + v.Add("address", config.Address) + if config.FoursquareID != "" { + v.Add("foursquare_id", config.FoursquareID) + } + + return v, nil +} + +func (config VenueConfig) method() string { + return "sendVenue" +} + +// ContactConfig allows you to send a contact. +type ContactConfig struct { + BaseChat + PhoneNumber string + FirstName string + LastName string +} + +func (config ContactConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add("phone_number", config.PhoneNumber) + v.Add("first_name", config.FirstName) + v.Add("last_name", config.LastName) + + return v, nil +} + +func (config ContactConfig) method() string { + return "sendContact" +} + +// GameConfig allows you to send a game. +type GameConfig struct { + BaseChat + GameShortName string +} + +func (config GameConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + + v.Add("game_short_name", config.GameShortName) + + return v, nil +} + +func (config GameConfig) method() string { + return "sendGame" +} + +// SetGameScoreConfig allows you to update the game score in a chat. +type SetGameScoreConfig struct { + UserID int + Score int + Force bool + DisableEditMessage bool + ChatID int64 + ChannelUsername string + MessageID int + InlineMessageID string +} + +func (config SetGameScoreConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("user_id", strconv.Itoa(config.UserID)) + v.Add("score", strconv.Itoa(config.Score)) + if config.InlineMessageID == "" { + if config.ChannelUsername == "" { + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + } else { + v.Add("chat_id", config.ChannelUsername) + } + v.Add("message_id", strconv.Itoa(config.MessageID)) + } else { + v.Add("inline_message_id", config.InlineMessageID) + } + v.Add("disable_edit_message", strconv.FormatBool(config.DisableEditMessage)) + + return v, nil +} + +func (config SetGameScoreConfig) method() string { + return "setGameScore" +} + +// GetGameHighScoresConfig allows you to fetch the high scores for a game. +type GetGameHighScoresConfig struct { + UserID int + ChatID int + ChannelUsername string + MessageID int + InlineMessageID string +} + +func (config GetGameHighScoresConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("user_id", strconv.Itoa(config.UserID)) + if config.InlineMessageID == "" { + if config.ChannelUsername == "" { + v.Add("chat_id", strconv.Itoa(config.ChatID)) + } else { + v.Add("chat_id", config.ChannelUsername) + } + v.Add("message_id", strconv.Itoa(config.MessageID)) + } else { + v.Add("inline_message_id", config.InlineMessageID) + } + + return v, nil +} + +func (config GetGameHighScoresConfig) method() string { + return "getGameHighScores" +} + +// ChatActionConfig contains information about a SendChatAction request. +type ChatActionConfig struct { + BaseChat + Action string // required +} + +// values returns a url.Values representation of ChatActionConfig. +func (config ChatActionConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + v.Add("action", config.Action) + return v, nil +} + +// method returns Telegram API method name for sending ChatAction. +func (config ChatActionConfig) method() string { + return "sendChatAction" +} + +// EditMessageTextConfig allows you to modify the text in a message. +type EditMessageTextConfig struct { + BaseEdit + Text string + ParseMode string + DisableWebPagePreview bool +} + +func (config EditMessageTextConfig) values() (url.Values, error) { + v, err := config.BaseEdit.values() + if err != nil { + return v, err + } + + v.Add("text", config.Text) + v.Add("parse_mode", config.ParseMode) + v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) + + return v, nil +} + +func (config EditMessageTextConfig) method() string { + return "editMessageText" +} + +// EditMessageCaptionConfig allows you to modify the caption of a message. +type EditMessageCaptionConfig struct { + BaseEdit + Caption string + ParseMode string +} + +func (config EditMessageCaptionConfig) values() (url.Values, error) { + v, _ := config.BaseEdit.values() + + v.Add("caption", config.Caption) + if config.ParseMode != "" { + v.Add("parse_mode", config.ParseMode) + } + + return v, nil +} + +func (config EditMessageCaptionConfig) method() string { + return "editMessageCaption" +} + +// EditMessageReplyMarkupConfig allows you to modify the reply markup +// of a message. +type EditMessageReplyMarkupConfig struct { + BaseEdit +} + +func (config EditMessageReplyMarkupConfig) values() (url.Values, error) { + return config.BaseEdit.values() +} + +func (config EditMessageReplyMarkupConfig) method() string { + return "editMessageReplyMarkup" +} + +// UserProfilePhotosConfig contains information about a +// GetUserProfilePhotos request. +type UserProfilePhotosConfig struct { + UserID int + Offset int + Limit int +} + +// FileConfig has information about a file hosted on Telegram. +type FileConfig struct { + FileID string +} + +// UpdateConfig contains information about a GetUpdates request. +type UpdateConfig struct { + Offset int + Limit int + Timeout int +} + +// WebhookConfig contains information about a SetWebhook request. +type WebhookConfig struct { + URL *url.URL + Certificate interface{} + MaxConnections int +} + +// FileBytes contains information about a set of bytes to upload +// as a File. +type FileBytes struct { + Name string + Bytes []byte +} + +// FileReader contains information about a reader to upload as a File. +// If Size is -1, it will read the entire Reader into memory to +// calculate a Size. +type FileReader struct { + Name string + Reader io.Reader + Size int64 +} + +// InlineConfig contains information on making an InlineQuery response. +type InlineConfig struct { + InlineQueryID string `json:"inline_query_id"` + Results []interface{} `json:"results"` + CacheTime int `json:"cache_time"` + IsPersonal bool `json:"is_personal"` + NextOffset string `json:"next_offset"` + SwitchPMText string `json:"switch_pm_text"` + SwitchPMParameter string `json:"switch_pm_parameter"` +} + +// CallbackConfig contains information on making a CallbackQuery response. +type CallbackConfig struct { + CallbackQueryID string `json:"callback_query_id"` + Text string `json:"text"` + ShowAlert bool `json:"show_alert"` + URL string `json:"url"` + CacheTime int `json:"cache_time"` +} + +// ChatMemberConfig contains information about a user in a chat for use +// with administrative functions such as kicking or unbanning a user. +type ChatMemberConfig struct { + ChatID int64 + SuperGroupUsername string + ChannelUsername string + UserID int +} + +// KickChatMemberConfig contains extra fields to kick user +type KickChatMemberConfig struct { + ChatMemberConfig + UntilDate int64 +} + +// RestrictChatMemberConfig contains fields to restrict members of chat +type RestrictChatMemberConfig struct { + ChatMemberConfig + UntilDate int64 + CanSendMessages *bool + CanSendMediaMessages *bool + CanSendOtherMessages *bool + CanAddWebPagePreviews *bool +} + +// PromoteChatMemberConfig contains fields to promote members of chat +type PromoteChatMemberConfig struct { + ChatMemberConfig + CanChangeInfo *bool + CanPostMessages *bool + CanEditMessages *bool + CanDeleteMessages *bool + CanInviteUsers *bool + CanRestrictMembers *bool + CanPinMessages *bool + CanPromoteMembers *bool +} + +// ChatConfig contains information about getting information on a chat. +type ChatConfig struct { + ChatID int64 + SuperGroupUsername string +} + +// ChatConfigWithUser contains information about getting information on +// a specific user within a chat. +type ChatConfigWithUser struct { + ChatID int64 + SuperGroupUsername string + UserID int +} + +// InvoiceConfig contains information for sendInvoice request. +type InvoiceConfig struct { + BaseChat + Title string // required + Description string // required + Payload string // required + ProviderToken string // required + StartParameter string // required + Currency string // required + Prices *[]LabeledPrice // required + PhotoURL string + PhotoSize int + PhotoWidth int + PhotoHeight int + NeedName bool + NeedPhoneNumber bool + NeedEmail bool + NeedShippingAddress bool + IsFlexible bool +} + +func (config InvoiceConfig) values() (url.Values, error) { + v, err := config.BaseChat.values() + if err != nil { + return v, err + } + v.Add("title", config.Title) + v.Add("description", config.Description) + v.Add("payload", config.Payload) + v.Add("provider_token", config.ProviderToken) + v.Add("start_parameter", config.StartParameter) + v.Add("currency", config.Currency) + data, err := json.Marshal(config.Prices) + if err != nil { + return v, err + } + v.Add("prices", string(data)) + if config.PhotoURL != "" { + v.Add("photo_url", config.PhotoURL) + } + if config.PhotoSize != 0 { + v.Add("photo_size", strconv.Itoa(config.PhotoSize)) + } + if config.PhotoWidth != 0 { + v.Add("photo_width", strconv.Itoa(config.PhotoWidth)) + } + if config.PhotoHeight != 0 { + v.Add("photo_height", strconv.Itoa(config.PhotoHeight)) + } + if config.NeedName != false { + v.Add("need_name", strconv.FormatBool(config.NeedName)) + } + if config.NeedPhoneNumber != false { + v.Add("need_phone_number", strconv.FormatBool(config.NeedPhoneNumber)) + } + if config.NeedEmail != false { + v.Add("need_email", strconv.FormatBool(config.NeedEmail)) + } + if config.NeedShippingAddress != false { + v.Add("need_shipping_address", strconv.FormatBool(config.NeedShippingAddress)) + } + if config.IsFlexible != false { + v.Add("is_flexible", strconv.FormatBool(config.IsFlexible)) + } + + return v, nil +} + +func (config InvoiceConfig) method() string { + return "sendInvoice" +} + +// ShippingConfig contains information for answerShippingQuery request. +type ShippingConfig struct { + ShippingQueryID string // required + OK bool // required + ShippingOptions *[]ShippingOption + ErrorMessage string +} + +// PreCheckoutConfig conatins information for answerPreCheckoutQuery request. +type PreCheckoutConfig struct { + PreCheckoutQueryID string // required + OK bool // required + ErrorMessage string +} + +// DeleteMessageConfig contains information of a message in a chat to delete. +type DeleteMessageConfig struct { + ChatID int64 + MessageID int +} + +func (config DeleteMessageConfig) method() string { + return "deleteMessage" +} + +func (config DeleteMessageConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + v.Add("message_id", strconv.Itoa(config.MessageID)) + + return v, nil +} + +// PinChatMessageConfig contains information of a message in a chat to pin. +type PinChatMessageConfig struct { + ChatID int64 + MessageID int + DisableNotification bool +} + +func (config PinChatMessageConfig) method() string { + return "pinChatMessage" +} + +func (config PinChatMessageConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + v.Add("message_id", strconv.Itoa(config.MessageID)) + v.Add("disable_notification", strconv.FormatBool(config.DisableNotification)) + + return v, nil +} + +// UnpinChatMessageConfig contains information of chat to unpin. +type UnpinChatMessageConfig struct { + ChatID int64 +} + +func (config UnpinChatMessageConfig) method() string { + return "unpinChatMessage" +} + +func (config UnpinChatMessageConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + + return v, nil +} + +// SetChatTitleConfig contains information for change chat title. +type SetChatTitleConfig struct { + ChatID int64 + Title string +} + +func (config SetChatTitleConfig) method() string { + return "setChatTitle" +} + +func (config SetChatTitleConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + v.Add("title", config.Title) + + return v, nil +} + +// SetChatDescriptionConfig contains information for change chat description. +type SetChatDescriptionConfig struct { + ChatID int64 + Description string +} + +func (config SetChatDescriptionConfig) method() string { + return "setChatDescription" +} + +func (config SetChatDescriptionConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + v.Add("description", config.Description) + + return v, nil +} + +// SetChatPhotoConfig contains information for change chat photo +type SetChatPhotoConfig struct { + BaseFile +} + +// name returns the field name for the Photo. +func (config SetChatPhotoConfig) name() string { + return "photo" +} + +// method returns Telegram API method name for sending Photo. +func (config SetChatPhotoConfig) method() string { + return "setChatPhoto" +} + +// DeleteChatPhotoConfig contains information for delete chat photo. +type DeleteChatPhotoConfig struct { + ChatID int64 +} + +func (config DeleteChatPhotoConfig) method() string { + return "deleteChatPhoto" +} + +func (config DeleteChatPhotoConfig) values() (url.Values, error) { + v := url.Values{} + + v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) + + return v, nil +} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go new file mode 100644 index 000000000..f49cbbab2 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/helpers.go @@ -0,0 +1,749 @@ +package tgbotapi + +import ( + "net/url" +) + +// NewMessage creates a new Message. +// +// chatID is where to send it, text is the message text. +func NewMessage(chatID int64, text string) MessageConfig { + return MessageConfig{ + BaseChat: BaseChat{ + ChatID: chatID, + ReplyToMessageID: 0, + }, + Text: text, + DisableWebPagePreview: false, + } +} + +// NewDeleteMessage creates a request to delete a message. +func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { + return DeleteMessageConfig{ + ChatID: chatID, + MessageID: messageID, + } +} + +// NewMessageToChannel creates a new Message that is sent to a channel +// by username. +// +// username is the username of the channel, text is the message text. +func NewMessageToChannel(username string, text string) MessageConfig { + return MessageConfig{ + BaseChat: BaseChat{ + ChannelUsername: username, + }, + Text: text, + } +} + +// NewForward creates a new forward. +// +// chatID is where to send it, fromChatID is the source chat, +// and messageID is the ID of the original message. +func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { + return ForwardConfig{ + BaseChat: BaseChat{ChatID: chatID}, + FromChatID: fromChatID, + MessageID: messageID, + } +} + +// NewPhotoUpload creates a new photo uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +// +// Note that you must send animated GIFs as a document. +func NewPhotoUpload(chatID int64, file interface{}) PhotoConfig { + return PhotoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewPhotoShare shares an existing photo. +// You may use this to reshare an existing photo without reuploading it. +// +// chatID is where to send it, fileID is the ID of the file +// already uploaded. +func NewPhotoShare(chatID int64, fileID string) PhotoConfig { + return PhotoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewAudioUpload creates a new audio uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewAudioUpload(chatID int64, file interface{}) AudioConfig { + return AudioConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewAudioShare shares an existing audio file. +// You may use this to reshare an existing audio file without +// reuploading it. +// +// chatID is where to send it, fileID is the ID of the audio +// already uploaded. +func NewAudioShare(chatID int64, fileID string) AudioConfig { + return AudioConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewDocumentUpload creates a new document uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewDocumentUpload(chatID int64, file interface{}) DocumentConfig { + return DocumentConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewDocumentShare shares an existing document. +// You may use this to reshare an existing document without +// reuploading it. +// +// chatID is where to send it, fileID is the ID of the document +// already uploaded. +func NewDocumentShare(chatID int64, fileID string) DocumentConfig { + return DocumentConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewStickerUpload creates a new sticker uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewStickerUpload(chatID int64, file interface{}) StickerConfig { + return StickerConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewStickerShare shares an existing sticker. +// You may use this to reshare an existing sticker without +// reuploading it. +// +// chatID is where to send it, fileID is the ID of the sticker +// already uploaded. +func NewStickerShare(chatID int64, fileID string) StickerConfig { + return StickerConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewVideoUpload creates a new video uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewVideoUpload(chatID int64, file interface{}) VideoConfig { + return VideoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewVideoShare shares an existing video. +// You may use this to reshare an existing video without reuploading it. +// +// chatID is where to send it, fileID is the ID of the video +// already uploaded. +func NewVideoShare(chatID int64, fileID string) VideoConfig { + return VideoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewAnimationUpload creates a new animation uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewAnimationUpload(chatID int64, file interface{}) AnimationConfig { + return AnimationConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewAnimationShare shares an existing animation. +// You may use this to reshare an existing animation without reuploading it. +// +// chatID is where to send it, fileID is the ID of the animation +// already uploaded. +func NewAnimationShare(chatID int64, fileID string) AnimationConfig { + return AnimationConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewVideoNoteUpload creates a new video note uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewVideoNoteUpload(chatID int64, length int, file interface{}) VideoNoteConfig { + return VideoNoteConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + Length: length, + } +} + +// NewVideoNoteShare shares an existing video. +// You may use this to reshare an existing video without reuploading it. +// +// chatID is where to send it, fileID is the ID of the video +// already uploaded. +func NewVideoNoteShare(chatID int64, length int, fileID string) VideoNoteConfig { + return VideoNoteConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + Length: length, + } +} + +// NewVoiceUpload creates a new voice uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +func NewVoiceUpload(chatID int64, file interface{}) VoiceConfig { + return VoiceConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewVoiceShare shares an existing voice. +// You may use this to reshare an existing voice without reuploading it. +// +// chatID is where to send it, fileID is the ID of the video +// already uploaded. +func NewVoiceShare(chatID int64, fileID string) VoiceConfig { + return VoiceConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} + +// NewMediaGroup creates a new media group. Files should be an array of +// two to ten InputMediaPhoto or InputMediaVideo. +func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { + return MediaGroupConfig{ + BaseChat: BaseChat{ + ChatID: chatID, + }, + InputMedia: files, + } +} + +// NewInputMediaPhoto creates a new InputMediaPhoto. +func NewInputMediaPhoto(media string) InputMediaPhoto { + return InputMediaPhoto{ + Type: "photo", + Media: media, + } +} + +// NewInputMediaVideo creates a new InputMediaVideo. +func NewInputMediaVideo(media string) InputMediaVideo { + return InputMediaVideo{ + Type: "video", + Media: media, + } +} + +// NewContact allows you to send a shared contact. +func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { + return ContactConfig{ + BaseChat: BaseChat{ + ChatID: chatID, + }, + PhoneNumber: phoneNumber, + FirstName: firstName, + } +} + +// NewLocation shares your location. +// +// chatID is where to send it, latitude and longitude are coordinates. +func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig { + return LocationConfig{ + BaseChat: BaseChat{ + ChatID: chatID, + }, + Latitude: latitude, + Longitude: longitude, + } +} + +// NewVenue allows you to send a venue and its location. +func NewVenue(chatID int64, title, address string, latitude, longitude float64) VenueConfig { + return VenueConfig{ + BaseChat: BaseChat{ + ChatID: chatID, + }, + Title: title, + Address: address, + Latitude: latitude, + Longitude: longitude, + } +} + +// NewChatAction sets a chat action. +// Actions last for 5 seconds, or until your next action. +// +// chatID is where to send it, action should be set via Chat constants. +func NewChatAction(chatID int64, action string) ChatActionConfig { + return ChatActionConfig{ + BaseChat: BaseChat{ChatID: chatID}, + Action: action, + } +} + +// NewUserProfilePhotos gets user profile photos. +// +// userID is the ID of the user you wish to get profile photos from. +func NewUserProfilePhotos(userID int) UserProfilePhotosConfig { + return UserProfilePhotosConfig{ + UserID: userID, + Offset: 0, + Limit: 0, + } +} + +// NewUpdate gets updates since the last Offset. +// +// offset is the last Update ID to include. +// You likely want to set this to the last Update ID plus 1. +func NewUpdate(offset int) UpdateConfig { + return UpdateConfig{ + Offset: offset, + Limit: 0, + Timeout: 0, + } +} + +// NewWebhook creates a new webhook. +// +// link is the url parsable link you wish to get the updates. +func NewWebhook(link string) WebhookConfig { + u, _ := url.Parse(link) + + return WebhookConfig{ + URL: u, + } +} + +// NewWebhookWithCert creates a new webhook with a certificate. +// +// link is the url you wish to get webhooks, +// file contains a string to a file, FileReader, or FileBytes. +func NewWebhookWithCert(link string, file interface{}) WebhookConfig { + u, _ := url.Parse(link) + + return WebhookConfig{ + URL: u, + Certificate: file, + } +} + +// NewInlineQueryResultArticle creates a new inline query article. +func NewInlineQueryResultArticle(id, title, messageText string) InlineQueryResultArticle { + return InlineQueryResultArticle{ + Type: "article", + ID: id, + Title: title, + InputMessageContent: InputTextMessageContent{ + Text: messageText, + }, + } +} + +// NewInlineQueryResultArticleMarkdown creates a new inline query article with Markdown parsing. +func NewInlineQueryResultArticleMarkdown(id, title, messageText string) InlineQueryResultArticle { + return InlineQueryResultArticle{ + Type: "article", + ID: id, + Title: title, + InputMessageContent: InputTextMessageContent{ + Text: messageText, + ParseMode: "Markdown", + }, + } +} + +// NewInlineQueryResultArticleHTML creates a new inline query article with HTML parsing. +func NewInlineQueryResultArticleHTML(id, title, messageText string) InlineQueryResultArticle { + return InlineQueryResultArticle{ + Type: "article", + ID: id, + Title: title, + InputMessageContent: InputTextMessageContent{ + Text: messageText, + ParseMode: "HTML", + }, + } +} + +// NewInlineQueryResultGIF creates a new inline query GIF. +func NewInlineQueryResultGIF(id, url string) InlineQueryResultGIF { + return InlineQueryResultGIF{ + Type: "gif", + ID: id, + URL: url, + } +} + +// NewInlineQueryResultMPEG4GIF creates a new inline query MPEG4 GIF. +func NewInlineQueryResultMPEG4GIF(id, url string) InlineQueryResultMPEG4GIF { + return InlineQueryResultMPEG4GIF{ + Type: "mpeg4_gif", + ID: id, + URL: url, + } +} + +// NewInlineQueryResultPhoto creates a new inline query photo. +func NewInlineQueryResultPhoto(id, url string) InlineQueryResultPhoto { + return InlineQueryResultPhoto{ + Type: "photo", + ID: id, + URL: url, + } +} + +// NewInlineQueryResultPhotoWithThumb creates a new inline query photo. +func NewInlineQueryResultPhotoWithThumb(id, url, thumb string) InlineQueryResultPhoto { + return InlineQueryResultPhoto{ + Type: "photo", + ID: id, + URL: url, + ThumbURL: thumb, + } +} + +// NewInlineQueryResultVideo creates a new inline query video. +func NewInlineQueryResultVideo(id, url string) InlineQueryResultVideo { + return InlineQueryResultVideo{ + Type: "video", + ID: id, + URL: url, + } +} + +// NewInlineQueryResultAudio creates a new inline query audio. +func NewInlineQueryResultAudio(id, url, title string) InlineQueryResultAudio { + return InlineQueryResultAudio{ + Type: "audio", + ID: id, + URL: url, + Title: title, + } +} + +// NewInlineQueryResultVoice creates a new inline query voice. +func NewInlineQueryResultVoice(id, url, title string) InlineQueryResultVoice { + return InlineQueryResultVoice{ + Type: "voice", + ID: id, + URL: url, + Title: title, + } +} + +// NewInlineQueryResultDocument creates a new inline query document. +func NewInlineQueryResultDocument(id, url, title, mimeType string) InlineQueryResultDocument { + return InlineQueryResultDocument{ + Type: "document", + ID: id, + URL: url, + Title: title, + MimeType: mimeType, + } +} + +// NewInlineQueryResultLocation creates a new inline query location. +func NewInlineQueryResultLocation(id, title string, latitude, longitude float64) InlineQueryResultLocation { + return InlineQueryResultLocation{ + Type: "location", + ID: id, + Title: title, + Latitude: latitude, + Longitude: longitude, + } +} + +// NewEditMessageText allows you to edit the text of a message. +func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { + return EditMessageTextConfig{ + BaseEdit: BaseEdit{ + ChatID: chatID, + MessageID: messageID, + }, + Text: text, + } +} + +// NewEditMessageCaption allows you to edit the caption of a message. +func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMessageCaptionConfig { + return EditMessageCaptionConfig{ + BaseEdit: BaseEdit{ + ChatID: chatID, + MessageID: messageID, + }, + Caption: caption, + } +} + +// NewEditMessageReplyMarkup allows you to edit the inline +// keyboard markup. +func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup InlineKeyboardMarkup) EditMessageReplyMarkupConfig { + return EditMessageReplyMarkupConfig{ + BaseEdit: BaseEdit{ + ChatID: chatID, + MessageID: messageID, + ReplyMarkup: &replyMarkup, + }, + } +} + +// NewHideKeyboard hides the keyboard, with the option for being selective +// or hiding for everyone. +func NewHideKeyboard(selective bool) ReplyKeyboardHide { + log.Println("NewHideKeyboard is deprecated, please use NewRemoveKeyboard") + + return ReplyKeyboardHide{ + HideKeyboard: true, + Selective: selective, + } +} + +// NewRemoveKeyboard hides the keyboard, with the option for being selective +// or hiding for everyone. +func NewRemoveKeyboard(selective bool) ReplyKeyboardRemove { + return ReplyKeyboardRemove{ + RemoveKeyboard: true, + Selective: selective, + } +} + +// NewKeyboardButton creates a regular keyboard button. +func NewKeyboardButton(text string) KeyboardButton { + return KeyboardButton{ + Text: text, + } +} + +// NewKeyboardButtonContact creates a keyboard button that requests +// user contact information upon click. +func NewKeyboardButtonContact(text string) KeyboardButton { + return KeyboardButton{ + Text: text, + RequestContact: true, + } +} + +// NewKeyboardButtonLocation creates a keyboard button that requests +// user location information upon click. +func NewKeyboardButtonLocation(text string) KeyboardButton { + return KeyboardButton{ + Text: text, + RequestLocation: true, + } +} + +// NewKeyboardButtonRow creates a row of keyboard buttons. +func NewKeyboardButtonRow(buttons ...KeyboardButton) []KeyboardButton { + var row []KeyboardButton + + row = append(row, buttons...) + + return row +} + +// NewReplyKeyboard creates a new regular keyboard with sane defaults. +func NewReplyKeyboard(rows ...[]KeyboardButton) ReplyKeyboardMarkup { + var keyboard [][]KeyboardButton + + keyboard = append(keyboard, rows...) + + return ReplyKeyboardMarkup{ + ResizeKeyboard: true, + Keyboard: keyboard, + } +} + +// NewInlineKeyboardButtonData creates an inline keyboard button with text +// and data for a callback. +func NewInlineKeyboardButtonData(text, data string) InlineKeyboardButton { + return InlineKeyboardButton{ + Text: text, + CallbackData: &data, + } +} + +// NewInlineKeyboardButtonURL creates an inline keyboard button with text +// which goes to a URL. +func NewInlineKeyboardButtonURL(text, url string) InlineKeyboardButton { + return InlineKeyboardButton{ + Text: text, + URL: &url, + } +} + +// NewInlineKeyboardButtonSwitch creates an inline keyboard button with +// text which allows the user to switch to a chat or return to a chat. +func NewInlineKeyboardButtonSwitch(text, sw string) InlineKeyboardButton { + return InlineKeyboardButton{ + Text: text, + SwitchInlineQuery: &sw, + } +} + +// NewInlineKeyboardRow creates an inline keyboard row with buttons. +func NewInlineKeyboardRow(buttons ...InlineKeyboardButton) []InlineKeyboardButton { + var row []InlineKeyboardButton + + row = append(row, buttons...) + + return row +} + +// NewInlineKeyboardMarkup creates a new inline keyboard. +func NewInlineKeyboardMarkup(rows ...[]InlineKeyboardButton) InlineKeyboardMarkup { + var keyboard [][]InlineKeyboardButton + + keyboard = append(keyboard, rows...) + + return InlineKeyboardMarkup{ + InlineKeyboard: keyboard, + } +} + +// NewCallback creates a new callback message. +func NewCallback(id, text string) CallbackConfig { + return CallbackConfig{ + CallbackQueryID: id, + Text: text, + ShowAlert: false, + } +} + +// NewCallbackWithAlert creates a new callback message that alerts +// the user. +func NewCallbackWithAlert(id, text string) CallbackConfig { + return CallbackConfig{ + CallbackQueryID: id, + Text: text, + ShowAlert: true, + } +} + +// NewInvoice creates a new Invoice request to the user. +func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices *[]LabeledPrice) InvoiceConfig { + return InvoiceConfig{ + BaseChat: BaseChat{ChatID: chatID}, + Title: title, + Description: description, + Payload: payload, + ProviderToken: providerToken, + StartParameter: startParameter, + Currency: currency, + Prices: prices} +} + +// NewSetChatPhotoUpload creates a new chat photo uploader. +// +// chatID is where to send it, file is a string path to the file, +// FileReader, or FileBytes. +// +// Note that you must send animated GIFs as a document. +func NewSetChatPhotoUpload(chatID int64, file interface{}) SetChatPhotoConfig { + return SetChatPhotoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + File: file, + UseExisting: false, + }, + } +} + +// NewSetChatPhotoShare shares an existing photo. +// You may use this to reshare an existing photo without reuploading it. +// +// chatID is where to send it, fileID is the ID of the file +// already uploaded. +func NewSetChatPhotoShare(chatID int64, fileID string) SetChatPhotoConfig { + return SetChatPhotoConfig{ + BaseFile: BaseFile{ + BaseChat: BaseChat{ChatID: chatID}, + FileID: fileID, + UseExisting: true, + }, + } +} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go new file mode 100644 index 000000000..18725514f --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/log.go @@ -0,0 +1,27 @@ +package tgbotapi + +import ( + "errors" + stdlog "log" + "os" +) + +// BotLogger is an interface that represents the required methods to log data. +// +// Instead of requiring the standard logger, we can just specify the methods we +// use and allow users to pass anything that implements these. +type BotLogger interface { + Println(v ...interface{}) + Printf(format string, v ...interface{}) +} + +var log BotLogger = stdlog.New(os.Stderr, "", stdlog.LstdFlags) + +// SetLogger specifies the logger that the package should use. +func SetLogger(logger BotLogger) error { + if logger == nil { + return errors.New("logger is nil") + } + log = logger + return nil +} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go new file mode 100644 index 000000000..5f55006d9 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/passport.go @@ -0,0 +1,315 @@ +package tgbotapi + +// PassportRequestInfoConfig allows you to request passport info +type PassportRequestInfoConfig struct { + BotID int `json:"bot_id"` + Scope *PassportScope `json:"scope"` + Nonce string `json:"nonce"` + PublicKey string `json:"public_key"` +} + +// PassportScopeElement supports using one or one of several elements. +type PassportScopeElement interface { + ScopeType() string +} + +// PassportScope is the requested scopes of data. +type PassportScope struct { + V int `json:"v"` + Data []PassportScopeElement `json:"data"` +} + +// PassportScopeElementOneOfSeveral allows you to request any one of the +// requested documents. +type PassportScopeElementOneOfSeveral struct { +} + +// ScopeType is the scope type. +func (eo *PassportScopeElementOneOfSeveral) ScopeType() string { + return "one_of" +} + +// PassportScopeElementOne requires the specified element be provided. +type PassportScopeElementOne struct { + Type string `json:"type"` // One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email” + Selfie bool `json:"selfie"` + Translation bool `json:"translation"` + NativeNames bool `json:"native_name"` +} + +// ScopeType is the scope type. +func (eo *PassportScopeElementOne) ScopeType() string { + return "one" +} + +type ( + // PassportData contains information about Telegram Passport data shared with + // the bot by the user. + PassportData struct { + // Array with information about documents and other Telegram Passport + // elements that was shared with the bot + Data []EncryptedPassportElement `json:"data"` + + // Encrypted credentials required to decrypt the data + Credentials *EncryptedCredentials `json:"credentials"` + } + + // PassportFile represents a file uploaded to Telegram Passport. Currently all + // Telegram Passport files are in JPEG format when decrypted and don't exceed + // 10MB. + PassportFile struct { + // Unique identifier for this file + FileID string `json:"file_id"` + + // File size + FileSize int `json:"file_size"` + + // Unix time when the file was uploaded + FileDate int64 `json:"file_date"` + } + + // EncryptedPassportElement contains information about documents or other + // Telegram Passport elements shared with the bot by the user. + EncryptedPassportElement struct { + // Element type. + Type string `json:"type"` + + // Base64-encoded encrypted Telegram Passport element data provided by + // the user, available for "personal_details", "passport", + // "driver_license", "identity_card", "identity_passport" and "address" + // types. Can be decrypted and verified using the accompanying + // EncryptedCredentials. + Data string `json:"data,omitempty"` + + // User's verified phone number, available only for "phone_number" type + PhoneNumber string `json:"phone_number,omitempty"` + + // User's verified email address, available only for "email" type + Email string `json:"email,omitempty"` + + // Array of encrypted files with documents provided by the user, + // available for "utility_bill", "bank_statement", "rental_agreement", + // "passport_registration" and "temporary_registration" types. Files can + // be decrypted and verified using the accompanying EncryptedCredentials. + Files []PassportFile `json:"files,omitempty"` + + // Encrypted file with the front side of the document, provided by the + // user. Available for "passport", "driver_license", "identity_card" and + // "internal_passport". The file can be decrypted and verified using the + // accompanying EncryptedCredentials. + FrontSide *PassportFile `json:"front_side,omitempty"` + + // Encrypted file with the reverse side of the document, provided by the + // user. Available for "driver_license" and "identity_card". The file can + // be decrypted and verified using the accompanying EncryptedCredentials. + ReverseSide *PassportFile `json:"reverse_side,omitempty"` + + // Encrypted file with the selfie of the user holding a document, + // provided by the user; available for "passport", "driver_license", + // "identity_card" and "internal_passport". The file can be decrypted + // and verified using the accompanying EncryptedCredentials. + Selfie *PassportFile `json:"selfie,omitempty"` + } + + // EncryptedCredentials contains data required for decrypting and + // authenticating EncryptedPassportElement. See the Telegram Passport + // Documentation for a complete description of the data decryption and + // authentication processes. + EncryptedCredentials struct { + // Base64-encoded encrypted JSON-serialized data with unique user's + // payload, data hashes and secrets required for EncryptedPassportElement + // decryption and authentication + Data string `json:"data"` + + // Base64-encoded data hash for data authentication + Hash string `json:"hash"` + + // Base64-encoded secret, encrypted with the bot's public RSA key, + // required for data decryption + Secret string `json:"secret"` + } + + // PassportElementError represents an error in the Telegram Passport element + // which was submitted that should be resolved by the user. + PassportElementError interface{} + + // PassportElementErrorDataField represents an issue in one of the data + // fields that was provided by the user. The error is considered resolved + // when the field's value changes. + PassportElementErrorDataField struct { + // Error source, must be data + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the error, one + // of "personal_details", "passport", "driver_license", "identity_card", + // "internal_passport", "address" + Type string `json:"type"` + + // Name of the data field which has the error + FieldName string `json:"field_name"` + + // Base64-encoded data hash + DataHash string `json:"data_hash"` + + // Error message + Message string `json:"message"` + } + + // PassportElementErrorFrontSide represents an issue with the front side of + // a document. The error is considered resolved when the file with the front + // side of the document changes. + PassportElementErrorFrontSide struct { + // Error source, must be front_side + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the issue, one + // of "passport", "driver_license", "identity_card", "internal_passport" + Type string `json:"type"` + + // Base64-encoded hash of the file with the front side of the document + FileHash string `json:"file_hash"` + + // Error message + Message string `json:"message"` + } + + // PassportElementErrorReverseSide represents an issue with the reverse side + // of a document. The error is considered resolved when the file with reverse + // side of the document changes. + PassportElementErrorReverseSide struct { + // Error source, must be reverse_side + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the issue, one + // of "driver_license", "identity_card" + Type string `json:"type"` + + // Base64-encoded hash of the file with the reverse side of the document + FileHash string `json:"file_hash"` + + // Error message + Message string `json:"message"` + } + + // PassportElementErrorSelfie represents an issue with the selfie with a + // document. The error is considered resolved when the file with the selfie + // changes. + PassportElementErrorSelfie struct { + // Error source, must be selfie + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the issue, one + // of "passport", "driver_license", "identity_card", "internal_passport" + Type string `json:"type"` + + // Base64-encoded hash of the file with the selfie + FileHash string `json:"file_hash"` + + // Error message + Message string `json:"message"` + } + + // PassportElementErrorFile represents an issue with a document scan. The + // error is considered resolved when the file with the document scan changes. + PassportElementErrorFile struct { + // Error source, must be file + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the issue, one + // of "utility_bill", "bank_statement", "rental_agreement", + // "passport_registration", "temporary_registration" + Type string `json:"type"` + + // Base64-encoded file hash + FileHash string `json:"file_hash"` + + // Error message + Message string `json:"message"` + } + + // PassportElementErrorFiles represents an issue with a list of scans. The + // error is considered resolved when the list of files containing the scans + // changes. + PassportElementErrorFiles struct { + // Error source, must be files + Source string `json:"source"` + + // The section of the user's Telegram Passport which has the issue, one + // of "utility_bill", "bank_statement", "rental_agreement", + // "passport_registration", "temporary_registration" + Type string `json:"type"` + + // List of base64-encoded file hashes + FileHashes []string `json:"file_hashes"` + + // Error message + Message string `json:"message"` + } + + // Credentials contains encrypted data. + Credentials struct { + Data SecureData `json:"secure_data"` + // Nonce the same nonce given in the request + Nonce string `json:"nonce"` + } + + // SecureData is a map of the fields and their encrypted values. + SecureData map[string]*SecureValue + // PersonalDetails *SecureValue `json:"personal_details"` + // Passport *SecureValue `json:"passport"` + // InternalPassport *SecureValue `json:"internal_passport"` + // DriverLicense *SecureValue `json:"driver_license"` + // IdentityCard *SecureValue `json:"identity_card"` + // Address *SecureValue `json:"address"` + // UtilityBill *SecureValue `json:"utility_bill"` + // BankStatement *SecureValue `json:"bank_statement"` + // RentalAgreement *SecureValue `json:"rental_agreement"` + // PassportRegistration *SecureValue `json:"passport_registration"` + // TemporaryRegistration *SecureValue `json:"temporary_registration"` + + // SecureValue contains encrypted values for a SecureData item. + SecureValue struct { + Data *DataCredentials `json:"data"` + FrontSide *FileCredentials `json:"front_side"` + ReverseSide *FileCredentials `json:"reverse_side"` + Selfie *FileCredentials `json:"selfie"` + Translation []*FileCredentials `json:"translation"` + Files []*FileCredentials `json:"files"` + } + + // DataCredentials contains information required to decrypt data. + DataCredentials struct { + // DataHash checksum of encrypted data + DataHash string `json:"data_hash"` + // Secret of encrypted data + Secret string `json:"secret"` + } + + // FileCredentials contains information required to decrypt files. + FileCredentials struct { + // FileHash checksum of encrypted data + FileHash string `json:"file_hash"` + // Secret of encrypted data + Secret string `json:"secret"` + } + + // PersonalDetails https://core.telegram.org/passport#personaldetails + PersonalDetails struct { + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + MiddleName string `json:"middle_name"` + BirthDate string `json:"birth_date"` + Gender string `json:"gender"` + CountryCode string `json:"country_code"` + ResidenceCountryCode string `json:"residence_country_code"` + FirstNameNative string `json:"first_name_native"` + LastNameNative string `json:"last_name_native"` + MiddleNameNative string `json:"middle_name_native"` + } + + // IDDocumentData https://core.telegram.org/passport#iddocumentdata + IDDocumentData struct { + DocumentNumber string `json:"document_no"` + ExpiryDate string `json:"expiry_date"` + } +) diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go new file mode 100644 index 000000000..d3c433fb0 --- /dev/null +++ b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/types.go @@ -0,0 +1,819 @@ +package tgbotapi + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" +) + +// APIResponse is a response from the Telegram API with the result +// stored raw. +type APIResponse struct { + Ok bool `json:"ok"` + Result json.RawMessage `json:"result"` + ErrorCode int `json:"error_code"` + Description string `json:"description"` + Parameters *ResponseParameters `json:"parameters"` +} + +// ResponseParameters are various errors that can be returned in APIResponse. +type ResponseParameters struct { + MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional + RetryAfter int `json:"retry_after"` // optional +} + +// Update is an update response, from GetUpdates. +type Update struct { + UpdateID int `json:"update_id"` + Message *Message `json:"message"` + EditedMessage *Message `json:"edited_message"` + ChannelPost *Message `json:"channel_post"` + EditedChannelPost *Message `json:"edited_channel_post"` + InlineQuery *InlineQuery `json:"inline_query"` + ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result"` + CallbackQuery *CallbackQuery `json:"callback_query"` + ShippingQuery *ShippingQuery `json:"shipping_query"` + PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query"` +} + +// UpdatesChannel is the channel for getting updates. +type UpdatesChannel <-chan Update + +// Clear discards all unprocessed incoming updates. +func (ch UpdatesChannel) Clear() { + for len(ch) != 0 { + <-ch + } +} + +// User is a user on Telegram. +type User struct { + ID int `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` // optional + UserName string `json:"username"` // optional + LanguageCode string `json:"language_code"` // optional + IsBot bool `json:"is_bot"` // optional +} + +// String displays a simple text version of a user. +// +// It is normally a user's username, but falls back to a first/last +// name as available. +func (u *User) String() string { + if u.UserName != "" { + return u.UserName + } + + name := u.FirstName + if u.LastName != "" { + name += " " + u.LastName + } + + return name +} + +// GroupChat is a group chat. +type GroupChat struct { + ID int `json:"id"` + Title string `json:"title"` +} + +// ChatPhoto represents a chat photo. +type ChatPhoto struct { + SmallFileID string `json:"small_file_id"` + BigFileID string `json:"big_file_id"` +} + +// Chat contains information about the place a message was sent. +type Chat struct { + ID int64 `json:"id"` + Type string `json:"type"` + Title string `json:"title"` // optional + UserName string `json:"username"` // optional + FirstName string `json:"first_name"` // optional + LastName string `json:"last_name"` // optional + AllMembersAreAdmins bool `json:"all_members_are_administrators"` // optional + Photo *ChatPhoto `json:"photo"` + Description string `json:"description,omitempty"` // optional + InviteLink string `json:"invite_link,omitempty"` // optional +} + +// IsPrivate returns if the Chat is a private conversation. +func (c Chat) IsPrivate() bool { + return c.Type == "private" +} + +// IsGroup returns if the Chat is a group. +func (c Chat) IsGroup() bool { + return c.Type == "group" +} + +// IsSuperGroup returns if the Chat is a supergroup. +func (c Chat) IsSuperGroup() bool { + return c.Type == "supergroup" +} + +// IsChannel returns if the Chat is a channel. +func (c Chat) IsChannel() bool { + return c.Type == "channel" +} + +// ChatConfig returns a ChatConfig struct for chat related methods. +func (c Chat) ChatConfig() ChatConfig { + return ChatConfig{ChatID: c.ID} +} + +// Message is returned by almost every request, and contains data about +// almost anything. +type Message struct { + MessageID int `json:"message_id"` + From *User `json:"from"` // optional + Date int `json:"date"` + Chat *Chat `json:"chat"` + ForwardFrom *User `json:"forward_from"` // optional + ForwardFromChat *Chat `json:"forward_from_chat"` // optional + ForwardFromMessageID int `json:"forward_from_message_id"` // optional + ForwardDate int `json:"forward_date"` // optional + ReplyToMessage *Message `json:"reply_to_message"` // optional + EditDate int `json:"edit_date"` // optional + Text string `json:"text"` // optional + Entities *[]MessageEntity `json:"entities"` // optional + Audio *Audio `json:"audio"` // optional + Document *Document `json:"document"` // optional + Animation *ChatAnimation `json:"animation"` // optional + Game *Game `json:"game"` // optional + Photo *[]PhotoSize `json:"photo"` // optional + Sticker *Sticker `json:"sticker"` // optional + Video *Video `json:"video"` // optional + VideoNote *VideoNote `json:"video_note"` // optional + Voice *Voice `json:"voice"` // optional + Caption string `json:"caption"` // optional + Contact *Contact `json:"contact"` // optional + Location *Location `json:"location"` // optional + Venue *Venue `json:"venue"` // optional + NewChatMembers *[]User `json:"new_chat_members"` // optional + LeftChatMember *User `json:"left_chat_member"` // optional + NewChatTitle string `json:"new_chat_title"` // optional + NewChatPhoto *[]PhotoSize `json:"new_chat_photo"` // optional + DeleteChatPhoto bool `json:"delete_chat_photo"` // optional + GroupChatCreated bool `json:"group_chat_created"` // optional + SuperGroupChatCreated bool `json:"supergroup_chat_created"` // optional + ChannelChatCreated bool `json:"channel_chat_created"` // optional + MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional + MigrateFromChatID int64 `json:"migrate_from_chat_id"` // optional + PinnedMessage *Message `json:"pinned_message"` // optional + Invoice *Invoice `json:"invoice"` // optional + SuccessfulPayment *SuccessfulPayment `json:"successful_payment"` // optional + PassportData *PassportData `json:"passport_data,omitempty"` // optional +} + +// Time converts the message timestamp into a Time. +func (m *Message) Time() time.Time { + return time.Unix(int64(m.Date), 0) +} + +// IsCommand returns true if message starts with a "bot_command" entity. +func (m *Message) IsCommand() bool { + if m.Entities == nil || len(*m.Entities) == 0 { + return false + } + + entity := (*m.Entities)[0] + return entity.Offset == 0 && entity.Type == "bot_command" +} + +// Command checks if the message was a command and if it was, returns the +// command. If the Message was not a command, it returns an empty string. +// +// If the command contains the at name syntax, it is removed. Use +// CommandWithAt() if you do not want that. +func (m *Message) Command() string { + command := m.CommandWithAt() + + if i := strings.Index(command, "@"); i != -1 { + command = command[:i] + } + + return command +} + +// CommandWithAt checks if the message was a command and if it was, returns the +// command. If the Message was not a command, it returns an empty string. +// +// If the command contains the at name syntax, it is not removed. Use Command() +// if you want that. +func (m *Message) CommandWithAt() string { + if !m.IsCommand() { + return "" + } + + // IsCommand() checks that the message begins with a bot_command entity + entity := (*m.Entities)[0] + return m.Text[1:entity.Length] +} + +// CommandArguments checks if the message was a command and if it was, +// returns all text after the command name. If the Message was not a +// command, it returns an empty string. +// +// Note: The first character after the command name is omitted: +// - "/foo bar baz" yields "bar baz", not " bar baz" +// - "/foo-bar baz" yields "bar baz", too +// Even though the latter is not a command conforming to the spec, the API +// marks "/foo" as command entity. +func (m *Message) CommandArguments() string { + if !m.IsCommand() { + return "" + } + + // IsCommand() checks that the message begins with a bot_command entity + entity := (*m.Entities)[0] + if len(m.Text) == entity.Length { + return "" // The command makes up the whole message + } + + return m.Text[entity.Length+1:] +} + +// MessageEntity contains information about data in a Message. +type MessageEntity struct { + Type string `json:"type"` + Offset int `json:"offset"` + Length int `json:"length"` + URL string `json:"url"` // optional + User *User `json:"user"` // optional +} + +// ParseURL attempts to parse a URL contained within a MessageEntity. +func (entity MessageEntity) ParseURL() (*url.URL, error) { + if entity.URL == "" { + return nil, errors.New(ErrBadURL) + } + + return url.Parse(entity.URL) +} + +// PhotoSize contains information about photos. +type PhotoSize struct { + FileID string `json:"file_id"` + Width int `json:"width"` + Height int `json:"height"` + FileSize int `json:"file_size"` // optional +} + +// Audio contains information about audio. +type Audio struct { + FileID string `json:"file_id"` + Duration int `json:"duration"` + Performer string `json:"performer"` // optional + Title string `json:"title"` // optional + MimeType string `json:"mime_type"` // optional + FileSize int `json:"file_size"` // optional +} + +// Document contains information about a document. +type Document struct { + FileID string `json:"file_id"` + Thumbnail *PhotoSize `json:"thumb"` // optional + FileName string `json:"file_name"` // optional + MimeType string `json:"mime_type"` // optional + FileSize int `json:"file_size"` // optional +} + +// Sticker contains information about a sticker. +type Sticker struct { + FileID string `json:"file_id"` + Width int `json:"width"` + Height int `json:"height"` + Thumbnail *PhotoSize `json:"thumb"` // optional + Emoji string `json:"emoji"` // optional + FileSize int `json:"file_size"` // optional + SetName string `json:"set_name"` // optional +} + +// ChatAnimation contains information about an animation. +type ChatAnimation struct { + FileID string `json:"file_id"` + Width int `json:"width"` + Height int `json:"height"` + Duration int `json:"duration"` + Thumbnail *PhotoSize `json:"thumb"` // optional + FileName string `json:"file_name"` // optional + MimeType string `json:"mime_type"` // optional + FileSize int `json:"file_size"` // optional +} + +// Video contains information about a video. +type Video struct { + FileID string `json:"file_id"` + Width int `json:"width"` + Height int `json:"height"` + Duration int `json:"duration"` + Thumbnail *PhotoSize `json:"thumb"` // optional + MimeType string `json:"mime_type"` // optional + FileSize int `json:"file_size"` // optional +} + +// VideoNote contains information about a video. +type VideoNote struct { + FileID string `json:"file_id"` + Length int `json:"length"` + Duration int `json:"duration"` + Thumbnail *PhotoSize `json:"thumb"` // optional + FileSize int `json:"file_size"` // optional +} + +// Voice contains information about a voice. +type Voice struct { + FileID string `json:"file_id"` + Duration int `json:"duration"` + MimeType string `json:"mime_type"` // optional + FileSize int `json:"file_size"` // optional +} + +// Contact contains information about a contact. +// +// Note that LastName and UserID may be empty. +type Contact struct { + PhoneNumber string `json:"phone_number"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` // optional + UserID int `json:"user_id"` // optional +} + +// Location contains information about a place. +type Location struct { + Longitude float64 `json:"longitude"` + Latitude float64 `json:"latitude"` +} + +// Venue contains information about a venue, including its Location. +type Venue struct { + Location Location `json:"location"` + Title string `json:"title"` + Address string `json:"address"` + FoursquareID string `json:"foursquare_id"` // optional +} + +// UserProfilePhotos contains a set of user profile photos. +type UserProfilePhotos struct { + TotalCount int `json:"total_count"` + Photos [][]PhotoSize `json:"photos"` +} + +// File contains information about a file to download from Telegram. +type File struct { + FileID string `json:"file_id"` + FileSize int `json:"file_size"` // optional + FilePath string `json:"file_path"` // optional +} + +// Link returns a full path to the download URL for a File. +// +// It requires the Bot Token to create the link. +func (f *File) Link(token string) string { + return fmt.Sprintf(FileEndpoint, token, f.FilePath) +} + +// ReplyKeyboardMarkup allows the Bot to set a custom keyboard. +type ReplyKeyboardMarkup struct { + Keyboard [][]KeyboardButton `json:"keyboard"` + ResizeKeyboard bool `json:"resize_keyboard"` // optional + OneTimeKeyboard bool `json:"one_time_keyboard"` // optional + Selective bool `json:"selective"` // optional +} + +// KeyboardButton is a button within a custom keyboard. +type KeyboardButton struct { + Text string `json:"text"` + RequestContact bool `json:"request_contact"` + RequestLocation bool `json:"request_location"` +} + +// ReplyKeyboardHide allows the Bot to hide a custom keyboard. +type ReplyKeyboardHide struct { + HideKeyboard bool `json:"hide_keyboard"` + Selective bool `json:"selective"` // optional +} + +// ReplyKeyboardRemove allows the Bot to hide a custom keyboard. +type ReplyKeyboardRemove struct { + RemoveKeyboard bool `json:"remove_keyboard"` + Selective bool `json:"selective"` +} + +// InlineKeyboardMarkup is a custom keyboard presented for an inline bot. +type InlineKeyboardMarkup struct { + InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"` +} + +// InlineKeyboardButton is a button within a custom keyboard for +// inline query responses. +// +// Note that some values are references as even an empty string +// will change behavior. +// +// CallbackGame, if set, MUST be first button in first row. +type InlineKeyboardButton struct { + Text string `json:"text"` + URL *string `json:"url,omitempty"` // optional + CallbackData *string `json:"callback_data,omitempty"` // optional + SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` // optional + SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` // optional + CallbackGame *CallbackGame `json:"callback_game,omitempty"` // optional + Pay bool `json:"pay,omitempty"` // optional +} + +// CallbackQuery is data sent when a keyboard button with callback data +// is clicked. +type CallbackQuery struct { + ID string `json:"id"` + From *User `json:"from"` + Message *Message `json:"message"` // optional + InlineMessageID string `json:"inline_message_id"` // optional + ChatInstance string `json:"chat_instance"` + Data string `json:"data"` // optional + GameShortName string `json:"game_short_name"` // optional +} + +// ForceReply allows the Bot to have users directly reply to it without +// additional interaction. +type ForceReply struct { + ForceReply bool `json:"force_reply"` + Selective bool `json:"selective"` // optional +} + +// ChatMember is information about a member in a chat. +type ChatMember struct { + User *User `json:"user"` + Status string `json:"status"` + UntilDate int64 `json:"until_date,omitempty"` // optional + CanBeEdited bool `json:"can_be_edited,omitempty"` // optional + CanChangeInfo bool `json:"can_change_info,omitempty"` // optional + CanPostMessages bool `json:"can_post_messages,omitempty"` // optional + CanEditMessages bool `json:"can_edit_messages,omitempty"` // optional + CanDeleteMessages bool `json:"can_delete_messages,omitempty"` // optional + CanInviteUsers bool `json:"can_invite_users,omitempty"` // optional + CanRestrictMembers bool `json:"can_restrict_members,omitempty"` // optional + CanPinMessages bool `json:"can_pin_messages,omitempty"` // optional + CanPromoteMembers bool `json:"can_promote_members,omitempty"` // optional + CanSendMessages bool `json:"can_send_messages,omitempty"` // optional + CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` // optional + CanSendOtherMessages bool `json:"can_send_other_messages,omitempty"` // optional + CanAddWebPagePreviews bool `json:"can_add_web_page_previews,omitempty"` // optional +} + +// IsCreator returns if the ChatMember was the creator of the chat. +func (chat ChatMember) IsCreator() bool { return chat.Status == "creator" } + +// IsAdministrator returns if the ChatMember is a chat administrator. +func (chat ChatMember) IsAdministrator() bool { return chat.Status == "administrator" } + +// IsMember returns if the ChatMember is a current member of the chat. +func (chat ChatMember) IsMember() bool { return chat.Status == "member" } + +// HasLeft returns if the ChatMember left the chat. +func (chat ChatMember) HasLeft() bool { return chat.Status == "left" } + +// WasKicked returns if the ChatMember was kicked from the chat. +func (chat ChatMember) WasKicked() bool { return chat.Status == "kicked" } + +// Game is a game within Telegram. +type Game struct { + Title string `json:"title"` + Description string `json:"description"` + Photo []PhotoSize `json:"photo"` + Text string `json:"text"` + TextEntities []MessageEntity `json:"text_entities"` + Animation Animation `json:"animation"` +} + +// Animation is a GIF animation demonstrating the game. +type Animation struct { + FileID string `json:"file_id"` + Thumb PhotoSize `json:"thumb"` + FileName string `json:"file_name"` + MimeType string `json:"mime_type"` + FileSize int `json:"file_size"` +} + +// GameHighScore is a user's score and position on the leaderboard. +type GameHighScore struct { + Position int `json:"position"` + User User `json:"user"` + Score int `json:"score"` +} + +// CallbackGame is for starting a game in an inline keyboard button. +type CallbackGame struct{} + +// WebhookInfo is information about a currently set webhook. +type WebhookInfo struct { + URL string `json:"url"` + HasCustomCertificate bool `json:"has_custom_certificate"` + PendingUpdateCount int `json:"pending_update_count"` + LastErrorDate int `json:"last_error_date"` // optional + LastErrorMessage string `json:"last_error_message"` // optional +} + +// IsSet returns true if a webhook is currently set. +func (info WebhookInfo) IsSet() bool { + return info.URL != "" +} + +// InputMediaPhoto contains a photo for displaying as part of a media group. +type InputMediaPhoto struct { + Type string `json:"type"` + Media string `json:"media"` + Caption string `json:"caption"` + ParseMode string `json:"parse_mode"` +} + +// InputMediaVideo contains a video for displaying as part of a media group. +type InputMediaVideo struct { + Type string `json:"type"` + Media string `json:"media"` + // thumb intentionally missing as it is not currently compatible + Caption string `json:"caption"` + ParseMode string `json:"parse_mode"` + Width int `json:"width"` + Height int `json:"height"` + Duration int `json:"duration"` + SupportsStreaming bool `json:"supports_streaming"` +} + +// InlineQuery is a Query from Telegram for an inline request. +type InlineQuery struct { + ID string `json:"id"` + From *User `json:"from"` + Location *Location `json:"location"` // optional + Query string `json:"query"` + Offset string `json:"offset"` +} + +// InlineQueryResultArticle is an inline query response article. +type InlineQueryResultArticle struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + Title string `json:"title"` // required + InputMessageContent interface{} `json:"input_message_content,omitempty"` // required + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + URL string `json:"url"` + HideURL bool `json:"hide_url"` + Description string `json:"description"` + ThumbURL string `json:"thumb_url"` + ThumbWidth int `json:"thumb_width"` + ThumbHeight int `json:"thumb_height"` +} + +// InlineQueryResultPhoto is an inline query response photo. +type InlineQueryResultPhoto struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"photo_url"` // required + MimeType string `json:"mime_type"` + Width int `json:"photo_width"` + Height int `json:"photo_height"` + ThumbURL string `json:"thumb_url"` + Title string `json:"title"` + Description string `json:"description"` + Caption string `json:"caption"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultGIF is an inline query response GIF. +type InlineQueryResultGIF struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"gif_url"` // required + Width int `json:"gif_width"` + Height int `json:"gif_height"` + Duration int `json:"gif_duration"` + ThumbURL string `json:"thumb_url"` + Title string `json:"title"` + Caption string `json:"caption"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF. +type InlineQueryResultMPEG4GIF struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"mpeg4_url"` // required + Width int `json:"mpeg4_width"` + Height int `json:"mpeg4_height"` + Duration int `json:"mpeg4_duration"` + ThumbURL string `json:"thumb_url"` + Title string `json:"title"` + Caption string `json:"caption"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultVideo is an inline query response video. +type InlineQueryResultVideo struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"video_url"` // required + MimeType string `json:"mime_type"` // required + ThumbURL string `json:"thumb_url"` + Title string `json:"title"` + Caption string `json:"caption"` + Width int `json:"video_width"` + Height int `json:"video_height"` + Duration int `json:"video_duration"` + Description string `json:"description"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultAudio is an inline query response audio. +type InlineQueryResultAudio struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"audio_url"` // required + Title string `json:"title"` // required + Caption string `json:"caption"` + Performer string `json:"performer"` + Duration int `json:"audio_duration"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultVoice is an inline query response voice. +type InlineQueryResultVoice struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + URL string `json:"voice_url"` // required + Title string `json:"title"` // required + Caption string `json:"caption"` + Duration int `json:"voice_duration"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` +} + +// InlineQueryResultDocument is an inline query response document. +type InlineQueryResultDocument struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + Title string `json:"title"` // required + Caption string `json:"caption"` + URL string `json:"document_url"` // required + MimeType string `json:"mime_type"` // required + Description string `json:"description"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` + ThumbURL string `json:"thumb_url"` + ThumbWidth int `json:"thumb_width"` + ThumbHeight int `json:"thumb_height"` +} + +// InlineQueryResultLocation is an inline query response location. +type InlineQueryResultLocation struct { + Type string `json:"type"` // required + ID string `json:"id"` // required + Latitude float64 `json:"latitude"` // required + Longitude float64 `json:"longitude"` // required + Title string `json:"title"` // required + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + InputMessageContent interface{} `json:"input_message_content,omitempty"` + ThumbURL string `json:"thumb_url"` + ThumbWidth int `json:"thumb_width"` + ThumbHeight int `json:"thumb_height"` +} + +// InlineQueryResultGame is an inline query response game. +type InlineQueryResultGame struct { + Type string `json:"type"` + ID string `json:"id"` + GameShortName string `json:"game_short_name"` + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// ChosenInlineResult is an inline query result chosen by a User +type ChosenInlineResult struct { + ResultID string `json:"result_id"` + From *User `json:"from"` + Location *Location `json:"location"` + InlineMessageID string `json:"inline_message_id"` + Query string `json:"query"` +} + +// InputTextMessageContent contains text for displaying +// as an inline query result. +type InputTextMessageContent struct { + Text string `json:"message_text"` + ParseMode string `json:"parse_mode"` + DisableWebPagePreview bool `json:"disable_web_page_preview"` +} + +// InputLocationMessageContent contains a location for displaying +// as an inline query result. +type InputLocationMessageContent struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` +} + +// InputVenueMessageContent contains a venue for displaying +// as an inline query result. +type InputVenueMessageContent struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Title string `json:"title"` + Address string `json:"address"` + FoursquareID string `json:"foursquare_id"` +} + +// InputContactMessageContent contains a contact for displaying +// as an inline query result. +type InputContactMessageContent struct { + PhoneNumber string `json:"phone_number"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` +} + +// Invoice contains basic information about an invoice. +type Invoice struct { + Title string `json:"title"` + Description string `json:"description"` + StartParameter string `json:"start_parameter"` + Currency string `json:"currency"` + TotalAmount int `json:"total_amount"` +} + +// LabeledPrice represents a portion of the price for goods or services. +type LabeledPrice struct { + Label string `json:"label"` + Amount int `json:"amount"` +} + +// ShippingAddress represents a shipping address. +type ShippingAddress struct { + CountryCode string `json:"country_code"` + State string `json:"state"` + City string `json:"city"` + StreetLine1 string `json:"street_line1"` + StreetLine2 string `json:"street_line2"` + PostCode string `json:"post_code"` +} + +// OrderInfo represents information about an order. +type OrderInfo struct { + Name string `json:"name,omitempty"` + PhoneNumber string `json:"phone_number,omitempty"` + Email string `json:"email,omitempty"` + ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` +} + +// ShippingOption represents one shipping option. +type ShippingOption struct { + ID string `json:"id"` + Title string `json:"title"` + Prices *[]LabeledPrice `json:"prices"` +} + +// SuccessfulPayment contains basic information about a successful payment. +type SuccessfulPayment struct { + Currency string `json:"currency"` + TotalAmount int `json:"total_amount"` + InvoicePayload string `json:"invoice_payload"` + ShippingOptionID string `json:"shipping_option_id,omitempty"` + OrderInfo *OrderInfo `json:"order_info,omitempty"` + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` + ProviderPaymentChargeID string `json:"provider_payment_charge_id"` +} + +// ShippingQuery contains information about an incoming shipping query. +type ShippingQuery struct { + ID string `json:"id"` + From *User `json:"from"` + InvoicePayload string `json:"invoice_payload"` + ShippingAddress *ShippingAddress `json:"shipping_address"` +} + +// PreCheckoutQuery contains information about an incoming pre-checkout query. +type PreCheckoutQuery struct { + ID string `json:"id"` + From *User `json:"from"` + Currency string `json:"currency"` + TotalAmount int `json:"total_amount"` + InvoicePayload string `json:"invoice_payload"` + ShippingOptionID string `json:"shipping_option_id,omitempty"` + OrderInfo *OrderInfo `json:"order_info,omitempty"` +} + +// Error is an error containing extra information returned by the Telegram API. +type Error struct { + Message string + ResponseParameters +} + +func (e Error) Error() string { + return e.Message +} diff --git a/vendor/github.com/gorilla/websocket/.gitignore b/vendor/github.com/gorilla/websocket/.gitignore new file mode 100644 index 000000000..cd3fcd1ef --- /dev/null +++ b/vendor/github.com/gorilla/websocket/.gitignore @@ -0,0 +1,25 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +.idea/ +*.iml diff --git a/vendor/github.com/gorilla/websocket/AUTHORS b/vendor/github.com/gorilla/websocket/AUTHORS new file mode 100644 index 000000000..1931f4006 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/AUTHORS @@ -0,0 +1,9 @@ +# This is the official list of Gorilla WebSocket authors for copyright +# purposes. +# +# Please keep the list sorted. + +Gary Burd +Google LLC (https://opensource.google.com/) +Joachim Bauch + diff --git a/vendor/github.com/gorilla/websocket/LICENSE b/vendor/github.com/gorilla/websocket/LICENSE new file mode 100644 index 000000000..9171c9722 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/websocket/README.md b/vendor/github.com/gorilla/websocket/README.md new file mode 100644 index 000000000..d33ed7fdd --- /dev/null +++ b/vendor/github.com/gorilla/websocket/README.md @@ -0,0 +1,33 @@ +# Gorilla WebSocket + +[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) +[![CircleCI](https://circleci.com/gh/gorilla/websocket.svg?style=svg)](https://circleci.com/gh/gorilla/websocket) + +Gorilla WebSocket is a [Go](http://golang.org/) implementation of the +[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. + + +### Documentation + +* [API Reference](https://pkg.go.dev/github.com/gorilla/websocket?tab=doc) +* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) +* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) +* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) +* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) + +### Status + +The Gorilla WebSocket package provides a complete and tested implementation of +the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The +package API is stable. + +### Installation + + go get github.com/gorilla/websocket + +### Protocol Compliance + +The Gorilla WebSocket package passes the server tests in the [Autobahn Test +Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn +subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). + diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go new file mode 100644 index 000000000..04fdafee1 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/client.go @@ -0,0 +1,434 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "io/ioutil" + "net" + "net/http" + "net/http/httptrace" + "net/url" + "strings" + "time" +) + +// ErrBadHandshake is returned when the server response to opening handshake is +// invalid. +var ErrBadHandshake = errors.New("websocket: bad handshake") + +var errInvalidCompression = errors.New("websocket: invalid compression negotiation") + +// NewClient creates a new client connection using the given net connection. +// The URL u specifies the host and request URI. Use requestHeader to specify +// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies +// (Cookie). Use the response.Header to get the selected subprotocol +// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). +// +// If the WebSocket handshake fails, ErrBadHandshake is returned along with a +// non-nil *http.Response so that callers can handle redirects, authentication, +// etc. +// +// Deprecated: Use Dialer instead. +func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) { + d := Dialer{ + ReadBufferSize: readBufSize, + WriteBufferSize: writeBufSize, + NetDial: func(net, addr string) (net.Conn, error) { + return netConn, nil + }, + } + return d.Dial(u.String(), requestHeader) +} + +// A Dialer contains options for connecting to WebSocket server. +// +// It is safe to call Dialer's methods concurrently. +type Dialer struct { + // NetDial specifies the dial function for creating TCP connections. If + // NetDial is nil, net.Dial is used. + NetDial func(network, addr string) (net.Conn, error) + + // NetDialContext specifies the dial function for creating TCP connections. If + // NetDialContext is nil, NetDial is used. + NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error) + + // NetDialTLSContext specifies the dial function for creating TLS/TCP connections. If + // NetDialTLSContext is nil, NetDialContext is used. + // If NetDialTLSContext is set, Dial assumes the TLS handshake is done there and + // TLSClientConfig is ignored. + NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) + + // Proxy specifies a function to return a proxy for a given + // Request. If the function returns a non-nil error, the + // request is aborted with the provided error. + // If Proxy is nil or returns a nil *URL, no proxy is used. + Proxy func(*http.Request) (*url.URL, error) + + // TLSClientConfig specifies the TLS configuration to use with tls.Client. + // If nil, the default configuration is used. + // If either NetDialTLS or NetDialTLSContext are set, Dial assumes the TLS handshake + // is done there and TLSClientConfig is ignored. + TLSClientConfig *tls.Config + + // HandshakeTimeout specifies the duration for the handshake to complete. + HandshakeTimeout time.Duration + + // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer + // size is zero, then a useful default size is used. The I/O buffer sizes + // do not limit the size of the messages that can be sent or received. + ReadBufferSize, WriteBufferSize int + + // WriteBufferPool is a pool of buffers for write operations. If the value + // is not set, then write buffers are allocated to the connection for the + // lifetime of the connection. + // + // A pool is most useful when the application has a modest volume of writes + // across a large number of connections. + // + // Applications should use a single pool for each unique value of + // WriteBufferSize. + WriteBufferPool BufferPool + + // Subprotocols specifies the client's requested subprotocols. + Subprotocols []string + + // EnableCompression specifies if the client should attempt to negotiate + // per message compression (RFC 7692). Setting this value to true does not + // guarantee that compression will be supported. Currently only "no context + // takeover" modes are supported. + EnableCompression bool + + // Jar specifies the cookie jar. + // If Jar is nil, cookies are not sent in requests and ignored + // in responses. + Jar http.CookieJar +} + +// Dial creates a new client connection by calling DialContext with a background context. +func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { + return d.DialContext(context.Background(), urlStr, requestHeader) +} + +var errMalformedURL = errors.New("malformed ws or wss URL") + +func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) { + hostPort = u.Host + hostNoPort = u.Host + if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") { + hostNoPort = hostNoPort[:i] + } else { + switch u.Scheme { + case "wss": + hostPort += ":443" + case "https": + hostPort += ":443" + default: + hostPort += ":80" + } + } + return hostPort, hostNoPort +} + +// DefaultDialer is a dialer with all fields set to the default values. +var DefaultDialer = &Dialer{ + Proxy: http.ProxyFromEnvironment, + HandshakeTimeout: 45 * time.Second, +} + +// nilDialer is dialer to use when receiver is nil. +var nilDialer = *DefaultDialer + +// DialContext creates a new client connection. Use requestHeader to specify the +// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). +// Use the response.Header to get the selected subprotocol +// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). +// +// The context will be used in the request and in the Dialer. +// +// If the WebSocket handshake fails, ErrBadHandshake is returned along with a +// non-nil *http.Response so that callers can handle redirects, authentication, +// etcetera. The response body may not contain the entire response and does not +// need to be closed by the application. +func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { + if d == nil { + d = &nilDialer + } + + challengeKey, err := generateChallengeKey() + if err != nil { + return nil, nil, err + } + + u, err := url.Parse(urlStr) + if err != nil { + return nil, nil, err + } + + switch u.Scheme { + case "ws": + u.Scheme = "http" + case "wss": + u.Scheme = "https" + default: + return nil, nil, errMalformedURL + } + + if u.User != nil { + // User name and password are not allowed in websocket URIs. + return nil, nil, errMalformedURL + } + + req := &http.Request{ + Method: http.MethodGet, + URL: u, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: make(http.Header), + Host: u.Host, + } + req = req.WithContext(ctx) + + // Set the cookies present in the cookie jar of the dialer + if d.Jar != nil { + for _, cookie := range d.Jar.Cookies(u) { + req.AddCookie(cookie) + } + } + + // Set the request headers using the capitalization for names and values in + // RFC examples. Although the capitalization shouldn't matter, there are + // servers that depend on it. The Header.Set method is not used because the + // method canonicalizes the header names. + req.Header["Upgrade"] = []string{"websocket"} + req.Header["Connection"] = []string{"Upgrade"} + req.Header["Sec-WebSocket-Key"] = []string{challengeKey} + req.Header["Sec-WebSocket-Version"] = []string{"13"} + if len(d.Subprotocols) > 0 { + req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")} + } + for k, vs := range requestHeader { + switch { + case k == "Host": + if len(vs) > 0 { + req.Host = vs[0] + } + case k == "Upgrade" || + k == "Connection" || + k == "Sec-Websocket-Key" || + k == "Sec-Websocket-Version" || + k == "Sec-Websocket-Extensions" || + (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): + return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) + case k == "Sec-Websocket-Protocol": + req.Header["Sec-WebSocket-Protocol"] = vs + default: + req.Header[k] = vs + } + } + + if d.EnableCompression { + req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"} + } + + if d.HandshakeTimeout != 0 { + var cancel func() + ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout) + defer cancel() + } + + // Get network dial function. + var netDial func(network, add string) (net.Conn, error) + + switch u.Scheme { + case "http": + if d.NetDialContext != nil { + netDial = func(network, addr string) (net.Conn, error) { + return d.NetDialContext(ctx, network, addr) + } + } else if d.NetDial != nil { + netDial = d.NetDial + } + case "https": + if d.NetDialTLSContext != nil { + netDial = func(network, addr string) (net.Conn, error) { + return d.NetDialTLSContext(ctx, network, addr) + } + } else if d.NetDialContext != nil { + netDial = func(network, addr string) (net.Conn, error) { + return d.NetDialContext(ctx, network, addr) + } + } else if d.NetDial != nil { + netDial = d.NetDial + } + default: + return nil, nil, errMalformedURL + } + + if netDial == nil { + netDialer := &net.Dialer{} + netDial = func(network, addr string) (net.Conn, error) { + return netDialer.DialContext(ctx, network, addr) + } + } + + // If needed, wrap the dial function to set the connection deadline. + if deadline, ok := ctx.Deadline(); ok { + forwardDial := netDial + netDial = func(network, addr string) (net.Conn, error) { + c, err := forwardDial(network, addr) + if err != nil { + return nil, err + } + err = c.SetDeadline(deadline) + if err != nil { + c.Close() + return nil, err + } + return c, nil + } + } + + // If needed, wrap the dial function to connect through a proxy. + if d.Proxy != nil { + proxyURL, err := d.Proxy(req) + if err != nil { + return nil, nil, err + } + if proxyURL != nil { + dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial)) + if err != nil { + return nil, nil, err + } + netDial = dialer.Dial + } + } + + hostPort, hostNoPort := hostPortNoPort(u) + trace := httptrace.ContextClientTrace(ctx) + if trace != nil && trace.GetConn != nil { + trace.GetConn(hostPort) + } + + netConn, err := netDial("tcp", hostPort) + if err != nil { + return nil, nil, err + } + if trace != nil && trace.GotConn != nil { + trace.GotConn(httptrace.GotConnInfo{ + Conn: netConn, + }) + } + + defer func() { + if netConn != nil { + netConn.Close() + } + }() + + if u.Scheme == "https" && d.NetDialTLSContext == nil { + // If NetDialTLSContext is set, assume that the TLS handshake has already been done + + cfg := cloneTLSConfig(d.TLSClientConfig) + if cfg.ServerName == "" { + cfg.ServerName = hostNoPort + } + tlsConn := tls.Client(netConn, cfg) + netConn = tlsConn + + if trace != nil && trace.TLSHandshakeStart != nil { + trace.TLSHandshakeStart() + } + err := doHandshake(ctx, tlsConn, cfg) + if trace != nil && trace.TLSHandshakeDone != nil { + trace.TLSHandshakeDone(tlsConn.ConnectionState(), err) + } + + if err != nil { + return nil, nil, err + } + } + + conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil) + + if err := req.Write(netConn); err != nil { + return nil, nil, err + } + + if trace != nil && trace.GotFirstResponseByte != nil { + if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 { + trace.GotFirstResponseByte() + } + } + + resp, err := http.ReadResponse(conn.br, req) + if err != nil { + if d.TLSClientConfig != nil { + for _, proto := range d.TLSClientConfig.NextProtos { + if proto != "http/1.1" { + return nil, nil, fmt.Errorf( + "websocket: protocol %q was given but is not supported;"+ + "sharing tls.Config with net/http Transport can cause this error: %w", + proto, err, + ) + } + } + } + return nil, nil, err + } + + if d.Jar != nil { + if rc := resp.Cookies(); len(rc) > 0 { + d.Jar.SetCookies(u, rc) + } + } + + if resp.StatusCode != 101 || + !tokenListContainsValue(resp.Header, "Upgrade", "websocket") || + !tokenListContainsValue(resp.Header, "Connection", "upgrade") || + resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) { + // Before closing the network connection on return from this + // function, slurp up some of the response to aid application + // debugging. + buf := make([]byte, 1024) + n, _ := io.ReadFull(resp.Body, buf) + resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) + return nil, resp, ErrBadHandshake + } + + for _, ext := range parseExtensions(resp.Header) { + if ext[""] != "permessage-deflate" { + continue + } + _, snct := ext["server_no_context_takeover"] + _, cnct := ext["client_no_context_takeover"] + if !snct || !cnct { + return nil, resp, errInvalidCompression + } + conn.newCompressionWriter = compressNoContextTakeover + conn.newDecompressionReader = decompressNoContextTakeover + break + } + + resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") + + netConn.SetDeadline(time.Time{}) + netConn = nil // to avoid close in defer. + return conn, resp, nil +} + +func cloneTLSConfig(cfg *tls.Config) *tls.Config { + if cfg == nil { + return &tls.Config{} + } + return cfg.Clone() +} diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go new file mode 100644 index 000000000..813ffb1e8 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/compression.go @@ -0,0 +1,148 @@ +// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "compress/flate" + "errors" + "io" + "strings" + "sync" +) + +const ( + minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 + maxCompressionLevel = flate.BestCompression + defaultCompressionLevel = 1 +) + +var ( + flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool + flateReaderPool = sync.Pool{New: func() interface{} { + return flate.NewReader(nil) + }} +) + +func decompressNoContextTakeover(r io.Reader) io.ReadCloser { + const tail = + // Add four bytes as specified in RFC + "\x00\x00\xff\xff" + + // Add final block to squelch unexpected EOF error from flate reader. + "\x01\x00\x00\xff\xff" + + fr, _ := flateReaderPool.Get().(io.ReadCloser) + fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) + return &flateReadWrapper{fr} +} + +func isValidCompressionLevel(level int) bool { + return minCompressionLevel <= level && level <= maxCompressionLevel +} + +func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { + p := &flateWriterPools[level-minCompressionLevel] + tw := &truncWriter{w: w} + fw, _ := p.Get().(*flate.Writer) + if fw == nil { + fw, _ = flate.NewWriter(tw, level) + } else { + fw.Reset(tw) + } + return &flateWriteWrapper{fw: fw, tw: tw, p: p} +} + +// truncWriter is an io.Writer that writes all but the last four bytes of the +// stream to another io.Writer. +type truncWriter struct { + w io.WriteCloser + n int + p [4]byte +} + +func (w *truncWriter) Write(p []byte) (int, error) { + n := 0 + + // fill buffer first for simplicity. + if w.n < len(w.p) { + n = copy(w.p[w.n:], p) + p = p[n:] + w.n += n + if len(p) == 0 { + return n, nil + } + } + + m := len(p) + if m > len(w.p) { + m = len(w.p) + } + + if nn, err := w.w.Write(w.p[:m]); err != nil { + return n + nn, err + } + + copy(w.p[:], w.p[m:]) + copy(w.p[len(w.p)-m:], p[len(p)-m:]) + nn, err := w.w.Write(p[:len(p)-m]) + return n + nn, err +} + +type flateWriteWrapper struct { + fw *flate.Writer + tw *truncWriter + p *sync.Pool +} + +func (w *flateWriteWrapper) Write(p []byte) (int, error) { + if w.fw == nil { + return 0, errWriteClosed + } + return w.fw.Write(p) +} + +func (w *flateWriteWrapper) Close() error { + if w.fw == nil { + return errWriteClosed + } + err1 := w.fw.Flush() + w.p.Put(w.fw) + w.fw = nil + if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { + return errors.New("websocket: internal error, unexpected bytes at end of flate stream") + } + err2 := w.tw.w.Close() + if err1 != nil { + return err1 + } + return err2 +} + +type flateReadWrapper struct { + fr io.ReadCloser +} + +func (r *flateReadWrapper) Read(p []byte) (int, error) { + if r.fr == nil { + return 0, io.ErrClosedPipe + } + n, err := r.fr.Read(p) + if err == io.EOF { + // Preemptively place the reader back in the pool. This helps with + // scenarios where the application does not call NextReader() soon after + // this final read. + r.Close() + } + return n, err +} + +func (r *flateReadWrapper) Close() error { + if r.fr == nil { + return io.ErrClosedPipe + } + err := r.fr.Close() + flateReaderPool.Put(r.fr) + r.fr = nil + return err +} diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go new file mode 100644 index 000000000..5161ef81f --- /dev/null +++ b/vendor/github.com/gorilla/websocket/conn.go @@ -0,0 +1,1238 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "encoding/binary" + "errors" + "io" + "io/ioutil" + "math/rand" + "net" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" +) + +const ( + // Frame header byte 0 bits from Section 5.2 of RFC 6455 + finalBit = 1 << 7 + rsv1Bit = 1 << 6 + rsv2Bit = 1 << 5 + rsv3Bit = 1 << 4 + + // Frame header byte 1 bits from Section 5.2 of RFC 6455 + maskBit = 1 << 7 + + maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask + maxControlFramePayloadSize = 125 + + writeWait = time.Second + + defaultReadBufferSize = 4096 + defaultWriteBufferSize = 4096 + + continuationFrame = 0 + noFrame = -1 +) + +// Close codes defined in RFC 6455, section 11.7. +const ( + CloseNormalClosure = 1000 + CloseGoingAway = 1001 + CloseProtocolError = 1002 + CloseUnsupportedData = 1003 + CloseNoStatusReceived = 1005 + CloseAbnormalClosure = 1006 + CloseInvalidFramePayloadData = 1007 + ClosePolicyViolation = 1008 + CloseMessageTooBig = 1009 + CloseMandatoryExtension = 1010 + CloseInternalServerErr = 1011 + CloseServiceRestart = 1012 + CloseTryAgainLater = 1013 + CloseTLSHandshake = 1015 +) + +// The message types are defined in RFC 6455, section 11.8. +const ( + // TextMessage denotes a text data message. The text message payload is + // interpreted as UTF-8 encoded text data. + TextMessage = 1 + + // BinaryMessage denotes a binary data message. + BinaryMessage = 2 + + // CloseMessage denotes a close control message. The optional message + // payload contains a numeric code and text. Use the FormatCloseMessage + // function to format a close message payload. + CloseMessage = 8 + + // PingMessage denotes a ping control message. The optional message payload + // is UTF-8 encoded text. + PingMessage = 9 + + // PongMessage denotes a pong control message. The optional message payload + // is UTF-8 encoded text. + PongMessage = 10 +) + +// ErrCloseSent is returned when the application writes a message to the +// connection after sending a close message. +var ErrCloseSent = errors.New("websocket: close sent") + +// ErrReadLimit is returned when reading a message that is larger than the +// read limit set for the connection. +var ErrReadLimit = errors.New("websocket: read limit exceeded") + +// netError satisfies the net Error interface. +type netError struct { + msg string + temporary bool + timeout bool +} + +func (e *netError) Error() string { return e.msg } +func (e *netError) Temporary() bool { return e.temporary } +func (e *netError) Timeout() bool { return e.timeout } + +// CloseError represents a close message. +type CloseError struct { + // Code is defined in RFC 6455, section 11.7. + Code int + + // Text is the optional text payload. + Text string +} + +func (e *CloseError) Error() string { + s := []byte("websocket: close ") + s = strconv.AppendInt(s, int64(e.Code), 10) + switch e.Code { + case CloseNormalClosure: + s = append(s, " (normal)"...) + case CloseGoingAway: + s = append(s, " (going away)"...) + case CloseProtocolError: + s = append(s, " (protocol error)"...) + case CloseUnsupportedData: + s = append(s, " (unsupported data)"...) + case CloseNoStatusReceived: + s = append(s, " (no status)"...) + case CloseAbnormalClosure: + s = append(s, " (abnormal closure)"...) + case CloseInvalidFramePayloadData: + s = append(s, " (invalid payload data)"...) + case ClosePolicyViolation: + s = append(s, " (policy violation)"...) + case CloseMessageTooBig: + s = append(s, " (message too big)"...) + case CloseMandatoryExtension: + s = append(s, " (mandatory extension missing)"...) + case CloseInternalServerErr: + s = append(s, " (internal server error)"...) + case CloseTLSHandshake: + s = append(s, " (TLS handshake error)"...) + } + if e.Text != "" { + s = append(s, ": "...) + s = append(s, e.Text...) + } + return string(s) +} + +// IsCloseError returns boolean indicating whether the error is a *CloseError +// with one of the specified codes. +func IsCloseError(err error, codes ...int) bool { + if e, ok := err.(*CloseError); ok { + for _, code := range codes { + if e.Code == code { + return true + } + } + } + return false +} + +// IsUnexpectedCloseError returns boolean indicating whether the error is a +// *CloseError with a code not in the list of expected codes. +func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { + if e, ok := err.(*CloseError); ok { + for _, code := range expectedCodes { + if e.Code == code { + return false + } + } + return true + } + return false +} + +var ( + errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} + errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} + errBadWriteOpCode = errors.New("websocket: bad write message type") + errWriteClosed = errors.New("websocket: write closed") + errInvalidControlFrame = errors.New("websocket: invalid control frame") +) + +func newMaskKey() [4]byte { + n := rand.Uint32() + return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} +} + +func hideTempErr(err error) error { + if e, ok := err.(net.Error); ok && e.Temporary() { + err = &netError{msg: e.Error(), timeout: e.Timeout()} + } + return err +} + +func isControl(frameType int) bool { + return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage +} + +func isData(frameType int) bool { + return frameType == TextMessage || frameType == BinaryMessage +} + +var validReceivedCloseCodes = map[int]bool{ + // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number + + CloseNormalClosure: true, + CloseGoingAway: true, + CloseProtocolError: true, + CloseUnsupportedData: true, + CloseNoStatusReceived: false, + CloseAbnormalClosure: false, + CloseInvalidFramePayloadData: true, + ClosePolicyViolation: true, + CloseMessageTooBig: true, + CloseMandatoryExtension: true, + CloseInternalServerErr: true, + CloseServiceRestart: true, + CloseTryAgainLater: true, + CloseTLSHandshake: false, +} + +func isValidReceivedCloseCode(code int) bool { + return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) +} + +// BufferPool represents a pool of buffers. The *sync.Pool type satisfies this +// interface. The type of the value stored in a pool is not specified. +type BufferPool interface { + // Get gets a value from the pool or returns nil if the pool is empty. + Get() interface{} + // Put adds a value to the pool. + Put(interface{}) +} + +// writePoolData is the type added to the write buffer pool. This wrapper is +// used to prevent applications from peeking at and depending on the values +// added to the pool. +type writePoolData struct{ buf []byte } + +// The Conn type represents a WebSocket connection. +type Conn struct { + conn net.Conn + isServer bool + subprotocol string + + // Write fields + mu chan struct{} // used as mutex to protect write to conn + writeBuf []byte // frame is constructed in this buffer. + writePool BufferPool + writeBufSize int + writeDeadline time.Time + writer io.WriteCloser // the current writer returned to the application + isWriting bool // for best-effort concurrent write detection + + writeErrMu sync.Mutex + writeErr error + + enableWriteCompression bool + compressionLevel int + newCompressionWriter func(io.WriteCloser, int) io.WriteCloser + + // Read fields + reader io.ReadCloser // the current reader returned to the application + readErr error + br *bufio.Reader + // bytes remaining in current frame. + // set setReadRemaining to safely update this value and prevent overflow + readRemaining int64 + readFinal bool // true the current message has more frames. + readLength int64 // Message size. + readLimit int64 // Maximum message size. + readMaskPos int + readMaskKey [4]byte + handlePong func(string) error + handlePing func(string) error + handleClose func(int, string) error + readErrCount int + messageReader *messageReader // the current low-level reader + + readDecompress bool // whether last read frame had RSV1 set + newDecompressionReader func(io.Reader) io.ReadCloser +} + +func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn { + + if br == nil { + if readBufferSize == 0 { + readBufferSize = defaultReadBufferSize + } else if readBufferSize < maxControlFramePayloadSize { + // must be large enough for control frame + readBufferSize = maxControlFramePayloadSize + } + br = bufio.NewReaderSize(conn, readBufferSize) + } + + if writeBufferSize <= 0 { + writeBufferSize = defaultWriteBufferSize + } + writeBufferSize += maxFrameHeaderSize + + if writeBuf == nil && writeBufferPool == nil { + writeBuf = make([]byte, writeBufferSize) + } + + mu := make(chan struct{}, 1) + mu <- struct{}{} + c := &Conn{ + isServer: isServer, + br: br, + conn: conn, + mu: mu, + readFinal: true, + writeBuf: writeBuf, + writePool: writeBufferPool, + writeBufSize: writeBufferSize, + enableWriteCompression: true, + compressionLevel: defaultCompressionLevel, + } + c.SetCloseHandler(nil) + c.SetPingHandler(nil) + c.SetPongHandler(nil) + return c +} + +// setReadRemaining tracks the number of bytes remaining on the connection. If n +// overflows, an ErrReadLimit is returned. +func (c *Conn) setReadRemaining(n int64) error { + if n < 0 { + return ErrReadLimit + } + + c.readRemaining = n + return nil +} + +// Subprotocol returns the negotiated protocol for the connection. +func (c *Conn) Subprotocol() string { + return c.subprotocol +} + +// Close closes the underlying network connection without sending or waiting +// for a close message. +func (c *Conn) Close() error { + return c.conn.Close() +} + +// LocalAddr returns the local network address. +func (c *Conn) LocalAddr() net.Addr { + return c.conn.LocalAddr() +} + +// RemoteAddr returns the remote network address. +func (c *Conn) RemoteAddr() net.Addr { + return c.conn.RemoteAddr() +} + +// Write methods + +func (c *Conn) writeFatal(err error) error { + err = hideTempErr(err) + c.writeErrMu.Lock() + if c.writeErr == nil { + c.writeErr = err + } + c.writeErrMu.Unlock() + return err +} + +func (c *Conn) read(n int) ([]byte, error) { + p, err := c.br.Peek(n) + if err == io.EOF { + err = errUnexpectedEOF + } + c.br.Discard(len(p)) + return p, err +} + +func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error { + <-c.mu + defer func() { c.mu <- struct{}{} }() + + c.writeErrMu.Lock() + err := c.writeErr + c.writeErrMu.Unlock() + if err != nil { + return err + } + + c.conn.SetWriteDeadline(deadline) + if len(buf1) == 0 { + _, err = c.conn.Write(buf0) + } else { + err = c.writeBufs(buf0, buf1) + } + if err != nil { + return c.writeFatal(err) + } + if frameType == CloseMessage { + c.writeFatal(ErrCloseSent) + } + return nil +} + +func (c *Conn) writeBufs(bufs ...[]byte) error { + b := net.Buffers(bufs) + _, err := b.WriteTo(c.conn) + return err +} + +// WriteControl writes a control message with the given deadline. The allowed +// message types are CloseMessage, PingMessage and PongMessage. +func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { + if !isControl(messageType) { + return errBadWriteOpCode + } + if len(data) > maxControlFramePayloadSize { + return errInvalidControlFrame + } + + b0 := byte(messageType) | finalBit + b1 := byte(len(data)) + if !c.isServer { + b1 |= maskBit + } + + buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) + buf = append(buf, b0, b1) + + if c.isServer { + buf = append(buf, data...) + } else { + key := newMaskKey() + buf = append(buf, key[:]...) + buf = append(buf, data...) + maskBytes(key, 0, buf[6:]) + } + + d := 1000 * time.Hour + if !deadline.IsZero() { + d = deadline.Sub(time.Now()) + if d < 0 { + return errWriteTimeout + } + } + + timer := time.NewTimer(d) + select { + case <-c.mu: + timer.Stop() + case <-timer.C: + return errWriteTimeout + } + defer func() { c.mu <- struct{}{} }() + + c.writeErrMu.Lock() + err := c.writeErr + c.writeErrMu.Unlock() + if err != nil { + return err + } + + c.conn.SetWriteDeadline(deadline) + _, err = c.conn.Write(buf) + if err != nil { + return c.writeFatal(err) + } + if messageType == CloseMessage { + c.writeFatal(ErrCloseSent) + } + return err +} + +// beginMessage prepares a connection and message writer for a new message. +func (c *Conn) beginMessage(mw *messageWriter, messageType int) error { + // Close previous writer if not already closed by the application. It's + // probably better to return an error in this situation, but we cannot + // change this without breaking existing applications. + if c.writer != nil { + c.writer.Close() + c.writer = nil + } + + if !isControl(messageType) && !isData(messageType) { + return errBadWriteOpCode + } + + c.writeErrMu.Lock() + err := c.writeErr + c.writeErrMu.Unlock() + if err != nil { + return err + } + + mw.c = c + mw.frameType = messageType + mw.pos = maxFrameHeaderSize + + if c.writeBuf == nil { + wpd, ok := c.writePool.Get().(writePoolData) + if ok { + c.writeBuf = wpd.buf + } else { + c.writeBuf = make([]byte, c.writeBufSize) + } + } + return nil +} + +// NextWriter returns a writer for the next message to send. The writer's Close +// method flushes the complete message to the network. +// +// There can be at most one open writer on a connection. NextWriter closes the +// previous writer if the application has not already done so. +// +// All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and +// PongMessage) are supported. +func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { + var mw messageWriter + if err := c.beginMessage(&mw, messageType); err != nil { + return nil, err + } + c.writer = &mw + if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { + w := c.newCompressionWriter(c.writer, c.compressionLevel) + mw.compress = true + c.writer = w + } + return c.writer, nil +} + +type messageWriter struct { + c *Conn + compress bool // whether next call to flushFrame should set RSV1 + pos int // end of data in writeBuf. + frameType int // type of the current frame. + err error +} + +func (w *messageWriter) endMessage(err error) error { + if w.err != nil { + return err + } + c := w.c + w.err = err + c.writer = nil + if c.writePool != nil { + c.writePool.Put(writePoolData{buf: c.writeBuf}) + c.writeBuf = nil + } + return err +} + +// flushFrame writes buffered data and extra as a frame to the network. The +// final argument indicates that this is the last frame in the message. +func (w *messageWriter) flushFrame(final bool, extra []byte) error { + c := w.c + length := w.pos - maxFrameHeaderSize + len(extra) + + // Check for invalid control frames. + if isControl(w.frameType) && + (!final || length > maxControlFramePayloadSize) { + return w.endMessage(errInvalidControlFrame) + } + + b0 := byte(w.frameType) + if final { + b0 |= finalBit + } + if w.compress { + b0 |= rsv1Bit + } + w.compress = false + + b1 := byte(0) + if !c.isServer { + b1 |= maskBit + } + + // Assume that the frame starts at beginning of c.writeBuf. + framePos := 0 + if c.isServer { + // Adjust up if mask not included in the header. + framePos = 4 + } + + switch { + case length >= 65536: + c.writeBuf[framePos] = b0 + c.writeBuf[framePos+1] = b1 | 127 + binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) + case length > 125: + framePos += 6 + c.writeBuf[framePos] = b0 + c.writeBuf[framePos+1] = b1 | 126 + binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) + default: + framePos += 8 + c.writeBuf[framePos] = b0 + c.writeBuf[framePos+1] = b1 | byte(length) + } + + if !c.isServer { + key := newMaskKey() + copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) + maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) + if len(extra) > 0 { + return w.endMessage(c.writeFatal(errors.New("websocket: internal error, extra used in client mode"))) + } + } + + // Write the buffers to the connection with best-effort detection of + // concurrent writes. See the concurrency section in the package + // documentation for more info. + + if c.isWriting { + panic("concurrent write to websocket connection") + } + c.isWriting = true + + err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) + + if !c.isWriting { + panic("concurrent write to websocket connection") + } + c.isWriting = false + + if err != nil { + return w.endMessage(err) + } + + if final { + w.endMessage(errWriteClosed) + return nil + } + + // Setup for next frame. + w.pos = maxFrameHeaderSize + w.frameType = continuationFrame + return nil +} + +func (w *messageWriter) ncopy(max int) (int, error) { + n := len(w.c.writeBuf) - w.pos + if n <= 0 { + if err := w.flushFrame(false, nil); err != nil { + return 0, err + } + n = len(w.c.writeBuf) - w.pos + } + if n > max { + n = max + } + return n, nil +} + +func (w *messageWriter) Write(p []byte) (int, error) { + if w.err != nil { + return 0, w.err + } + + if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { + // Don't buffer large messages. + err := w.flushFrame(false, p) + if err != nil { + return 0, err + } + return len(p), nil + } + + nn := len(p) + for len(p) > 0 { + n, err := w.ncopy(len(p)) + if err != nil { + return 0, err + } + copy(w.c.writeBuf[w.pos:], p[:n]) + w.pos += n + p = p[n:] + } + return nn, nil +} + +func (w *messageWriter) WriteString(p string) (int, error) { + if w.err != nil { + return 0, w.err + } + + nn := len(p) + for len(p) > 0 { + n, err := w.ncopy(len(p)) + if err != nil { + return 0, err + } + copy(w.c.writeBuf[w.pos:], p[:n]) + w.pos += n + p = p[n:] + } + return nn, nil +} + +func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { + if w.err != nil { + return 0, w.err + } + for { + if w.pos == len(w.c.writeBuf) { + err = w.flushFrame(false, nil) + if err != nil { + break + } + } + var n int + n, err = r.Read(w.c.writeBuf[w.pos:]) + w.pos += n + nn += int64(n) + if err != nil { + if err == io.EOF { + err = nil + } + break + } + } + return nn, err +} + +func (w *messageWriter) Close() error { + if w.err != nil { + return w.err + } + return w.flushFrame(true, nil) +} + +// WritePreparedMessage writes prepared message into connection. +func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { + frameType, frameData, err := pm.frame(prepareKey{ + isServer: c.isServer, + compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), + compressionLevel: c.compressionLevel, + }) + if err != nil { + return err + } + if c.isWriting { + panic("concurrent write to websocket connection") + } + c.isWriting = true + err = c.write(frameType, c.writeDeadline, frameData, nil) + if !c.isWriting { + panic("concurrent write to websocket connection") + } + c.isWriting = false + return err +} + +// WriteMessage is a helper method for getting a writer using NextWriter, +// writing the message and closing the writer. +func (c *Conn) WriteMessage(messageType int, data []byte) error { + + if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { + // Fast path with no allocations and single frame. + + var mw messageWriter + if err := c.beginMessage(&mw, messageType); err != nil { + return err + } + n := copy(c.writeBuf[mw.pos:], data) + mw.pos += n + data = data[n:] + return mw.flushFrame(true, data) + } + + w, err := c.NextWriter(messageType) + if err != nil { + return err + } + if _, err = w.Write(data); err != nil { + return err + } + return w.Close() +} + +// SetWriteDeadline sets the write deadline on the underlying network +// connection. After a write has timed out, the websocket state is corrupt and +// all future writes will return an error. A zero value for t means writes will +// not time out. +func (c *Conn) SetWriteDeadline(t time.Time) error { + c.writeDeadline = t + return nil +} + +// Read methods + +func (c *Conn) advanceFrame() (int, error) { + // 1. Skip remainder of previous frame. + + if c.readRemaining > 0 { + if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { + return noFrame, err + } + } + + // 2. Read and parse first two bytes of frame header. + // To aid debugging, collect and report all errors in the first two bytes + // of the header. + + var errors []string + + p, err := c.read(2) + if err != nil { + return noFrame, err + } + + frameType := int(p[0] & 0xf) + final := p[0]&finalBit != 0 + rsv1 := p[0]&rsv1Bit != 0 + rsv2 := p[0]&rsv2Bit != 0 + rsv3 := p[0]&rsv3Bit != 0 + mask := p[1]&maskBit != 0 + c.setReadRemaining(int64(p[1] & 0x7f)) + + c.readDecompress = false + if rsv1 { + if c.newDecompressionReader != nil { + c.readDecompress = true + } else { + errors = append(errors, "RSV1 set") + } + } + + if rsv2 { + errors = append(errors, "RSV2 set") + } + + if rsv3 { + errors = append(errors, "RSV3 set") + } + + switch frameType { + case CloseMessage, PingMessage, PongMessage: + if c.readRemaining > maxControlFramePayloadSize { + errors = append(errors, "len > 125 for control") + } + if !final { + errors = append(errors, "FIN not set on control") + } + case TextMessage, BinaryMessage: + if !c.readFinal { + errors = append(errors, "data before FIN") + } + c.readFinal = final + case continuationFrame: + if c.readFinal { + errors = append(errors, "continuation after FIN") + } + c.readFinal = final + default: + errors = append(errors, "bad opcode "+strconv.Itoa(frameType)) + } + + if mask != c.isServer { + errors = append(errors, "bad MASK") + } + + if len(errors) > 0 { + return noFrame, c.handleProtocolError(strings.Join(errors, ", ")) + } + + // 3. Read and parse frame length as per + // https://tools.ietf.org/html/rfc6455#section-5.2 + // + // The length of the "Payload data", in bytes: if 0-125, that is the payload + // length. + // - If 126, the following 2 bytes interpreted as a 16-bit unsigned + // integer are the payload length. + // - If 127, the following 8 bytes interpreted as + // a 64-bit unsigned integer (the most significant bit MUST be 0) are the + // payload length. Multibyte length quantities are expressed in network byte + // order. + + switch c.readRemaining { + case 126: + p, err := c.read(2) + if err != nil { + return noFrame, err + } + + if err := c.setReadRemaining(int64(binary.BigEndian.Uint16(p))); err != nil { + return noFrame, err + } + case 127: + p, err := c.read(8) + if err != nil { + return noFrame, err + } + + if err := c.setReadRemaining(int64(binary.BigEndian.Uint64(p))); err != nil { + return noFrame, err + } + } + + // 4. Handle frame masking. + + if mask { + c.readMaskPos = 0 + p, err := c.read(len(c.readMaskKey)) + if err != nil { + return noFrame, err + } + copy(c.readMaskKey[:], p) + } + + // 5. For text and binary messages, enforce read limit and return. + + if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { + + c.readLength += c.readRemaining + // Don't allow readLength to overflow in the presence of a large readRemaining + // counter. + if c.readLength < 0 { + return noFrame, ErrReadLimit + } + + if c.readLimit > 0 && c.readLength > c.readLimit { + c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) + return noFrame, ErrReadLimit + } + + return frameType, nil + } + + // 6. Read control frame payload. + + var payload []byte + if c.readRemaining > 0 { + payload, err = c.read(int(c.readRemaining)) + c.setReadRemaining(0) + if err != nil { + return noFrame, err + } + if c.isServer { + maskBytes(c.readMaskKey, 0, payload) + } + } + + // 7. Process control frame payload. + + switch frameType { + case PongMessage: + if err := c.handlePong(string(payload)); err != nil { + return noFrame, err + } + case PingMessage: + if err := c.handlePing(string(payload)); err != nil { + return noFrame, err + } + case CloseMessage: + closeCode := CloseNoStatusReceived + closeText := "" + if len(payload) >= 2 { + closeCode = int(binary.BigEndian.Uint16(payload)) + if !isValidReceivedCloseCode(closeCode) { + return noFrame, c.handleProtocolError("bad close code " + strconv.Itoa(closeCode)) + } + closeText = string(payload[2:]) + if !utf8.ValidString(closeText) { + return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") + } + } + if err := c.handleClose(closeCode, closeText); err != nil { + return noFrame, err + } + return noFrame, &CloseError{Code: closeCode, Text: closeText} + } + + return frameType, nil +} + +func (c *Conn) handleProtocolError(message string) error { + data := FormatCloseMessage(CloseProtocolError, message) + if len(data) > maxControlFramePayloadSize { + data = data[:maxControlFramePayloadSize] + } + c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)) + return errors.New("websocket: " + message) +} + +// NextReader returns the next data message received from the peer. The +// returned messageType is either TextMessage or BinaryMessage. +// +// There can be at most one open reader on a connection. NextReader discards +// the previous message if the application has not already consumed it. +// +// Applications must break out of the application's read loop when this method +// returns a non-nil error value. Errors returned from this method are +// permanent. Once this method returns a non-nil error, all subsequent calls to +// this method return the same error. +func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { + // Close previous reader, only relevant for decompression. + if c.reader != nil { + c.reader.Close() + c.reader = nil + } + + c.messageReader = nil + c.readLength = 0 + + for c.readErr == nil { + frameType, err := c.advanceFrame() + if err != nil { + c.readErr = hideTempErr(err) + break + } + + if frameType == TextMessage || frameType == BinaryMessage { + c.messageReader = &messageReader{c} + c.reader = c.messageReader + if c.readDecompress { + c.reader = c.newDecompressionReader(c.reader) + } + return frameType, c.reader, nil + } + } + + // Applications that do handle the error returned from this method spin in + // tight loop on connection failure. To help application developers detect + // this error, panic on repeated reads to the failed connection. + c.readErrCount++ + if c.readErrCount >= 1000 { + panic("repeated read on failed websocket connection") + } + + return noFrame, nil, c.readErr +} + +type messageReader struct{ c *Conn } + +func (r *messageReader) Read(b []byte) (int, error) { + c := r.c + if c.messageReader != r { + return 0, io.EOF + } + + for c.readErr == nil { + + if c.readRemaining > 0 { + if int64(len(b)) > c.readRemaining { + b = b[:c.readRemaining] + } + n, err := c.br.Read(b) + c.readErr = hideTempErr(err) + if c.isServer { + c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) + } + rem := c.readRemaining + rem -= int64(n) + c.setReadRemaining(rem) + if c.readRemaining > 0 && c.readErr == io.EOF { + c.readErr = errUnexpectedEOF + } + return n, c.readErr + } + + if c.readFinal { + c.messageReader = nil + return 0, io.EOF + } + + frameType, err := c.advanceFrame() + switch { + case err != nil: + c.readErr = hideTempErr(err) + case frameType == TextMessage || frameType == BinaryMessage: + c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") + } + } + + err := c.readErr + if err == io.EOF && c.messageReader == r { + err = errUnexpectedEOF + } + return 0, err +} + +func (r *messageReader) Close() error { + return nil +} + +// ReadMessage is a helper method for getting a reader using NextReader and +// reading from that reader to a buffer. +func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { + var r io.Reader + messageType, r, err = c.NextReader() + if err != nil { + return messageType, nil, err + } + p, err = ioutil.ReadAll(r) + return messageType, p, err +} + +// SetReadDeadline sets the read deadline on the underlying network connection. +// After a read has timed out, the websocket connection state is corrupt and +// all future reads will return an error. A zero value for t means reads will +// not time out. +func (c *Conn) SetReadDeadline(t time.Time) error { + return c.conn.SetReadDeadline(t) +} + +// SetReadLimit sets the maximum size in bytes for a message read from the peer. If a +// message exceeds the limit, the connection sends a close message to the peer +// and returns ErrReadLimit to the application. +func (c *Conn) SetReadLimit(limit int64) { + c.readLimit = limit +} + +// CloseHandler returns the current close handler +func (c *Conn) CloseHandler() func(code int, text string) error { + return c.handleClose +} + +// SetCloseHandler sets the handler for close messages received from the peer. +// The code argument to h is the received close code or CloseNoStatusReceived +// if the close message is empty. The default close handler sends a close +// message back to the peer. +// +// The handler function is called from the NextReader, ReadMessage and message +// reader Read methods. The application must read the connection to process +// close messages as described in the section on Control Messages above. +// +// The connection read methods return a CloseError when a close message is +// received. Most applications should handle close messages as part of their +// normal error handling. Applications should only set a close handler when the +// application must perform some action before sending a close message back to +// the peer. +func (c *Conn) SetCloseHandler(h func(code int, text string) error) { + if h == nil { + h = func(code int, text string) error { + message := FormatCloseMessage(code, "") + c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) + return nil + } + } + c.handleClose = h +} + +// PingHandler returns the current ping handler +func (c *Conn) PingHandler() func(appData string) error { + return c.handlePing +} + +// SetPingHandler sets the handler for ping messages received from the peer. +// The appData argument to h is the PING message application data. The default +// ping handler sends a pong to the peer. +// +// The handler function is called from the NextReader, ReadMessage and message +// reader Read methods. The application must read the connection to process +// ping messages as described in the section on Control Messages above. +func (c *Conn) SetPingHandler(h func(appData string) error) { + if h == nil { + h = func(message string) error { + err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) + if err == ErrCloseSent { + return nil + } else if e, ok := err.(net.Error); ok && e.Temporary() { + return nil + } + return err + } + } + c.handlePing = h +} + +// PongHandler returns the current pong handler +func (c *Conn) PongHandler() func(appData string) error { + return c.handlePong +} + +// SetPongHandler sets the handler for pong messages received from the peer. +// The appData argument to h is the PONG message application data. The default +// pong handler does nothing. +// +// The handler function is called from the NextReader, ReadMessage and message +// reader Read methods. The application must read the connection to process +// pong messages as described in the section on Control Messages above. +func (c *Conn) SetPongHandler(h func(appData string) error) { + if h == nil { + h = func(string) error { return nil } + } + c.handlePong = h +} + +// NetConn returns the underlying connection that is wrapped by c. +// Note that writing to or reading from this connection directly will corrupt the +// WebSocket connection. +func (c *Conn) NetConn() net.Conn { + return c.conn +} + +// UnderlyingConn returns the internal net.Conn. This can be used to further +// modifications to connection specific flags. +// Deprecated: Use the NetConn method. +func (c *Conn) UnderlyingConn() net.Conn { + return c.conn +} + +// EnableWriteCompression enables and disables write compression of +// subsequent text and binary messages. This function is a noop if +// compression was not negotiated with the peer. +func (c *Conn) EnableWriteCompression(enable bool) { + c.enableWriteCompression = enable +} + +// SetCompressionLevel sets the flate compression level for subsequent text and +// binary messages. This function is a noop if compression was not negotiated +// with the peer. See the compress/flate package for a description of +// compression levels. +func (c *Conn) SetCompressionLevel(level int) error { + if !isValidCompressionLevel(level) { + return errors.New("websocket: invalid compression level") + } + c.compressionLevel = level + return nil +} + +// FormatCloseMessage formats closeCode and text as a WebSocket close message. +// An empty message is returned for code CloseNoStatusReceived. +func FormatCloseMessage(closeCode int, text string) []byte { + if closeCode == CloseNoStatusReceived { + // Return empty message because it's illegal to send + // CloseNoStatusReceived. Return non-nil value in case application + // checks for nil. + return []byte{} + } + buf := make([]byte, 2+len(text)) + binary.BigEndian.PutUint16(buf, uint16(closeCode)) + copy(buf[2:], text) + return buf +} diff --git a/vendor/github.com/gorilla/websocket/doc.go b/vendor/github.com/gorilla/websocket/doc.go new file mode 100644 index 000000000..8db0cef95 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/doc.go @@ -0,0 +1,227 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package websocket implements the WebSocket protocol defined in RFC 6455. +// +// Overview +// +// The Conn type represents a WebSocket connection. A server application calls +// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn: +// +// var upgrader = websocket.Upgrader{ +// ReadBufferSize: 1024, +// WriteBufferSize: 1024, +// } +// +// func handler(w http.ResponseWriter, r *http.Request) { +// conn, err := upgrader.Upgrade(w, r, nil) +// if err != nil { +// log.Println(err) +// return +// } +// ... Use conn to send and receive messages. +// } +// +// Call the connection's WriteMessage and ReadMessage methods to send and +// receive messages as a slice of bytes. This snippet of code shows how to echo +// messages using these methods: +// +// for { +// messageType, p, err := conn.ReadMessage() +// if err != nil { +// log.Println(err) +// return +// } +// if err := conn.WriteMessage(messageType, p); err != nil { +// log.Println(err) +// return +// } +// } +// +// In above snippet of code, p is a []byte and messageType is an int with value +// websocket.BinaryMessage or websocket.TextMessage. +// +// An application can also send and receive messages using the io.WriteCloser +// and io.Reader interfaces. To send a message, call the connection NextWriter +// method to get an io.WriteCloser, write the message to the writer and close +// the writer when done. To receive a message, call the connection NextReader +// method to get an io.Reader and read until io.EOF is returned. This snippet +// shows how to echo messages using the NextWriter and NextReader methods: +// +// for { +// messageType, r, err := conn.NextReader() +// if err != nil { +// return +// } +// w, err := conn.NextWriter(messageType) +// if err != nil { +// return err +// } +// if _, err := io.Copy(w, r); err != nil { +// return err +// } +// if err := w.Close(); err != nil { +// return err +// } +// } +// +// Data Messages +// +// The WebSocket protocol distinguishes between text and binary data messages. +// Text messages are interpreted as UTF-8 encoded text. The interpretation of +// binary messages is left to the application. +// +// This package uses the TextMessage and BinaryMessage integer constants to +// identify the two data message types. The ReadMessage and NextReader methods +// return the type of the received message. The messageType argument to the +// WriteMessage and NextWriter methods specifies the type of a sent message. +// +// It is the application's responsibility to ensure that text messages are +// valid UTF-8 encoded text. +// +// Control Messages +// +// The WebSocket protocol defines three types of control messages: close, ping +// and pong. Call the connection WriteControl, WriteMessage or NextWriter +// methods to send a control message to the peer. +// +// Connections handle received close messages by calling the handler function +// set with the SetCloseHandler method and by returning a *CloseError from the +// NextReader, ReadMessage or the message Read method. The default close +// handler sends a close message to the peer. +// +// Connections handle received ping messages by calling the handler function +// set with the SetPingHandler method. The default ping handler sends a pong +// message to the peer. +// +// Connections handle received pong messages by calling the handler function +// set with the SetPongHandler method. The default pong handler does nothing. +// If an application sends ping messages, then the application should set a +// pong handler to receive the corresponding pong. +// +// The control message handler functions are called from the NextReader, +// ReadMessage and message reader Read methods. The default close and ping +// handlers can block these methods for a short time when the handler writes to +// the connection. +// +// The application must read the connection to process close, ping and pong +// messages sent from the peer. If the application is not otherwise interested +// in messages from the peer, then the application should start a goroutine to +// read and discard messages from the peer. A simple example is: +// +// func readLoop(c *websocket.Conn) { +// for { +// if _, _, err := c.NextReader(); err != nil { +// c.Close() +// break +// } +// } +// } +// +// Concurrency +// +// Connections support one concurrent reader and one concurrent writer. +// +// Applications are responsible for ensuring that no more than one goroutine +// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, +// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and +// that no more than one goroutine calls the read methods (NextReader, +// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) +// concurrently. +// +// The Close and WriteControl methods can be called concurrently with all other +// methods. +// +// Origin Considerations +// +// Web browsers allow Javascript applications to open a WebSocket connection to +// any host. It's up to the server to enforce an origin policy using the Origin +// request header sent by the browser. +// +// The Upgrader calls the function specified in the CheckOrigin field to check +// the origin. If the CheckOrigin function returns false, then the Upgrade +// method fails the WebSocket handshake with HTTP status 403. +// +// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail +// the handshake if the Origin request header is present and the Origin host is +// not equal to the Host request header. +// +// The deprecated package-level Upgrade function does not perform origin +// checking. The application is responsible for checking the Origin header +// before calling the Upgrade function. +// +// Buffers +// +// Connections buffer network input and output to reduce the number +// of system calls when reading or writing messages. +// +// Write buffers are also used for constructing WebSocket frames. See RFC 6455, +// Section 5 for a discussion of message framing. A WebSocket frame header is +// written to the network each time a write buffer is flushed to the network. +// Decreasing the size of the write buffer can increase the amount of framing +// overhead on the connection. +// +// The buffer sizes in bytes are specified by the ReadBufferSize and +// WriteBufferSize fields in the Dialer and Upgrader. The Dialer uses a default +// size of 4096 when a buffer size field is set to zero. The Upgrader reuses +// buffers created by the HTTP server when a buffer size field is set to zero. +// The HTTP server buffers have a size of 4096 at the time of this writing. +// +// The buffer sizes do not limit the size of a message that can be read or +// written by a connection. +// +// Buffers are held for the lifetime of the connection by default. If the +// Dialer or Upgrader WriteBufferPool field is set, then a connection holds the +// write buffer only when writing a message. +// +// Applications should tune the buffer sizes to balance memory use and +// performance. Increasing the buffer size uses more memory, but can reduce the +// number of system calls to read or write the network. In the case of writing, +// increasing the buffer size can reduce the number of frame headers written to +// the network. +// +// Some guidelines for setting buffer parameters are: +// +// Limit the buffer sizes to the maximum expected message size. Buffers larger +// than the largest message do not provide any benefit. +// +// Depending on the distribution of message sizes, setting the buffer size to +// a value less than the maximum expected message size can greatly reduce memory +// use with a small impact on performance. Here's an example: If 99% of the +// messages are smaller than 256 bytes and the maximum message size is 512 +// bytes, then a buffer size of 256 bytes will result in 1.01 more system calls +// than a buffer size of 512 bytes. The memory savings is 50%. +// +// A write buffer pool is useful when the application has a modest number +// writes over a large number of connections. when buffers are pooled, a larger +// buffer size has a reduced impact on total memory use and has the benefit of +// reducing system calls and frame overhead. +// +// Compression EXPERIMENTAL +// +// Per message compression extensions (RFC 7692) are experimentally supported +// by this package in a limited capacity. Setting the EnableCompression option +// to true in Dialer or Upgrader will attempt to negotiate per message deflate +// support. +// +// var upgrader = websocket.Upgrader{ +// EnableCompression: true, +// } +// +// If compression was successfully negotiated with the connection's peer, any +// message received in compressed form will be automatically decompressed. +// All Read methods will return uncompressed bytes. +// +// Per message compression of messages written to a connection can be enabled +// or disabled by calling the corresponding Conn method: +// +// conn.EnableWriteCompression(false) +// +// Currently this package does not support compression with "context takeover". +// This means that messages must be compressed and decompressed in isolation, +// without retaining sliding window or dictionary state across messages. For +// more details refer to RFC 7692. +// +// Use of compression is experimental and may result in decreased performance. +package websocket diff --git a/vendor/github.com/gorilla/websocket/join.go b/vendor/github.com/gorilla/websocket/join.go new file mode 100644 index 000000000..c64f8c829 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/join.go @@ -0,0 +1,42 @@ +// Copyright 2019 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "io" + "strings" +) + +// JoinMessages concatenates received messages to create a single io.Reader. +// The string term is appended to each message. The returned reader does not +// support concurrent calls to the Read method. +func JoinMessages(c *Conn, term string) io.Reader { + return &joinReader{c: c, term: term} +} + +type joinReader struct { + c *Conn + term string + r io.Reader +} + +func (r *joinReader) Read(p []byte) (int, error) { + if r.r == nil { + var err error + _, r.r, err = r.c.NextReader() + if err != nil { + return 0, err + } + if r.term != "" { + r.r = io.MultiReader(r.r, strings.NewReader(r.term)) + } + } + n, err := r.r.Read(p) + if err == io.EOF { + err = nil + r.r = nil + } + return n, err +} diff --git a/vendor/github.com/gorilla/websocket/json.go b/vendor/github.com/gorilla/websocket/json.go new file mode 100644 index 000000000..dc2c1f641 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/json.go @@ -0,0 +1,60 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "encoding/json" + "io" +) + +// WriteJSON writes the JSON encoding of v as a message. +// +// Deprecated: Use c.WriteJSON instead. +func WriteJSON(c *Conn, v interface{}) error { + return c.WriteJSON(v) +} + +// WriteJSON writes the JSON encoding of v as a message. +// +// See the documentation for encoding/json Marshal for details about the +// conversion of Go values to JSON. +func (c *Conn) WriteJSON(v interface{}) error { + w, err := c.NextWriter(TextMessage) + if err != nil { + return err + } + err1 := json.NewEncoder(w).Encode(v) + err2 := w.Close() + if err1 != nil { + return err1 + } + return err2 +} + +// ReadJSON reads the next JSON-encoded message from the connection and stores +// it in the value pointed to by v. +// +// Deprecated: Use c.ReadJSON instead. +func ReadJSON(c *Conn, v interface{}) error { + return c.ReadJSON(v) +} + +// ReadJSON reads the next JSON-encoded message from the connection and stores +// it in the value pointed to by v. +// +// See the documentation for the encoding/json Unmarshal function for details +// about the conversion of JSON to a Go value. +func (c *Conn) ReadJSON(v interface{}) error { + _, r, err := c.NextReader() + if err != nil { + return err + } + err = json.NewDecoder(r).Decode(v) + if err == io.EOF { + // One value is expected in the message. + err = io.ErrUnexpectedEOF + } + return err +} diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go new file mode 100644 index 000000000..d0742bf2a --- /dev/null +++ b/vendor/github.com/gorilla/websocket/mask.go @@ -0,0 +1,55 @@ +// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of +// this source code is governed by a BSD-style license that can be found in the +// LICENSE file. + +//go:build !appengine +// +build !appengine + +package websocket + +import "unsafe" + +const wordSize = int(unsafe.Sizeof(uintptr(0))) + +func maskBytes(key [4]byte, pos int, b []byte) int { + // Mask one byte at a time for small buffers. + if len(b) < 2*wordSize { + for i := range b { + b[i] ^= key[pos&3] + pos++ + } + return pos & 3 + } + + // Mask one byte at a time to word boundary. + if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { + n = wordSize - n + for i := range b[:n] { + b[i] ^= key[pos&3] + pos++ + } + b = b[n:] + } + + // Create aligned word size key. + var k [wordSize]byte + for i := range k { + k[i] = key[(pos+i)&3] + } + kw := *(*uintptr)(unsafe.Pointer(&k)) + + // Mask one word at a time. + n := (len(b) / wordSize) * wordSize + for i := 0; i < n; i += wordSize { + *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw + } + + // Mask one byte at a time for remaining bytes. + b = b[n:] + for i := range b { + b[i] ^= key[pos&3] + pos++ + } + + return pos & 3 +} diff --git a/vendor/github.com/gorilla/websocket/mask_safe.go b/vendor/github.com/gorilla/websocket/mask_safe.go new file mode 100644 index 000000000..36250ca7c --- /dev/null +++ b/vendor/github.com/gorilla/websocket/mask_safe.go @@ -0,0 +1,16 @@ +// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of +// this source code is governed by a BSD-style license that can be found in the +// LICENSE file. + +//go:build appengine +// +build appengine + +package websocket + +func maskBytes(key [4]byte, pos int, b []byte) int { + for i := range b { + b[i] ^= key[pos&3] + pos++ + } + return pos & 3 +} diff --git a/vendor/github.com/gorilla/websocket/prepared.go b/vendor/github.com/gorilla/websocket/prepared.go new file mode 100644 index 000000000..c854225e9 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/prepared.go @@ -0,0 +1,102 @@ +// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bytes" + "net" + "sync" + "time" +) + +// PreparedMessage caches on the wire representations of a message payload. +// Use PreparedMessage to efficiently send a message payload to multiple +// connections. PreparedMessage is especially useful when compression is used +// because the CPU and memory expensive compression operation can be executed +// once for a given set of compression options. +type PreparedMessage struct { + messageType int + data []byte + mu sync.Mutex + frames map[prepareKey]*preparedFrame +} + +// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. +type prepareKey struct { + isServer bool + compress bool + compressionLevel int +} + +// preparedFrame contains data in wire representation. +type preparedFrame struct { + once sync.Once + data []byte +} + +// NewPreparedMessage returns an initialized PreparedMessage. You can then send +// it to connection using WritePreparedMessage method. Valid wire +// representation will be calculated lazily only once for a set of current +// connection options. +func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { + pm := &PreparedMessage{ + messageType: messageType, + frames: make(map[prepareKey]*preparedFrame), + data: data, + } + + // Prepare a plain server frame. + _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) + if err != nil { + return nil, err + } + + // To protect against caller modifying the data argument, remember the data + // copied to the plain server frame. + pm.data = frameData[len(frameData)-len(data):] + return pm, nil +} + +func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { + pm.mu.Lock() + frame, ok := pm.frames[key] + if !ok { + frame = &preparedFrame{} + pm.frames[key] = frame + } + pm.mu.Unlock() + + var err error + frame.once.Do(func() { + // Prepare a frame using a 'fake' connection. + // TODO: Refactor code in conn.go to allow more direct construction of + // the frame. + mu := make(chan struct{}, 1) + mu <- struct{}{} + var nc prepareConn + c := &Conn{ + conn: &nc, + mu: mu, + isServer: key.isServer, + compressionLevel: key.compressionLevel, + enableWriteCompression: true, + writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), + } + if key.compress { + c.newCompressionWriter = compressNoContextTakeover + } + err = c.WriteMessage(pm.messageType, pm.data) + frame.data = nc.buf.Bytes() + }) + return pm.messageType, frame.data, err +} + +type prepareConn struct { + buf bytes.Buffer + net.Conn +} + +func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } +func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/vendor/github.com/gorilla/websocket/proxy.go b/vendor/github.com/gorilla/websocket/proxy.go new file mode 100644 index 000000000..e0f466b72 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/proxy.go @@ -0,0 +1,77 @@ +// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "encoding/base64" + "errors" + "net" + "net/http" + "net/url" + "strings" +) + +type netDialerFunc func(network, addr string) (net.Conn, error) + +func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { + return fn(network, addr) +} + +func init() { + proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { + return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil + }) +} + +type httpProxyDialer struct { + proxyURL *url.URL + forwardDial func(network, addr string) (net.Conn, error) +} + +func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { + hostPort, _ := hostPortNoPort(hpd.proxyURL) + conn, err := hpd.forwardDial(network, hostPort) + if err != nil { + return nil, err + } + + connectHeader := make(http.Header) + if user := hpd.proxyURL.User; user != nil { + proxyUser := user.Username() + if proxyPassword, passwordSet := user.Password(); passwordSet { + credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) + connectHeader.Set("Proxy-Authorization", "Basic "+credential) + } + } + + connectReq := &http.Request{ + Method: http.MethodConnect, + URL: &url.URL{Opaque: addr}, + Host: addr, + Header: connectHeader, + } + + if err := connectReq.Write(conn); err != nil { + conn.Close() + return nil, err + } + + // Read response. It's OK to use and discard buffered reader here becaue + // the remote server does not speak until spoken to. + br := bufio.NewReader(conn) + resp, err := http.ReadResponse(br, connectReq) + if err != nil { + conn.Close() + return nil, err + } + + if resp.StatusCode != 200 { + conn.Close() + f := strings.SplitN(resp.Status, " ", 2) + return nil, errors.New(f[1]) + } + return conn, nil +} diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go new file mode 100644 index 000000000..bb3359743 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/server.go @@ -0,0 +1,365 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "errors" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +// HandshakeError describes an error with the handshake from the peer. +type HandshakeError struct { + message string +} + +func (e HandshakeError) Error() string { return e.message } + +// Upgrader specifies parameters for upgrading an HTTP connection to a +// WebSocket connection. +// +// It is safe to call Upgrader's methods concurrently. +type Upgrader struct { + // HandshakeTimeout specifies the duration for the handshake to complete. + HandshakeTimeout time.Duration + + // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer + // size is zero, then buffers allocated by the HTTP server are used. The + // I/O buffer sizes do not limit the size of the messages that can be sent + // or received. + ReadBufferSize, WriteBufferSize int + + // WriteBufferPool is a pool of buffers for write operations. If the value + // is not set, then write buffers are allocated to the connection for the + // lifetime of the connection. + // + // A pool is most useful when the application has a modest volume of writes + // across a large number of connections. + // + // Applications should use a single pool for each unique value of + // WriteBufferSize. + WriteBufferPool BufferPool + + // Subprotocols specifies the server's supported protocols in order of + // preference. If this field is not nil, then the Upgrade method negotiates a + // subprotocol by selecting the first match in this list with a protocol + // requested by the client. If there's no match, then no protocol is + // negotiated (the Sec-Websocket-Protocol header is not included in the + // handshake response). + Subprotocols []string + + // Error specifies the function for generating HTTP error responses. If Error + // is nil, then http.Error is used to generate the HTTP response. + Error func(w http.ResponseWriter, r *http.Request, status int, reason error) + + // CheckOrigin returns true if the request Origin header is acceptable. If + // CheckOrigin is nil, then a safe default is used: return false if the + // Origin request header is present and the origin host is not equal to + // request Host header. + // + // A CheckOrigin function should carefully validate the request origin to + // prevent cross-site request forgery. + CheckOrigin func(r *http.Request) bool + + // EnableCompression specify if the server should attempt to negotiate per + // message compression (RFC 7692). Setting this value to true does not + // guarantee that compression will be supported. Currently only "no context + // takeover" modes are supported. + EnableCompression bool +} + +func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { + err := HandshakeError{reason} + if u.Error != nil { + u.Error(w, r, status, err) + } else { + w.Header().Set("Sec-Websocket-Version", "13") + http.Error(w, http.StatusText(status), status) + } + return nil, err +} + +// checkSameOrigin returns true if the origin is not set or is equal to the request host. +func checkSameOrigin(r *http.Request) bool { + origin := r.Header["Origin"] + if len(origin) == 0 { + return true + } + u, err := url.Parse(origin[0]) + if err != nil { + return false + } + return equalASCIIFold(u.Host, r.Host) +} + +func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { + if u.Subprotocols != nil { + clientProtocols := Subprotocols(r) + for _, serverProtocol := range u.Subprotocols { + for _, clientProtocol := range clientProtocols { + if clientProtocol == serverProtocol { + return clientProtocol + } + } + } + } else if responseHeader != nil { + return responseHeader.Get("Sec-Websocket-Protocol") + } + return "" +} + +// Upgrade upgrades the HTTP server connection to the WebSocket protocol. +// +// The responseHeader is included in the response to the client's upgrade +// request. Use the responseHeader to specify cookies (Set-Cookie). To specify +// subprotocols supported by the server, set Upgrader.Subprotocols directly. +// +// If the upgrade fails, then Upgrade replies to the client with an HTTP error +// response. +func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { + const badHandshake = "websocket: the client is not using the websocket protocol: " + + if !tokenListContainsValue(r.Header, "Connection", "upgrade") { + return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header") + } + + if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { + return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header") + } + + if r.Method != http.MethodGet { + return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET") + } + + if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { + return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") + } + + if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { + return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported") + } + + checkOrigin := u.CheckOrigin + if checkOrigin == nil { + checkOrigin = checkSameOrigin + } + if !checkOrigin(r) { + return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin") + } + + challengeKey := r.Header.Get("Sec-Websocket-Key") + if !isValidChallengeKey(challengeKey) { + return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header must be Base64 encoded value of 16-byte in length") + } + + subprotocol := u.selectSubprotocol(r, responseHeader) + + // Negotiate PMCE + var compress bool + if u.EnableCompression { + for _, ext := range parseExtensions(r.Header) { + if ext[""] != "permessage-deflate" { + continue + } + compress = true + break + } + } + + h, ok := w.(http.Hijacker) + if !ok { + return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") + } + var brw *bufio.ReadWriter + netConn, brw, err := h.Hijack() + if err != nil { + return u.returnError(w, r, http.StatusInternalServerError, err.Error()) + } + + if brw.Reader.Buffered() > 0 { + netConn.Close() + return nil, errors.New("websocket: client sent data before handshake is complete") + } + + var br *bufio.Reader + if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 { + // Reuse hijacked buffered reader as connection reader. + br = brw.Reader + } + + buf := bufioWriterBuffer(netConn, brw.Writer) + + var writeBuf []byte + if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 { + // Reuse hijacked write buffer as connection buffer. + writeBuf = buf + } + + c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf) + c.subprotocol = subprotocol + + if compress { + c.newCompressionWriter = compressNoContextTakeover + c.newDecompressionReader = decompressNoContextTakeover + } + + // Use larger of hijacked buffer and connection write buffer for header. + p := buf + if len(c.writeBuf) > len(p) { + p = c.writeBuf + } + p = p[:0] + + p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) + p = append(p, computeAcceptKey(challengeKey)...) + p = append(p, "\r\n"...) + if c.subprotocol != "" { + p = append(p, "Sec-WebSocket-Protocol: "...) + p = append(p, c.subprotocol...) + p = append(p, "\r\n"...) + } + if compress { + p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) + } + for k, vs := range responseHeader { + if k == "Sec-Websocket-Protocol" { + continue + } + for _, v := range vs { + p = append(p, k...) + p = append(p, ": "...) + for i := 0; i < len(v); i++ { + b := v[i] + if b <= 31 { + // prevent response splitting. + b = ' ' + } + p = append(p, b) + } + p = append(p, "\r\n"...) + } + } + p = append(p, "\r\n"...) + + // Clear deadlines set by HTTP server. + netConn.SetDeadline(time.Time{}) + + if u.HandshakeTimeout > 0 { + netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) + } + if _, err = netConn.Write(p); err != nil { + netConn.Close() + return nil, err + } + if u.HandshakeTimeout > 0 { + netConn.SetWriteDeadline(time.Time{}) + } + + return c, nil +} + +// Upgrade upgrades the HTTP server connection to the WebSocket protocol. +// +// Deprecated: Use websocket.Upgrader instead. +// +// Upgrade does not perform origin checking. The application is responsible for +// checking the Origin header before calling Upgrade. An example implementation +// of the same origin policy check is: +// +// if req.Header.Get("Origin") != "http://"+req.Host { +// http.Error(w, "Origin not allowed", http.StatusForbidden) +// return +// } +// +// If the endpoint supports subprotocols, then the application is responsible +// for negotiating the protocol used on the connection. Use the Subprotocols() +// function to get the subprotocols requested by the client. Use the +// Sec-Websocket-Protocol response header to specify the subprotocol selected +// by the application. +// +// The responseHeader is included in the response to the client's upgrade +// request. Use the responseHeader to specify cookies (Set-Cookie) and the +// negotiated subprotocol (Sec-Websocket-Protocol). +// +// The connection buffers IO to the underlying network connection. The +// readBufSize and writeBufSize parameters specify the size of the buffers to +// use. Messages can be larger than the buffers. +// +// If the request is not a valid WebSocket handshake, then Upgrade returns an +// error of type HandshakeError. Applications should handle this error by +// replying to the client with an HTTP error response. +func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { + u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} + u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { + // don't return errors to maintain backwards compatibility + } + u.CheckOrigin = func(r *http.Request) bool { + // allow all connections by default + return true + } + return u.Upgrade(w, r, responseHeader) +} + +// Subprotocols returns the subprotocols requested by the client in the +// Sec-Websocket-Protocol header. +func Subprotocols(r *http.Request) []string { + h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) + if h == "" { + return nil + } + protocols := strings.Split(h, ",") + for i := range protocols { + protocols[i] = strings.TrimSpace(protocols[i]) + } + return protocols +} + +// IsWebSocketUpgrade returns true if the client requested upgrade to the +// WebSocket protocol. +func IsWebSocketUpgrade(r *http.Request) bool { + return tokenListContainsValue(r.Header, "Connection", "upgrade") && + tokenListContainsValue(r.Header, "Upgrade", "websocket") +} + +// bufioReaderSize size returns the size of a bufio.Reader. +func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int { + // This code assumes that peek on a reset reader returns + // bufio.Reader.buf[:0]. + // TODO: Use bufio.Reader.Size() after Go 1.10 + br.Reset(originalReader) + if p, err := br.Peek(0); err == nil { + return cap(p) + } + return 0 +} + +// writeHook is an io.Writer that records the last slice passed to it vio +// io.Writer.Write. +type writeHook struct { + p []byte +} + +func (wh *writeHook) Write(p []byte) (int, error) { + wh.p = p + return len(p), nil +} + +// bufioWriterBuffer grabs the buffer from a bufio.Writer. +func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte { + // This code assumes that bufio.Writer.buf[:1] is passed to the + // bufio.Writer's underlying writer. + var wh writeHook + bw.Reset(&wh) + bw.WriteByte(0) + bw.Flush() + + bw.Reset(originalWriter) + + return wh.p[:cap(wh.p)] +} diff --git a/vendor/github.com/gorilla/websocket/tls_handshake.go b/vendor/github.com/gorilla/websocket/tls_handshake.go new file mode 100644 index 000000000..a62b68ccb --- /dev/null +++ b/vendor/github.com/gorilla/websocket/tls_handshake.go @@ -0,0 +1,21 @@ +//go:build go1.17 +// +build go1.17 + +package websocket + +import ( + "context" + "crypto/tls" +) + +func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { + if err := tlsConn.HandshakeContext(ctx); err != nil { + return err + } + if !cfg.InsecureSkipVerify { + if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/gorilla/websocket/tls_handshake_116.go b/vendor/github.com/gorilla/websocket/tls_handshake_116.go new file mode 100644 index 000000000..e1b2b44f6 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/tls_handshake_116.go @@ -0,0 +1,21 @@ +//go:build !go1.17 +// +build !go1.17 + +package websocket + +import ( + "context" + "crypto/tls" +) + +func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { + if err := tlsConn.Handshake(); err != nil { + return err + } + if !cfg.InsecureSkipVerify { + if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/gorilla/websocket/util.go b/vendor/github.com/gorilla/websocket/util.go new file mode 100644 index 000000000..31a5dee64 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/util.go @@ -0,0 +1,298 @@ +// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "io" + "net/http" + "strings" + "unicode/utf8" +) + +var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + +func computeAcceptKey(challengeKey string) string { + h := sha1.New() + h.Write([]byte(challengeKey)) + h.Write(keyGUID) + return base64.StdEncoding.EncodeToString(h.Sum(nil)) +} + +func generateChallengeKey() (string, error) { + p := make([]byte, 16) + if _, err := io.ReadFull(rand.Reader, p); err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(p), nil +} + +// Token octets per RFC 2616. +var isTokenOctet = [256]bool{ + '!': true, + '#': true, + '$': true, + '%': true, + '&': true, + '\'': true, + '*': true, + '+': true, + '-': true, + '.': true, + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + 'A': true, + 'B': true, + 'C': true, + 'D': true, + 'E': true, + 'F': true, + 'G': true, + 'H': true, + 'I': true, + 'J': true, + 'K': true, + 'L': true, + 'M': true, + 'N': true, + 'O': true, + 'P': true, + 'Q': true, + 'R': true, + 'S': true, + 'T': true, + 'U': true, + 'W': true, + 'V': true, + 'X': true, + 'Y': true, + 'Z': true, + '^': true, + '_': true, + '`': true, + 'a': true, + 'b': true, + 'c': true, + 'd': true, + 'e': true, + 'f': true, + 'g': true, + 'h': true, + 'i': true, + 'j': true, + 'k': true, + 'l': true, + 'm': true, + 'n': true, + 'o': true, + 'p': true, + 'q': true, + 'r': true, + 's': true, + 't': true, + 'u': true, + 'v': true, + 'w': true, + 'x': true, + 'y': true, + 'z': true, + '|': true, + '~': true, +} + +// skipSpace returns a slice of the string s with all leading RFC 2616 linear +// whitespace removed. +func skipSpace(s string) (rest string) { + i := 0 + for ; i < len(s); i++ { + if b := s[i]; b != ' ' && b != '\t' { + break + } + } + return s[i:] +} + +// nextToken returns the leading RFC 2616 token of s and the string following +// the token. +func nextToken(s string) (token, rest string) { + i := 0 + for ; i < len(s); i++ { + if !isTokenOctet[s[i]] { + break + } + } + return s[:i], s[i:] +} + +// nextTokenOrQuoted returns the leading token or quoted string per RFC 2616 +// and the string following the token or quoted string. +func nextTokenOrQuoted(s string) (value string, rest string) { + if !strings.HasPrefix(s, "\"") { + return nextToken(s) + } + s = s[1:] + for i := 0; i < len(s); i++ { + switch s[i] { + case '"': + return s[:i], s[i+1:] + case '\\': + p := make([]byte, len(s)-1) + j := copy(p, s[:i]) + escape := true + for i = i + 1; i < len(s); i++ { + b := s[i] + switch { + case escape: + escape = false + p[j] = b + j++ + case b == '\\': + escape = true + case b == '"': + return string(p[:j]), s[i+1:] + default: + p[j] = b + j++ + } + } + return "", "" + } + } + return "", "" +} + +// equalASCIIFold returns true if s is equal to t with ASCII case folding as +// defined in RFC 4790. +func equalASCIIFold(s, t string) bool { + for s != "" && t != "" { + sr, size := utf8.DecodeRuneInString(s) + s = s[size:] + tr, size := utf8.DecodeRuneInString(t) + t = t[size:] + if sr == tr { + continue + } + if 'A' <= sr && sr <= 'Z' { + sr = sr + 'a' - 'A' + } + if 'A' <= tr && tr <= 'Z' { + tr = tr + 'a' - 'A' + } + if sr != tr { + return false + } + } + return s == t +} + +// tokenListContainsValue returns true if the 1#token header with the given +// name contains a token equal to value with ASCII case folding. +func tokenListContainsValue(header http.Header, name string, value string) bool { +headers: + for _, s := range header[name] { + for { + var t string + t, s = nextToken(skipSpace(s)) + if t == "" { + continue headers + } + s = skipSpace(s) + if s != "" && s[0] != ',' { + continue headers + } + if equalASCIIFold(t, value) { + return true + } + if s == "" { + continue headers + } + s = s[1:] + } + } + return false +} + +// parseExtensions parses WebSocket extensions from a header. +func parseExtensions(header http.Header) []map[string]string { + // From RFC 6455: + // + // Sec-WebSocket-Extensions = extension-list + // extension-list = 1#extension + // extension = extension-token *( ";" extension-param ) + // extension-token = registered-token + // registered-token = token + // extension-param = token [ "=" (token | quoted-string) ] + // ;When using the quoted-string syntax variant, the value + // ;after quoted-string unescaping MUST conform to the + // ;'token' ABNF. + + var result []map[string]string +headers: + for _, s := range header["Sec-Websocket-Extensions"] { + for { + var t string + t, s = nextToken(skipSpace(s)) + if t == "" { + continue headers + } + ext := map[string]string{"": t} + for { + s = skipSpace(s) + if !strings.HasPrefix(s, ";") { + break + } + var k string + k, s = nextToken(skipSpace(s[1:])) + if k == "" { + continue headers + } + s = skipSpace(s) + var v string + if strings.HasPrefix(s, "=") { + v, s = nextTokenOrQuoted(skipSpace(s[1:])) + s = skipSpace(s) + } + if s != "" && s[0] != ',' && s[0] != ';' { + continue headers + } + ext[k] = v + } + if s != "" && s[0] != ',' { + continue headers + } + result = append(result, ext) + if s == "" { + continue headers + } + s = s[1:] + } + } + return result +} + +// isValidChallengeKey checks if the argument meets RFC6455 specification. +func isValidChallengeKey(s string) bool { + // From RFC6455: + // + // A |Sec-WebSocket-Key| header field with a base64-encoded (see + // Section 4 of [RFC4648]) value that, when decoded, is 16 bytes in + // length. + + if s == "" { + return false + } + decoded, err := base64.StdEncoding.DecodeString(s) + return err == nil && len(decoded) == 16 +} diff --git a/vendor/github.com/gorilla/websocket/x_net_proxy.go b/vendor/github.com/gorilla/websocket/x_net_proxy.go new file mode 100644 index 000000000..2e668f6b8 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/x_net_proxy.go @@ -0,0 +1,473 @@ +// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. +//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy + +// Package proxy provides support for a variety of protocols to proxy network +// data. +// + +package websocket + +import ( + "errors" + "io" + "net" + "net/url" + "os" + "strconv" + "strings" + "sync" +) + +type proxy_direct struct{} + +// Direct is a direct proxy: one that makes network connections directly. +var proxy_Direct = proxy_direct{} + +func (proxy_direct) Dial(network, addr string) (net.Conn, error) { + return net.Dial(network, addr) +} + +// A PerHost directs connections to a default Dialer unless the host name +// requested matches one of a number of exceptions. +type proxy_PerHost struct { + def, bypass proxy_Dialer + + bypassNetworks []*net.IPNet + bypassIPs []net.IP + bypassZones []string + bypassHosts []string +} + +// NewPerHost returns a PerHost Dialer that directs connections to either +// defaultDialer or bypass, depending on whether the connection matches one of +// the configured rules. +func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost { + return &proxy_PerHost{ + def: defaultDialer, + bypass: bypass, + } +} + +// Dial connects to the address addr on the given network through either +// defaultDialer or bypass. +func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + + return p.dialerForRequest(host).Dial(network, addr) +} + +func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer { + if ip := net.ParseIP(host); ip != nil { + for _, net := range p.bypassNetworks { + if net.Contains(ip) { + return p.bypass + } + } + for _, bypassIP := range p.bypassIPs { + if bypassIP.Equal(ip) { + return p.bypass + } + } + return p.def + } + + for _, zone := range p.bypassZones { + if strings.HasSuffix(host, zone) { + return p.bypass + } + if host == zone[1:] { + // For a zone ".example.com", we match "example.com" + // too. + return p.bypass + } + } + for _, bypassHost := range p.bypassHosts { + if bypassHost == host { + return p.bypass + } + } + return p.def +} + +// AddFromString parses a string that contains comma-separated values +// specifying hosts that should use the bypass proxy. Each value is either an +// IP address, a CIDR range, a zone (*.example.com) or a host name +// (localhost). A best effort is made to parse the string and errors are +// ignored. +func (p *proxy_PerHost) AddFromString(s string) { + hosts := strings.Split(s, ",") + for _, host := range hosts { + host = strings.TrimSpace(host) + if len(host) == 0 { + continue + } + if strings.Contains(host, "/") { + // We assume that it's a CIDR address like 127.0.0.0/8 + if _, net, err := net.ParseCIDR(host); err == nil { + p.AddNetwork(net) + } + continue + } + if ip := net.ParseIP(host); ip != nil { + p.AddIP(ip) + continue + } + if strings.HasPrefix(host, "*.") { + p.AddZone(host[1:]) + continue + } + p.AddHost(host) + } +} + +// AddIP specifies an IP address that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match an IP. +func (p *proxy_PerHost) AddIP(ip net.IP) { + p.bypassIPs = append(p.bypassIPs, ip) +} + +// AddNetwork specifies an IP range that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match. +func (p *proxy_PerHost) AddNetwork(net *net.IPNet) { + p.bypassNetworks = append(p.bypassNetworks, net) +} + +// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of +// "example.com" matches "example.com" and all of its subdomains. +func (p *proxy_PerHost) AddZone(zone string) { + if strings.HasSuffix(zone, ".") { + zone = zone[:len(zone)-1] + } + if !strings.HasPrefix(zone, ".") { + zone = "." + zone + } + p.bypassZones = append(p.bypassZones, zone) +} + +// AddHost specifies a host name that will use the bypass proxy. +func (p *proxy_PerHost) AddHost(host string) { + if strings.HasSuffix(host, ".") { + host = host[:len(host)-1] + } + p.bypassHosts = append(p.bypassHosts, host) +} + +// A Dialer is a means to establish a connection. +type proxy_Dialer interface { + // Dial connects to the given address via the proxy. + Dial(network, addr string) (c net.Conn, err error) +} + +// Auth contains authentication parameters that specific Dialers may require. +type proxy_Auth struct { + User, Password string +} + +// FromEnvironment returns the dialer specified by the proxy related variables in +// the environment. +func proxy_FromEnvironment() proxy_Dialer { + allProxy := proxy_allProxyEnv.Get() + if len(allProxy) == 0 { + return proxy_Direct + } + + proxyURL, err := url.Parse(allProxy) + if err != nil { + return proxy_Direct + } + proxy, err := proxy_FromURL(proxyURL, proxy_Direct) + if err != nil { + return proxy_Direct + } + + noProxy := proxy_noProxyEnv.Get() + if len(noProxy) == 0 { + return proxy + } + + perHost := proxy_NewPerHost(proxy, proxy_Direct) + perHost.AddFromString(noProxy) + return perHost +} + +// proxySchemes is a map from URL schemes to a function that creates a Dialer +// from a URL with such a scheme. +var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error) + +// RegisterDialerType takes a URL scheme and a function to generate Dialers from +// a URL with that scheme and a forwarding Dialer. Registered schemes are used +// by FromURL. +func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) { + if proxy_proxySchemes == nil { + proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) + } + proxy_proxySchemes[scheme] = f +} + +// FromURL returns a Dialer given a URL specification and an underlying +// Dialer for it to make network requests. +func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) { + var auth *proxy_Auth + if u.User != nil { + auth = new(proxy_Auth) + auth.User = u.User.Username() + if p, ok := u.User.Password(); ok { + auth.Password = p + } + } + + switch u.Scheme { + case "socks5": + return proxy_SOCKS5("tcp", u.Host, auth, forward) + } + + // If the scheme doesn't match any of the built-in schemes, see if it + // was registered by another package. + if proxy_proxySchemes != nil { + if f, ok := proxy_proxySchemes[u.Scheme]; ok { + return f(u, forward) + } + } + + return nil, errors.New("proxy: unknown scheme: " + u.Scheme) +} + +var ( + proxy_allProxyEnv = &proxy_envOnce{ + names: []string{"ALL_PROXY", "all_proxy"}, + } + proxy_noProxyEnv = &proxy_envOnce{ + names: []string{"NO_PROXY", "no_proxy"}, + } +) + +// envOnce looks up an environment variable (optionally by multiple +// names) once. It mitigates expensive lookups on some platforms +// (e.g. Windows). +// (Borrowed from net/http/transport.go) +type proxy_envOnce struct { + names []string + once sync.Once + val string +} + +func (e *proxy_envOnce) Get() string { + e.once.Do(e.init) + return e.val +} + +func (e *proxy_envOnce) init() { + for _, n := range e.names { + e.val = os.Getenv(n) + if e.val != "" { + return + } + } +} + +// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address +// with an optional username and password. See RFC 1928 and RFC 1929. +func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) { + s := &proxy_socks5{ + network: network, + addr: addr, + forward: forward, + } + if auth != nil { + s.user = auth.User + s.password = auth.Password + } + + return s, nil +} + +type proxy_socks5 struct { + user, password string + network, addr string + forward proxy_Dialer +} + +const proxy_socks5Version = 5 + +const ( + proxy_socks5AuthNone = 0 + proxy_socks5AuthPassword = 2 +) + +const proxy_socks5Connect = 1 + +const ( + proxy_socks5IP4 = 1 + proxy_socks5Domain = 3 + proxy_socks5IP6 = 4 +) + +var proxy_socks5Errors = []string{ + "", + "general failure", + "connection forbidden", + "network unreachable", + "host unreachable", + "connection refused", + "TTL expired", + "command not supported", + "address type not supported", +} + +// Dial connects to the address addr on the given network via the SOCKS5 proxy. +func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) { + switch network { + case "tcp", "tcp6", "tcp4": + default: + return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) + } + + conn, err := s.forward.Dial(s.network, s.addr) + if err != nil { + return nil, err + } + if err := s.connect(conn, addr); err != nil { + conn.Close() + return nil, err + } + return conn, nil +} + +// connect takes an existing connection to a socks5 proxy server, +// and commands the server to extend that connection to target, +// which must be a canonical address with a host and port. +func (s *proxy_socks5) connect(conn net.Conn, target string) error { + host, portStr, err := net.SplitHostPort(target) + if err != nil { + return err + } + + port, err := strconv.Atoi(portStr) + if err != nil { + return errors.New("proxy: failed to parse port number: " + portStr) + } + if port < 1 || port > 0xffff { + return errors.New("proxy: port number out of range: " + portStr) + } + + // the size here is just an estimate + buf := make([]byte, 0, 6+len(host)) + + buf = append(buf, proxy_socks5Version) + if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { + buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword) + } else { + buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone) + } + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + if buf[0] != 5 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) + } + if buf[1] == 0xff { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") + } + + // See RFC 1929 + if buf[1] == proxy_socks5AuthPassword { + buf = buf[:0] + buf = append(buf, 1 /* password protocol version */) + buf = append(buf, uint8(len(s.user))) + buf = append(buf, s.user...) + buf = append(buf, uint8(len(s.password))) + buf = append(buf, s.password...) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if buf[1] != 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") + } + } + + buf = buf[:0] + buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */) + + if ip := net.ParseIP(host); ip != nil { + if ip4 := ip.To4(); ip4 != nil { + buf = append(buf, proxy_socks5IP4) + ip = ip4 + } else { + buf = append(buf, proxy_socks5IP6) + } + buf = append(buf, ip...) + } else { + if len(host) > 255 { + return errors.New("proxy: destination host name too long: " + host) + } + buf = append(buf, proxy_socks5Domain) + buf = append(buf, byte(len(host))) + buf = append(buf, host...) + } + buf = append(buf, byte(port>>8), byte(port)) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:4]); err != nil { + return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + failure := "unknown error" + if int(buf[1]) < len(proxy_socks5Errors) { + failure = proxy_socks5Errors[buf[1]] + } + + if len(failure) > 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) + } + + bytesToDiscard := 0 + switch buf[3] { + case proxy_socks5IP4: + bytesToDiscard = net.IPv4len + case proxy_socks5IP6: + bytesToDiscard = net.IPv6len + case proxy_socks5Domain: + _, err := io.ReadFull(conn, buf[:1]) + if err != nil { + return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + bytesToDiscard = int(buf[0]) + default: + return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) + } + + if cap(buf) < bytesToDiscard { + buf = make([]byte, bytesToDiscard) + } else { + buf = buf[:bytesToDiscard] + } + if _, err := io.ReadFull(conn, buf); err != nil { + return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + // Also need to discard the port number + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/.codacy.yml b/vendor/github.com/nikoksr/notify/.codacy.yml new file mode 100644 index 000000000..c51b7ff70 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/.codacy.yml @@ -0,0 +1,3 @@ +--- +exclude_paths: + - '**.md' diff --git a/vendor/github.com/nikoksr/notify/.editorconfig b/vendor/github.com/nikoksr/notify/.editorconfig new file mode 100644 index 000000000..fcd5e93e1 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[*.{md,yml,toml}] +indent_size = 2 diff --git a/vendor/github.com/nikoksr/notify/.gitignore b/vendor/github.com/nikoksr/notify/.gitignore new file mode 100644 index 000000000..046c23f60 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/.gitignore @@ -0,0 +1,13 @@ +# Folders +bin/ +build/ +.idea/ +.vscode/ +tmp/ + +# Files +*.log +.gh-docker-token +.env +coverage.out +cover.html diff --git a/vendor/github.com/nikoksr/notify/.golangci.yaml b/vendor/github.com/nikoksr/notify/.golangci.yaml new file mode 100644 index 000000000..27b48a814 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/.golangci.yaml @@ -0,0 +1,475 @@ +# This file is licensed under the terms of the MIT license https://opensource.org/license/mit +# Copyright (c) 2021-2025 Marat Reimers + +## Golden config for golangci-lint v2.7.2 +# +# This is the best config for golangci-lint based on my experience and opinion. +# It is very strict, but not extremely strict. +# Feel free to adapt it to suit your needs. +# If this config helps you, please consider keeping a link to this repo (see the next comment). + +# Based on https://github.com/maratori/golangci-lint-config + +version: "2" + +issues: + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 50 + +formatters: + enable: + - goimports # checks if the code and import statements are formatted according to the 'goimports' command + - golines # checks if code is formatted, and fixes long lines + + ## you may want to enable + #- gci # checks if code and import statements are formatted, with additional rules + #- gofmt # checks if the code is formatted according to 'gofmt' command + #- gofumpt # enforces a stricter format than 'gofmt', while being backwards compatible + #- swaggo # formats swaggo comments + + # All settings can be found here https://github.com/golangci/golangci-lint/blob/HEAD/.golangci.reference.yml + settings: + goimports: + # A list of prefixes, which, if set, checks import paths + # with the given prefixes are grouped after 3rd-party packages. + # Default: [] + local-prefixes: + - github.com/my/project + + golines: + # Target maximum line length. + # Default: 100 + max-len: 120 + +linters: + enable: + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + - canonicalheader # checks whether net/http.Header uses canonical header + - copyloopvar # detects places where loop variables are copied (Go 1.22+) + - cyclop # checks function and package cyclomatic complexity + - depguard # checks if package imports are in a list of acceptable packages + - dupl # tool for code clone detection + - durationcheck # checks for two durations multiplied together + - embeddedstructfieldcheck # checks embedded types in structs + - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases + - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error + - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 + - exhaustive # checks exhaustiveness of enum switch statements + - exptostd # detects functions from golang.org/x/exp/ that can be replaced by std functions + - fatcontext # detects nested contexts in loops + - forbidigo # forbids identifiers + #- funcorder # checks the order of functions, methods, and constructors # DISABLED: too opinionated + - funlen # tool for detection of long functions + - gocheckcompilerdirectives # validates go compiler directive comments (//go:) + - gochecknoglobals # checks that no global variables exist + - gochecknoinits # checks that no init functions are present in Go code + - gochecksumtype # checks exhaustiveness on Go "sum types" + - gocognit # computes and checks the cognitive complexity of functions + - goconst # finds repeated strings that could be replaced by a constant + - gocritic # provides diagnostics that check for bugs, performance and style issues + - gocyclo # computes and checks the cyclomatic complexity of functions + - godoclint # checks Golang's documentation practice + - godot # checks if comments end in a period + - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod + - goprintffuncname # checks that printf-like functions are named with f at the end + - gosec # inspects source code for security problems + - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - iface # checks the incorrect use of interfaces, helping developers avoid interface pollution + - ineffassign # detects when assignments to existing variables are not used + - intrange # finds places where for loops could make use of an integer range + - iotamixing # checks if iotas are being used in const blocks with other non-iota declarations + - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap) + - makezero # finds slice declarations with non-zero initial length + - mirror # reports wrong mirror patterns of bytes/strings usage + - mnd # detects magic numbers + - modernize # suggests simplifications to Go code, using modern language and library features + - musttag # enforces field tags in (un)marshaled structs + - nakedret # finds naked returns in functions greater than a specified function length + - nestif # reports deeply nested if statements + - nilerr # finds the code that returns nil even if it checks that the error is not nil + - nilnesserr # reports that it checks for err != nil, but it returns a different nil value error (powered by nilness and nilerr) + - nilnil # checks that there is no simultaneous return of nil error and an invalid value + - noctx # finds sending http request without context.Context + - nolintlint # reports ill-formed or insufficient nolint directives + - nonamedreturns # reports all named returns + - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL + - perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative + - predeclared # finds code that shadows one of Go's predeclared identifiers + - promlinter # checks Prometheus metrics naming via promlint + - protogetter # reports direct reads from proto message fields when getters should be used + - reassign # checks that package variables are not reassigned + #- recvcheck # checks for receiver type consistency # DISABLED: mixed receivers are sometimes intentional + - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint + - rowserrcheck # checks whether Err of rows is checked successfully + - sloglint # ensure consistent code style when using log/slog + - spancheck # checks for mistakes with OpenTelemetry/Census spans + - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed + - staticcheck # is a go vet on steroids, applying a ton of static analysis checks + - testableexamples # checks if examples are testable (have an expected output) + - testifylint # checks usage of github.com/stretchr/testify + #- testpackage # makes you use a separate _test package # DISABLED: we need access to internal/unexported items in tests + - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes + - unconvert # removes unnecessary type conversions + - unparam # reports unused function parameters + - unqueryvet # detects SELECT * in SQL queries and SQL builders, encouraging explicit column selection + - unused # checks for unused constants, variables, functions and types + - usestdlibvars # detects the possibility to use variables/constants from the Go standard library + - usetesting # reports uses of functions with replacement inside the testing package + - wastedassign # finds wasted assignment statements + - whitespace # detects leading and trailing whitespace + + ## you may want to enable + #- arangolint # opinionated best practices for arangodb client + #- decorder # checks declaration order and count of types, constants, variables and functions + #- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized + #- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega + #- godox # detects usage of FIXME, TODO and other keywords inside comments + #- goheader # checks is file header matches to pattern + #- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters + #- interfacebloat # checks the number of methods inside an interface + #- ireturn # accept interfaces, return concrete types + #- noinlineerr # disallows inline error handling `if err := ...; err != nil {` + #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated + #- tagalign # checks that struct tags are well aligned + #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope + #- wrapcheck # checks that errors returned from external packages are wrapped + #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event + + ## disabled + #- containedctx # detects struct contained context.Context field + #- contextcheck # [too many false positives] checks the function whether use a non-inherited context + #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + #- dupword # [useless without config] checks for duplicate words in the source code + #- err113 # [too strict] checks the errors handling expressions + #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted + #- forcetypeassert # [replaced by errcheck] finds forced type assertions + #- gomodguard # [use more powerful depguard] allow and block lists linter for direct Go module dependencies + #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase + #- grouper # analyzes expression groups + #- importas # enforces consistent import aliases + #- lll # [replaced by golines] reports long lines + #- maintidx # measures the maintainability index of each function + #- misspell # [useless] finds commonly misspelled English words in comments + #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity + #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test + #- tagliatelle # checks the struct tags + #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers + #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines + #- wsl_v5 # [too strict and mostly code is not more readable] add or remove empty lines + + # All settings can be found here https://github.com/golangci/golangci-lint/blob/HEAD/.golangci.reference.yml + settings: + cyclop: + # The maximal code complexity to report. + # Default: 10 + max-complexity: 30 + # The maximal average package complexity. + # If it's higher than 0.0 (float) the check is enabled. + # Default: 0.0 + package-average: 10.0 + + depguard: + # Rules to apply. + # + # Variables: + # - File Variables + # Use an exclamation mark `!` to negate a variable. + # Example: `!$test` matches any file that is not a go test file. + # + # `$all` - matches all go files + # `$test` - matches all go test files + # + # - Package Variables + # + # `$gostd` - matches all of go's standard library (Pulled from `GOROOT`) + # + # Default (applies if no custom rules are defined): Only allow $gostd in all files. + rules: + "deprecated": + # List of file globs that will match this list of settings to compare against. + # By default, if a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The placeholder '${base-path}' is substituted with a path relative to the mode defined with `run.relative-path-mode`. + # The placeholder '${config-path}' is substituted with a path relative to the configuration file. + # Default: $all + files: + - "$all" + # List of packages that are not allowed. + # Entries can be a variable (starting with $), a string prefix, or an exact match (if ending with $). + # Default: [] + deny: + - pkg: github.com/golang/protobuf + desc: Use google.golang.org/protobuf instead, see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules + - pkg: github.com/satori/go.uuid + desc: Use github.com/google/uuid instead, satori's package is not maintained + - pkg: github.com/gofrs/uuid$ + desc: Use github.com/gofrs/uuid/v5 or later, it was not a go module before v5 + "non-test files": + files: + - "!$test" + deny: + - pkg: math/rand$ + desc: Use math/rand/v2 instead, see https://go.dev/blog/randv2 + "non-main files": + files: + - "!**/main.go" + deny: + - pkg: log$ + desc: Use log/slog instead, see https://go.dev/blog/slog + + embeddedstructfieldcheck: + # Checks that sync.Mutex and sync.RWMutex are not used as embedded fields. + # Default: false + forbid-mutex: true + + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + + exhaustruct: + # List of regular expressions to match type names that should be excluded from processing. + # Anonymous structs can be matched by '' alias. + # Has precedence over `include`. + # Each regular expression must match the full type name, including package path. + # For example, to match type `net/http.Cookie` regular expression should be `.*/http\.Cookie`, + # but not `http\.Cookie`. + # Default: [] + exclude: + # std libs + - ^net/http.Client$ + - ^net/http.Cookie$ + - ^net/http.Request$ + - ^net/http.Response$ + - ^net/http.Server$ + - ^net/http.Transport$ + - ^net/url.URL$ + - ^os/exec.Cmd$ + - ^reflect.StructField$ + # public libs + - ^github.com/Shopify/sarama.Config$ + - ^github.com/Shopify/sarama.ProducerMessage$ + - ^github.com/mitchellh/mapstructure.DecoderConfig$ + - ^github.com/prometheus/client_golang/.+Opts$ + - ^github.com/spf13/cobra.Command$ + - ^github.com/spf13/cobra.CompletionOptions$ + - ^github.com/stretchr/testify/mock.Mock$ + - ^github.com/testcontainers/testcontainers-go.+Request$ + - ^github.com/testcontainers/testcontainers-go.FromDockerfile$ + - ^golang.org/x/tools/go/analysis.Analyzer$ + - ^google.golang.org/protobuf/.+Options$ + - ^gopkg.in/yaml.v3.Node$ + # Allows empty structures in return statements. + # Default: false + allow-empty-returns: true + + funcorder: + # Checks if the exported methods of a structure are placed before the non-exported ones. + # Default: true + struct-method: false + + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 100 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: 50 + + gochecksumtype: + # Presence of `default` case in switch statements satisfies exhaustiveness, if all members are not listed. + # Default: true + default-signifies-exhaustive: false + + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 20 + + gocritic: + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be found at https://go-critic.com/overview. + settings: + captLocal: + # Whether to restrict checker to params only. + # Default: true + paramsOnly: false + underef: + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref: false + + godoclint: + # List of rules to enable in addition to the default set. + # Default: empty + enable: + # Assert no unused link in godocs. + # https://github.com/godoc-lint/godoc-lint?tab=readme-ov-file#no-unused-link + - no-unused-link + + govet: + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `GL_DEBUG=govet golangci-lint run --enable=govet` to see default, all available analyzers, and enabled analyzers. + # Default: [] + disable: + - fieldalignment # too strict + # Settings per analyzer. + settings: + shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + strict: true + + inamedparam: + # Skips check for interface methods with only a single parameter. + # Default: false + skip-single-param: true + + mnd: + # List of function patterns to exclude from analysis. + # Values always ignored: `time.Date`, + # `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`, + # `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`. + # Default: [] + ignored-functions: + - args.Error + - flag.Arg + - flag.Duration.* + - flag.Float.* + - flag.Int.* + - flag.Uint.* + - os.Chmod + - os.Mkdir.* + - os.OpenFile + - os.WriteFile + - prometheus.ExponentialBuckets.* + - prometheus.LinearBuckets + + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 0 + + nolintlint: + # Exclude following linters from requiring an explanation. + # Default: [] + allow-no-explanation: [ funlen, gocognit, golines ] + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true + + perfsprint: + # Optimizes into strings concatenation. + # Default: true + strconcat: false + + reassign: + # Patterns for global variable names that are checked for reassignment. + # See https://github.com/curioswitch/go-reassign#usage + # Default: ["EOF", "Err.*"] + patterns: + - ".*" + + rowserrcheck: + # database/sql is always checked. + # Default: [] + packages: + - github.com/jmoiron/sqlx + + sloglint: + # Enforce not using global loggers. + # Values: + # - "": disabled + # - "all": report all global loggers + # - "default": report only the default slog logger + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global + # Default: "" + no-global: all + # Enforce using methods that accept a context. + # Values: + # - "": disabled + # - "all": report all contextless calls + # - "scope": report only if a context exists in the scope of the outermost function + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only + # Default: "" + context: scope + + staticcheck: + # SAxxxx checks in https://staticcheck.dev/docs/configuration/options/#checks + # Example (to disable some checks): [ "all", "-SA1000", "-SA1001"] + # Default: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"] + checks: + - all + # Incorrect or missing package comment. + # https://staticcheck.dev/docs/checks/#ST1000 + - -ST1000 + # Use consistent method receiver names. + # https://staticcheck.dev/docs/checks/#ST1016 + - -ST1016 + # Omit embedded fields from selector expression. + # https://staticcheck.dev/docs/checks/#QF1008 + - -QF1008 + + usetesting: + # Enable/disable `os.TempDir()` detections. + # Default: false + os-temp-dir: true + + exclusions: + # Log a warning if an exclusion rule is unused. + # Default: false + warn-unused: true + # Predefined exclusion rules. + # Default: [] + presets: + - std-error-handling + - common-false-positives + # Excluding configuration per-path, per-linter, per-text and per-source. + rules: + - source: 'TODO' + linters: [ godot ] + - text: 'should have a package comment' + linters: [ revive ] + - text: 'exported \S+ \S+ should have comment( \(or a comment on this block\))? or be unexported' + linters: [ revive ] + - text: 'package comment should be of the form ".+"' + source: '// ?(nolint|TODO)' + linters: [ revive ] + - text: 'comment on exported \S+ \S+ should be of the form ".+"' + source: '// ?(nolint|TODO)' + linters: [ revive, staticcheck ] + - path: 'service/http/' + text: 'var-naming: avoid package names that conflict with Go standard library package names' + linters: + - revive + - path: '_test\.go' + linters: + - bodyclose + - dupl + - errcheck + - funlen + - goconst + - gosec + - noctx + - wrapcheck diff --git a/vendor/github.com/nikoksr/notify/.mockery.yaml b/vendor/github.com/nikoksr/notify/.mockery.yaml new file mode 100644 index 000000000..92f45bb91 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/.mockery.yaml @@ -0,0 +1,13 @@ +with-expecter: true +mockname: "mock{{.InterfaceName}}" +filename: "mock_{{.InterfaceName | snakecase}}.go" +packages: + github.com/nikoksr/notify: + config: + dir: "{{.InterfaceDir}}" + inpackage: true + include-auto-generated: false + recursive: true + all: true + exclude: + - "service/http" diff --git a/vendor/github.com/nikoksr/notify/CODE_OF_CONDUCT.md b/vendor/github.com/nikoksr/notify/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..b0432af9e --- /dev/null +++ b/vendor/github.com/nikoksr/notify/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[INSERT CONTACT METHOD]. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/inclusion/blob/master/code-of-conduct-enforcement/consequence-ladder.md +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations + diff --git a/vendor/github.com/nikoksr/notify/CONTRIBUTING.md b/vendor/github.com/nikoksr/notify/CONTRIBUTING.md new file mode 100644 index 000000000..92a9dc584 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/CONTRIBUTING.md @@ -0,0 +1,34 @@ +## Contributing to Notify + +We want to make contributing to this project as easy and transparent as possible. + +## Tests + +Ideally, unit tests should accompany every newly introduced exported function. We're always striving to increase the project's test coverage. + +## Commits + +Commit messages should be well formatted, and to make that "standardized", we are using Conventional Commits. + +You can follow the documentation on [their website](https://www.conventionalcommits.org). + +## Pull Requests + +We actively welcome your pull requests. + +1. Fork the repo and create your branch from `main`. +2. If you've added code that should be tested, add tests. +3. If you've changed or added exported functions or types, document them. +4. We use [gofumpt](https://github.com/mvdan/gofumpt) to format our code. Don't forget to always run `make fmt` before opening a new PR. +5. Ensure the test suite passes and the linter doesn't complain (`make ci`). + + +## Issues + +We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be +able to reproduce the issue. + +## License + +By contributing to notify, you agree that your contributions will be licensed under the LICENSE file in the root +directory of this source tree. diff --git a/vendor/github.com/nikoksr/notify/LICENSE b/vendor/github.com/nikoksr/notify/LICENSE new file mode 100644 index 000000000..5711c31c8 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2021 Niko Köser + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/nikoksr/notify/Makefile b/vendor/github.com/nikoksr/notify/Makefile new file mode 100644 index 000000000..d2913617c --- /dev/null +++ b/vendor/github.com/nikoksr/notify/Makefile @@ -0,0 +1,67 @@ +export GO111MODULE := on +export GOPROXY = https://proxy.golang.org,direct + +############################################################################### +# DEPENDENCIES +############################################################################### + +# Install all the build and lint dependencies +tools: + @go install mvdan.cc/gofumpt@latest + @go install github.com/daixiang0/gci@latest + @go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + @go install github.com/vektra/mockery/v2@v2.44.1 + @go install github.com/segmentio/golines@latest +.PHONY: tools + +############################################################################### +# TESTS +############################################################################### + +test: + @go build ./... + @go test -failfast -race ./... +.PHONY: test + +gen-coverage: + @go test -race -covermode=atomic -coverprofile=coverage.out ./... > /dev/null +.PHONY: gen-coverage + +coverage: gen-coverage + @go tool cover -func coverage.out +.PHONY: coverage + +coverage-html: gen-coverage + @go tool cover -html=coverage.out -o cover.html +.PHONY: coverage-html + +mock: + @mockery + @rm mock_notifier.go mock_option.go +.PHONY: mock + +############################################################################### +# CODE HEALTH +############################################################################### + +fmt: + @goimports -w . + @golines --shorten-comments -m 120 -w . + @gofumpt -w -l . + @gci write -s standard -s default -s "prefix(github.com/nikoksr/notify)" . +.PHONY: fmt + +lint: + @golangci-lint run ./... +.PHONY: lint + +clean: + @find . -name "mock_*" -type f -delete +.PHONY: clean + +ci: lint test +.PHONY: ci + +############################################################################### + +.DEFAULT_GOAL := ci diff --git a/vendor/github.com/nikoksr/notify/README.md b/vendor/github.com/nikoksr/notify/README.md new file mode 100644 index 000000000..813025aa5 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/README.md @@ -0,0 +1,132 @@ +
+notify logo + +[![codecov](https://codecov.io/gh/nikoksr/notify/branch/main/graph/badge.svg?token=QDON0KO2WV)](https://codecov.io/gh/nikoksr/notify) +[![Go Report Card](https://goreportcard.com/badge/github.com/nikoksr/notify)](https://goreportcard.com/report/github.com/nikoksr/notify) +[![Codacy Badge](https://app.codacy.com/project/badge/Grade/37fdff3c275c4a72a3a061f2d0ec5553)](https://www.codacy.com/gh/nikoksr/notify/dashboard?utm_source=github.com&utm_medium=referral&utm_content=nikoksr/notify&utm_campaign=Badge_Grade) +[![Maintainability](https://api.codeclimate.com/v1/badges/b3afd7bf115341995077/maintainability)](https://codeclimate.com/github/nikoksr/notify/maintainability) +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/nikoksr/notify) + +
+ +>

A dead simple Go library for sending notifications to various messaging services.

+ +> [!NOTE] +> **[July 2024 Update]**: Notify is back under active maintenance! [Read the full announcement here](https://github.com/nikoksr/notify/discussions/840). + +

+ +## About + +*Notify* was born out of my own need to have my API servers running in production be able to notify me when critical errors occur. Of course, _Notify_ can be used for any other purpose as well. The library is kept as simple as possible for quick integration and ease of use. + +## Disclaimer + +Any misuse of this library is your own liability and responsibility and cannot be attributed to the authors of this library. See [license](LICENSE) for more. + +Spamming through the use of this library **may get you permanently banned** on most supported platforms. + +Since Notify is highly dependent on the consistency of the supported external services and the corresponding latest client libraries, we cannot guarantee its reliability nor its consistency, and therefore you should probably not use or rely on Notify in critical scenarios. + +## Install + +```sh +go get -u github.com/nikoksr/notify +``` + +## Example usage + +```go +// Create a telegram service. Ignoring error for demo simplicity. +telegramService, _ := telegram.New("your_telegram_api_token") + +// Passing a telegram chat id as receiver for our messages. +// Basically where should our message be sent? +telegramService.AddReceivers(-1234567890) + +// Tell our notifier to use the telegram service. You can repeat the above process +// for as many services as you like and just tell the notifier to use them. +// Inspired by http middlewares used in higher level libraries. +notify.UseServices(telegramService) + +// Send a test message. +_ = notify.Send( + context.Background(), + "Subject/Title", + "The actual message - Hello, you awesome gophers! :)", +) +``` + +#### Recommendation + +In this example, we use the global `Send()` function. Similar to most logging libraries such as +[zap](https://github.com/uber-go/zap), we provide global functions for convenience. However, as with most logging +libraries, we also recommend avoiding the use of global functions as much as possible. Instead, use one of our versatile +constructor functions to create a new local `Notify` instance and pass it down the stream. + +## Contributing + +Yes, please! Contributions of all kinds are very welcome! Feel free to check our [open issues](https://github.com/nikoksr/notify/issues). Please also take a look at the [contribution guidelines](https://github.com/nikoksr/notify/blob/main/CONTRIBUTING.md). + +> Psst, don't forget to check the list of [missing services](https://github.com/nikoksr/notify/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aaffects%2Fservices+label%3A%22help+wanted%22+no%3Aassignee) waiting to be added by you or create [a new issue](https://github.com/nikoksr/notify/issues/new?assignees=&labels=affects%2Fservices%2C+good+first+issue%2C+hacktoberfest%2C+help+wanted%2C+type%2Fenhancement%2C+up+for+grabs&template=service-request.md&title=feat%28service%29%3A+Add+%5BSERVICE+NAME%5D+service) if you want a new service to be added. + +## Supported services + +> Click [here](https://github.com/nikoksr/notify/issues/new?assignees=&labels=affects%2Fservices%2C+good+first+issue%2C+hacktoberfest%2C+help+wanted%2C+type%2Fenhancement%2C+up+for+grabs&template=service-request.md&title=feat%28service%29%3A+Add+%5BSERVICE+NAME%5D+service) to request a missing service. + +| Service | Path | Credits | Status | +|-----------------------------------------------------------------------------------|------------------------------------------|-------------------------------------------------------------------------------------------------|:------------------:| +| [Amazon SES](https://aws.amazon.com/ses) | [service/amazonses](service/amazonses) | [aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2) | :heavy_check_mark: | +| [Amazon SNS](https://aws.amazon.com/sns) | [service/amazonsns](service/amazonsns) | [aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2) | :heavy_check_mark: | +| [Bark](https://apps.apple.com/us/app/bark-customed-notifications/id1403753865) | [service/bark](service/bark) | - | :heavy_check_mark: | +| [DingTalk](https://www.dingtalk.com) | [service/dinding](service/dingding) | [blinkbean/dingtalk](https://github.com/blinkbean/dingtalk) | :heavy_check_mark: | +| [Discord](https://discord.com) | [service/discord](service/discord) | [bwmarrin/discordgo](https://github.com/bwmarrin/discordgo) | :heavy_check_mark: | +| [Email](https://wikipedia.org/wiki/Email) | [service/mail](service/mail) | [jordan-wright/email](https://github.com/jordan-wright/email) | :heavy_check_mark: | +| [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) | [service/fcm](service/fcm) | [appleboy/go-fcm](https://github.com/appleboy/go-fcm) | :heavy_check_mark: | +| [Google Chat](https://workspace.google.com/intl/en/products/chat/) | [service/googlechat](service/googlechat) | [googleapis/google-api-go-client](https://google.golang.org/api/chat/v1) | :heavy_check_mark: | +| [HTTP](https://wikipedia.org/wiki/Hypertext_Transfer_Protocol) | [service/http](service/http) | - | :heavy_check_mark: | +| [Lark](https://www.larksuite.com/) | [service/lark](service/lark) | [go-lark/lark](https://github.com/go-lark/lark) | :heavy_check_mark: | +| [Line](https://line.me) | [service/line](service/line) | [line/line-bot-sdk-go](https://github.com/line/line-bot-sdk-go) | :heavy_check_mark: | +| [Line Notify](https://notify-bot.line.me) | [service/line](service/line) | [utahta/go-linenotify](https://github.com/utahta/go-linenotify) | :heavy_check_mark: | +| [Mailgun](https://www.mailgun.com) | [service/mailgun](service/mailgun) | [mailgun/mailgun-go](https://github.com/mailgun/mailgun-go) | :heavy_check_mark: | +| [Matrix](https://www.matrix.org) | [service/matrix](service/matrix) | [mautrix/go](https://github.com/mautrix/go) | :heavy_check_mark: | +| [Microsoft Teams](https://www.microsoft.com/microsoft-teams) | [service/msteams](service/msteams) | [atc0005/go-teams-notify](https://github.com/atc0005/go-teams-notify) | :heavy_check_mark: | +| [PagerDuty](https://www.pagerduty.com) | [service/pagerduty](service/pagerduty) | [PagerDuty/go-pagerduty](https://github.com/PagerDuty/go-pagerduty) | :heavy_check_mark: | +| [Plivo](https://www.plivo.com) | [service/plivo](service/plivo) | [plivo/plivo-go](https://github.com/plivo/plivo-go) | :heavy_check_mark: | +| [Pushover](https://pushover.net/) | [service/pushover](service/pushover) | [gregdel/pushover](https://github.com/gregdel/pushover) | :heavy_check_mark: | +| [Pushbullet](https://www.pushbullet.com) | [service/pushbullet](service/pushbullet) | [cschomburg/go-pushbullet](https://github.com/cschomburg/go-pushbullet) | :heavy_check_mark: | +| [Reddit](https://www.reddit.com) | [service/reddit](service/reddit) | [vartanbeno/go-reddit](https://github.com/vartanbeno/go-reddit) | :heavy_check_mark: | +| [RocketChat](https://rocket.chat) | [service/rocketchat](service/rocketchat) | [RocketChat/Rocket.Chat.Go.SDK](https://github.com/RocketChat/Rocket.Chat.Go.SDK) | :heavy_check_mark: | +| [SendGrid](https://sendgrid.com) | [service/sendgrid](service/sendgrid) | [sendgrid/sendgrid-go](https://github.com/sendgrid/sendgrid-go) | :heavy_check_mark: | +| [Slack](https://slack.com) | [service/slack](service/slack) | [slack-go/slack](https://github.com/slack-go/slack) | :heavy_check_mark: | +| [Syslog](https://wikipedia.org/wiki/Syslog) | [service/syslog](service/syslog) | [log/syslog](https://pkg.go.dev/log/syslog) | :heavy_check_mark: | +| [Telegram](https://telegram.org) | [service/telegram](service/telegram) | [go-telegram-bot-api/telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api) | :heavy_check_mark: | +| [TextMagic](https://www.textmagic.com) | [service/textmagic](service/textmagic) | [textmagic/textmagic-rest-go-v2](https://github.com/textmagic/textmagic-rest-go-v2) | :heavy_check_mark: | +| [Twilio](https://www.twilio.com/) | [service/twilio](service/twilio) | [kevinburke/twilio-go](https://github.com/kevinburke/twilio-go) | :heavy_check_mark: | +| [Twitter](https://twitter.com) | [service/twitter](service/twitter) | [drswork/go-twitter](https://github.com/drswork/go-twitter) | :heavy_check_mark: | +| [Viber](https://www.viber.com) | [service/viber](service/viber) | [mileusna/viber](https://github.com/mileusna/viber) | :heavy_check_mark: | +| [WeChat](https://www.wechat.com) | [service/wechat](service/wechat) | [silenceper/wechat](https://github.com/silenceper/wechat) | :heavy_check_mark: | +| [Webpush Notification](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) | [service/webpush](service/webpush) | [SherClockHolmes/webpush-go](https://github.com/SherClockHolmes/webpush-go/) | :heavy_check_mark: | +| [WhatsApp](https://www.whatsapp.com) | [service/whatsapp](service/whatsapp) | [Rhymen/go-whatsapp](https://github.com/Rhymen/go-whatsapp) | :x: | + +## Special Thanks + +### Maintainers + +- [@svaloumas](https://github.com/svaloumas) + +### Logo + +The [logo](https://github.com/MariaLetta/free-gophers-pack) was made by the amazing [MariaLetta](https://github.com/MariaLetta). + +## Support + +If you find this project useful, consider giving it a ⭐️! Your support helps bring more attention to the project, allowing us to enhance it even further. + +While you're here, feel free to check out my other work: + +- [nikoksr/konfetty](https://github.com/nikoksr/konfetty) - Zero-dependency, type-safe and powerful post-processing for your existing config solution in Go. diff --git a/vendor/github.com/nikoksr/notify/SECURITY.md b/vendor/github.com/nikoksr/notify/SECURITY.md new file mode 100644 index 000000000..4961617a7 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/SECURITY.md @@ -0,0 +1,9 @@ +# Security Policy + +## Supported Versions + +Only the last stable version at any given point. + +## Reporting a Vulnerability + +Vulnerabilities can be disclosed via email to contact@nikoksr.dev. diff --git a/vendor/github.com/nikoksr/notify/notify.go b/vendor/github.com/nikoksr/notify/notify.go new file mode 100644 index 000000000..abe6e2fb0 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/notify.go @@ -0,0 +1,98 @@ +package notify + +import ( + context "context" + "errors" +) + +// ErrSendNotification signals that the notifier failed to send a notification. +var ErrSendNotification = errors.New("send notification") + +// Notifier defines the behavior for notification services. +// +// The Send function simply sends a subject and a message string to the internal destination Notifier. +// +// E.g. for telegram.Telegram it sends the message to the specified group chat. +type Notifier interface { + Send(context.Context, string, string) error +} + +// Compile-time check to ensure Notify implements Notifier. +var _ Notifier = (*Notify)(nil) + +// Notify is the central struct for managing notification services and sending messages to them. +type Notify struct { + Disabled bool + notifiers []Notifier +} + +// Option is a function that can be used to configure a Notify instance. It is used by the WithOptions and +// NewWithOptions functions. It's a function because it's a bit more flexible than using a struct. The only required +// parameter is the Notify instance itself. +type Option func(*Notify) + +// Enable is an Option function that enables the Notify instance. This is the default behavior. +func Enable(n *Notify) { + if n != nil { + n.Disabled = false + } +} + +// Disable is an Option function that disables the Notify instance. It is enabled by default. +func Disable(n *Notify) { + if n != nil { + n.Disabled = true + } +} + +// WithOptions applies the given options to the Notify instance. If no options are provided, it returns the Notify +// instance unchanged. +func (n *Notify) WithOptions(options ...Option) *Notify { + if options == nil { + return n + } + + for _, option := range options { + if option != nil { + option(n) + } + } + + return n +} + +// NewWithOptions returns a new instance of Notify with the given options. If no options are provided, it returns a new +// Notify instance with default options. By default, the Notify instance is enabled. +func NewWithOptions(options ...Option) *Notify { + n := &Notify{ + Disabled: false, // Enabled by default. + notifiers: make([]Notifier, 0), // Avoid nil list. + } + + return n.WithOptions(options...) +} + +// New returns a new instance of Notify. It returns a new Notify instance with default options. By default, the Notify +// instance is enabled. +func New() *Notify { + return NewWithOptions() +} + +// NewWithServices returns a new instance of Notify with the given services. By default, the Notify instance is enabled. +// If no services are provided, it returns a new Notify instance with default options. +func NewWithServices(services ...Notifier) *Notify { + n := New() + n.UseServices(services...) + + return n +} + +// Create the package level Notify instance. +// +//nolint:gochecknoglobals // I agree with the linter, won't bother fixing this now, will be fixed in v2. +var std = New() + +// Default returns the standard Notify instance used by the package-level send function. +func Default() *Notify { + return std +} diff --git a/vendor/github.com/nikoksr/notify/renovate.json b/vendor/github.com/nikoksr/notify/renovate.json new file mode 100644 index 000000000..93578af22 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/renovate.json @@ -0,0 +1,13 @@ +{ + "extends": ["config:base"], + "assignees": ["nikoksr"], + "labels": ["type/deps"], + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + } + ], + "postUpdateOptions": ["gomodTidy"], + "dependencyDashboard": false +} diff --git a/vendor/github.com/nikoksr/notify/send.go b/vendor/github.com/nikoksr/notify/send.go new file mode 100644 index 000000000..d2e4ddf1e --- /dev/null +++ b/vendor/github.com/nikoksr/notify/send.go @@ -0,0 +1,46 @@ +package notify + +import ( + "context" + "errors" + + "golang.org/x/sync/errgroup" +) + +// send calls the underlying notification services to send the given subject and message to their respective endpoints. +func (n *Notify) send(ctx context.Context, subject, message string) error { + if n.Disabled { + return nil + } + if ctx == nil { + ctx = context.Background() + } + + var eg errgroup.Group + for _, service := range n.notifiers { + if service == nil { + continue + } + + eg.Go(func() error { + return service.Send(ctx, subject, message) + }) + } + + err := eg.Wait() + if err != nil { + err = errors.Join(ErrSendNotification, err) + } + + return err +} + +// Send calls the underlying notification services to send the given subject and message to their respective endpoints. +func (n *Notify) Send(ctx context.Context, subject, message string) error { + return n.send(ctx, subject, message) +} + +// Send calls the underlying notification services to send the given subject and message to their respective endpoints. +func Send(ctx context.Context, subject, message string) error { + return std.Send(ctx, subject, message) +} diff --git a/vendor/github.com/nikoksr/notify/service/discord/README.md b/vendor/github.com/nikoksr/notify/service/discord/README.md new file mode 100644 index 000000000..048172be9 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/discord/README.md @@ -0,0 +1,122 @@ +# Discord + +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/nikoksr/notify/service/discord) + +## Prerequisites + +To use the Discord notification service, you will need: + +- A Discord Bot Token or OAuth2 Token +- Channel IDs where you want to send messages + +You can create a Discord bot and get your token from the [Discord Developer Portal](https://discord.com/developers/applications). + +## Usage + +### Basic Usage + +```go +package main + +import ( + "context" + "log" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/discord" +) + +func main() { + discordSvc := discord.New() + + // Authenticate with your bot token + if err := discordSvc.AuthenticateWithBotToken("your-bot-token"); err != nil { + log.Fatalf("failed to authenticate: %s", err.Error()) + } + + // Add channel IDs to send messages to + discordSvc.AddReceivers("channel-id-1", "channel-id-2") + + notifier := notify.New() + notifier.UseServices(discordSvc) + + if err := notifier.Send(context.Background(), "Subject", "Message body"); err != nil { + log.Fatalf("failed to send notification: %s", err.Error()) + } + + log.Println("notification sent") +} +``` + +### OAuth2 Authentication + +You can also authenticate using an OAuth2 token: + +```go +discordSvc := discord.New() + +if err := discordSvc.AuthenticateWithOAuth2Token("your-oauth2-token"); err != nil { + log.Fatalf("failed to authenticate: %s", err.Error()) +} +``` + +### Advanced Configuration + +For advanced use cases such as proxy configuration or custom HTTP client settings, you can use `SetClient` with `DefaultSession`: + +```go +package main + +import ( + "context" + "log" + "net/http" + "net/url" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/discord" +) + +func main() { + // Create a custom HTTP client with proxy + proxyURL, _ := url.Parse("http://proxy.example.com:8080") + httpClient := &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyURL(proxyURL), + }, + } + + // Get a Discord session with default configuration + session := discord.DefaultSession() + session.Client = httpClient + + // Create Discord service and set the custom session + discordSvc := discord.New() + discordSvc.SetClient(session) + + // Authenticate - this will preserve the custom HTTP client + if err := discordSvc.AuthenticateWithBotToken("your-bot-token"); err != nil { + log.Fatalf("failed to authenticate: %s", err.Error()) + } + + discordSvc.AddReceivers("channel-id") + + notifier := notify.New() + notifier.UseServices(discordSvc) + + if err := notifier.Send(context.Background(), "Subject", "Message via proxy"); err != nil { + log.Fatalf("failed to send notification: %s", err.Error()) + } + + log.Println("notification sent") +} +``` + +The `SetClient` method allows full control over the Discord session configuration, including: + +- Custom HTTP client (for proxies, custom timeouts, etc.) +- Shard configuration +- Connection settings +- Rate limiting behavior + +Note that `DefaultSession()` allows you to configure the Discord session without importing the `discordgo` package directly. diff --git a/vendor/github.com/nikoksr/notify/service/discord/discord.go b/vendor/github.com/nikoksr/notify/service/discord/discord.go new file mode 100644 index 000000000..718638b56 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/discord/discord.go @@ -0,0 +1,156 @@ +package discord + +import ( + "context" + "fmt" + + "github.com/bwmarrin/discordgo" +) + +//go:generate mockery --name=discordSession --output=. --case=underscore --inpackage +type discordSession interface { + ChannelMessageSend(channelID string, content string, options ...discordgo.RequestOption) (*discordgo.Message, error) +} + +// Compile-time check to ensure that discordgo.Session implements the discordSession interface. +var _ discordSession = new(discordgo.Session) + +// Discord struct holds necessary data to communicate with the Discord API. +type Discord struct { + client discordSession + channelIDs []string +} + +// New returns a new instance of a Discord notification service. +// The instance is created with a default Discord session. For advanced configuration +// such as proxy support or custom timeouts, use SetClient to provide a custom session +// before calling the authentication methods. +func New() *Discord { + return &Discord{ + client: &discordgo.Session{}, + channelIDs: []string{}, + } +} + +// authenticate will configure authentication on the existing Discord session. +// If a custom session was set via SetClient, it preserves all custom configuration +// (HTTP client, proxy settings, etc.) while setting the authentication token. +func (d *Discord) authenticate(token string) error { + // If we have an existing session, configure it in-place + if d.client != nil { + if session, ok := d.client.(*discordgo.Session); ok { + session.Token = token + session.Identify.Token = token + session.Identify.Intents = discordgo.IntentsGuildMessageTyping + return nil + } + } + + // Fallback: create new session (only if client is nil or not a Session) + client, err := discordgo.New(token) + if err != nil { + return err + } + + client.Identify.Intents = discordgo.IntentsGuildMessageTyping + + d.client = client + + return nil +} + +// DefaultSession returns a new Discord session with default configuration. +// This allows configuring a custom session without importing the discordgo package. +// The session is created with Discord's standard defaults and can be customized before +// passing it to SetClient. +// +// Example - Configure proxy without importing discordgo: +// +// session := discord.DefaultSession() +// session.Client = &http.Client{ +// Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, +// } +// d := discord.New() +// d.SetClient(session) +// d.AuthenticateWithBotToken(token) +func DefaultSession() *discordgo.Session { + // Use discordgo.New with empty token to get proper defaults + session, _ := discordgo.New("") + return session +} + +// SetClient sets a custom Discord session, allowing full control over the +// session configuration including HTTP client, proxy settings, intents, and +// other Discord session options. +// +// This is useful for advanced use cases like proxy configuration or custom timeouts. +// After calling SetClient, you can still use the AuthenticateWith* methods to set +// the authentication token while preserving your custom configuration. +// +// Use DefaultSession() to get a session instance without importing discordgo. +// +// Example - Configure proxy, then authenticate: +// +// session := discord.DefaultSession() +// session.Client = &http.Client{ +// Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, +// } +// d := discord.New() +// d.SetClient(session) +// d.AuthenticateWithBotToken(token) // Preserves proxy configuration +func (d *Discord) SetClient(client *discordgo.Session) { + d.client = client +} + +// AuthenticateWithBotToken authenticates you as a bot to Discord via the given access token. +// For more info, see here: https://pkg.go.dev/github.com/bwmarrin/discordgo@v0.22.1#New +func (d *Discord) AuthenticateWithBotToken(token string) error { + token = parseBotToken(token) + + return d.authenticate(token) +} + +// AuthenticateWithOAuth2Token authenticates you to Discord via the given OAUTH2 token. +// For more info, see here: https://pkg.go.dev/github.com/bwmarrin/discordgo@v0.22.1#New +func (d *Discord) AuthenticateWithOAuth2Token(token string) error { + token = parseOAuthToken(token) + + return d.authenticate(token) +} + +// parseBotToken parses a regular token to a bot token that is understandable for discord. +// For more info, see here: https://pkg.go.dev/github.com/bwmarrin/discordgo@v0.22.1#New +func parseBotToken(token string) string { + return "Bot " + token +} + +// parseBotToken parses a regular token to a OAUTH2 token that is understandable for discord. +// For more info, see here: https://pkg.go.dev/github.com/bwmarrin/discordgo@v0.22.1#New +func parseOAuthToken(token string) string { + return "Bearer " + token +} + +// AddReceivers takes Discord channel IDs and adds them to the internal channel ID list. The Send method will send +// a given message to all those channels. +func (d *Discord) AddReceivers(channelIDs ...string) { + d.channelIDs = append(d.channelIDs, channelIDs...) +} + +// Send takes a message subject and a message body and sends them to all previously set chats. +func (d Discord) Send(ctx context.Context, subject, message string) error { + fullMessage := subject + "\n" + message // Treating subject as message title + + for _, channelID := range d.channelIDs { + select { + case <-ctx.Done(): + return ctx.Err() + default: + _, err := d.client.ChannelMessageSend(channelID, fullMessage) + if err != nil { + return fmt.Errorf("send message to Discord channel %q: %w", channelID, err) + } + } + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/service/discord/mock_discord_session.go b/vendor/github.com/nikoksr/notify/service/discord/mock_discord_session.go new file mode 100644 index 000000000..fda0766cf --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/discord/mock_discord_session.go @@ -0,0 +1,109 @@ +// Code generated by mockery v2.43.2. DO NOT EDIT. + +package discord + +import ( + discordgo "github.com/bwmarrin/discordgo" + mock "github.com/stretchr/testify/mock" +) + +// mockdiscordSession is an autogenerated mock type for the discordSession type +type mockdiscordSession struct { + mock.Mock +} + +type mockdiscordSession_Expecter struct { + mock *mock.Mock +} + +func (_m *mockdiscordSession) EXPECT() *mockdiscordSession_Expecter { + return &mockdiscordSession_Expecter{mock: &_m.Mock} +} + +// ChannelMessageSend provides a mock function with given fields: channelID, content, options +func (_m *mockdiscordSession) ChannelMessageSend(channelID string, content string, options ...discordgo.RequestOption) (*discordgo.Message, error) { + _va := make([]interface{}, len(options)) + for _i := range options { + _va[_i] = options[_i] + } + var _ca []interface{} + _ca = append(_ca, channelID, content) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + if len(ret) == 0 { + panic("no return value specified for ChannelMessageSend") + } + + var r0 *discordgo.Message + var r1 error + if rf, ok := ret.Get(0).(func(string, string, ...discordgo.RequestOption) (*discordgo.Message, error)); ok { + return rf(channelID, content, options...) + } + if rf, ok := ret.Get(0).(func(string, string, ...discordgo.RequestOption) *discordgo.Message); ok { + r0 = rf(channelID, content, options...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*discordgo.Message) + } + } + + if rf, ok := ret.Get(1).(func(string, string, ...discordgo.RequestOption) error); ok { + r1 = rf(channelID, content, options...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// mockdiscordSession_ChannelMessageSend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChannelMessageSend' +type mockdiscordSession_ChannelMessageSend_Call struct { + *mock.Call +} + +// ChannelMessageSend is a helper method to define mock.On call +// - channelID string +// - content string +// - options ...discordgo.RequestOption +func (_e *mockdiscordSession_Expecter) ChannelMessageSend(channelID interface{}, content interface{}, options ...interface{}) *mockdiscordSession_ChannelMessageSend_Call { + return &mockdiscordSession_ChannelMessageSend_Call{Call: _e.mock.On("ChannelMessageSend", + append([]interface{}{channelID, content}, options...)...)} +} + +func (_c *mockdiscordSession_ChannelMessageSend_Call) Run(run func(channelID string, content string, options ...discordgo.RequestOption)) *mockdiscordSession_ChannelMessageSend_Call { + _c.Call.Run(func(args mock.Arguments) { + variadicArgs := make([]discordgo.RequestOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(discordgo.RequestOption) + } + } + run(args[0].(string), args[1].(string), variadicArgs...) + }) + return _c +} + +func (_c *mockdiscordSession_ChannelMessageSend_Call) Return(_a0 *discordgo.Message, _a1 error) *mockdiscordSession_ChannelMessageSend_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *mockdiscordSession_ChannelMessageSend_Call) RunAndReturn(run func(string, string, ...discordgo.RequestOption) (*discordgo.Message, error)) *mockdiscordSession_ChannelMessageSend_Call { + _c.Call.Return(run) + return _c +} + +// newMockdiscordSession creates a new instance of mockdiscordSession. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newMockdiscordSession(t interface { + mock.TestingT + Cleanup(func()) +}) *mockdiscordSession { + mock := &mockdiscordSession{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/vendor/github.com/nikoksr/notify/service/http/README.md b/vendor/github.com/nikoksr/notify/service/http/README.md new file mode 100644 index 000000000..268acbc00 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/http/README.md @@ -0,0 +1,79 @@ +# Generic HTTP service + +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/nikoksr/notify/service/http) + +## Prerequisites + +Technically, you don't need any prerequisites to use this service. However, you will need an HTTP endpoint to send requests to. + +See our [Notify Test Server](https://github.com/nikoksr/notify-http-test) for a simple HTTP server that can be used for testing. + +## Usage + +```go +package main + +import ( + "context" + "log" + stdhttp "net/http" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/http" +) + +func main() { + // Create http service + httpService := http.New() + + // + // In the following example, we will send two requests to the same HTTP endpoint. This is meant to be used with + // Notify's test http server: https://github.com/nikoksr/notify-http-test. It supports multiple content-types on the + // same endpoint, to simplify testing. All you have to do is run `go run main.go` in the test server's directory and + // this example will work. + // So the following example should send two requests to the same endpoint, one with content-type application/json and + // one with content-type text/plain. The requests should be logged differently by the test server since we provide + // a custom payload builder func for the second webhook. + + // Add a default webhook; this uses application/json as content type and POST as request method. + httpService.AddReceiversURLs("http://localhost:8080") + + // Add a custom webhook; the build payload function is used to build the payload that will be sent to the receiver + // from the given subject and message. + httpService.AddReceivers(&http.Webhook{ + URL: "http://localhost:8080", + Header: stdhttp.Header{}, + ContentType: "text/plain", + Method: stdhttp.MethodPost, + BuildPayload: func(subject, message string) (payload any) { + return "[text/plain]: " + subject + " - " + message + }, + }) + + // + // NOTE: In case of an unsupported content type, we could provide a custom marshaller here. + // See http.Service.Serializer and http.defaultMarshaller.Marshal for details. + // + + // Add pre-send hook to log the request before it is sent. + httpService.PreSend(func(ctx context.Context, req *stdhttp.Request) error { + log.Printf("Sending request to %s", req.URL) + return nil + }) + + // Add post-send hook to log the response after it is received. + httpService.PostSend(func(ctx context.Context, req *stdhttp.Request, resp *stdhttp.Response) error { + log.Printf("Received response from %s", resp.Request.URL) + return nil + }) + + // Create the notifier and use the HTTP service + n := notify.NewWithServices(httpService) + + // Send a test message. + if err := n.Send(context.Background(), "Testing new features", "Notify's HTTP service is here."); err != nil { + log.Fatal(err) + } +} + +``` diff --git a/vendor/github.com/nikoksr/notify/service/http/doc.go b/vendor/github.com/nikoksr/notify/service/http/doc.go new file mode 100644 index 000000000..50e093800 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/http/doc.go @@ -0,0 +1,80 @@ +/* +Package http provides an HTTP service. It is used to send notifications to HTTP endpoints. The service is configured +with a list of webhooks. Each webhook contains the URL of the endpoint, the HTTP method to use, the content type of the +HTTP request and a function that builds the payload of the request. + +The service also allows to register pre and post send hooks. These hooks are called before and after the request is sent +to the receiver. The pre send hook can be used to modify the request before it is sent. The post send hook can be used +to modify the response after it is received. The hooks are called in the order they are registered. + +Usage: + + package main + + import ( + "context" + "log" + stdhttp "net/http" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/http" + ) + + func main() { + // Create http service + httpService := http.New() + + // + // In the following example, we will send two requests to the same HTTP endpoint. This is meant to be used + // with Notify's test http server: https://github.com/nikoksr/notify-http-test. It supports multiple + // content-types on the same endpoint, to simplify testing. All you have to do is run `go run main.go` in + // the test server's directory and + // this example will work. + // So the following example should send two requests to the same endpoint, one with content-type + // application/json and one with content-type text/plain. The requests should be logged differently by the + // test server since we provide + // a custom payload builder func for the second webhook. + + // Add a default webhook; this uses application/json as content type and POST as request method. + httpService.AddReceiversURLs("http://localhost:8080") + + // Add a custom webhook; the build payload function is used to build the payload that will be sent to the + // receiver + // from the given subject and message. + httpService.AddReceivers(&http.Webhook{ + URL: "http://localhost:8080", + Header: stdhttp.Header{}, + ContentType: "text/plain", + Method: stdhttp.MethodPost, + BuildPayload: func(subject, message string) (payload any) { + return "[text/plain]: " + subject + " - " + message + }, + }) + + // + // NOTE: In case of an unsupported content type, we could provide a custom marshaller here. + // See http.Service.Serializer and http.defaultMarshaller.Marshal for details. + // + + // Add pre-send hook to log the request before it is sent. + httpService.PreSend(func(ctx context.Context, req *stdhttp.Request) error { + log.Printf("Sending request to %s", req.URL) + return nil + }) + + // Add post-send hook to log the response after it is received. + httpService.PostSend(func(ctx context.Context, req *stdhttp.Request, resp *stdhttp.Response) error { + log.Printf("Received response from %s", resp.Request.URL) + return nil + }) + + // Create the notifier and use the HTTP service + n := notify.NewWithServices(httpService) + + // Send a test message. + if err := n.Send(context.Background(), "Testing new features", "Notify's HTTP service is here."); err != nil { + log.Fatal(err) + } + } +*/ +package http diff --git a/vendor/github.com/nikoksr/notify/service/http/http.go b/vendor/github.com/nikoksr/notify/service/http/http.go new file mode 100644 index 000000000..e1215d4b9 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/http/http.go @@ -0,0 +1,281 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/nikoksr/notify" +) + +type ( + // PreSendHookFn defines a function signature for a pre-send hook. + PreSendHookFn func(req *http.Request) error + + // PostSendHookFn defines a function signature for a post-send hook. + PostSendHookFn func(req *http.Request, resp *http.Response) error + + // BuildPayloadFn defines a function signature for a function that builds a payload. + BuildPayloadFn func(subject, message string) (payload any) + + // Serializer is used to serialize the payload to a byte slice. + Serializer interface { + Marshal(contentType string, payload any) (payloadRaw []byte, err error) + } + + // Webhook represents a single webhook receiver. It contains all the information needed to send a valid request to + // the receiver. The BuildPayload function is used to build the payload that will be sent to the receiver from the + // given subject and message. + Webhook struct { + ContentType string + Header http.Header + Method string + URL string + BuildPayload BuildPayloadFn + } + + // Service is the main struct of this package. It contains all the information needed to send notifications to a + // list of receivers. The receivers are represented by Webhooks and are expected to be valid HTTP endpoints. The + // Service also allows. + Service struct { + client *http.Client + webhooks []*Webhook + preSendHooks []PreSendHookFn + postSendHooks []PostSendHookFn + Serializer Serializer + } +) + +const ( + defaultUserAgent = "notify/" + notify.Version + defaultContentType = "application/json; charset=utf-8" + defaultRequestMethod = http.MethodPost + + // Defining these as constants for testing purposes. + defaultSubjectKey = "subject" + defaultMessageKey = "message" +) + +type defaultMarshaller struct{} + +// Marshal takes a payload and serializes it to a byte slice. The content type is used to determine the serialization +// format. If the content type is not supported, an error is returned. The default marshaller supports the following +// content types: application/json, text/plain. +// NOTE: should we expand the default marshaller to support more content types? +func (defaultMarshaller) Marshal(contentType string, payload any) ([]byte, error) { + var out []byte + var err error + + switch { + case strings.HasPrefix(contentType, "application/json"): + out, err = json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("marshal payload: %w", err) + } + case strings.HasPrefix(contentType, "text/plain"): + str, ok := payload.(string) + if !ok { + return nil, fmt.Errorf("payload was expected to be of type string, got %T", payload) + } + out = []byte(str) + default: + return nil, errors.New("unsupported content type") + } + + return out, nil +} + +// buildDefaultPayload is the default payload builder. It builds a payload that is a map with the keys "subject" and +// "message". +func buildDefaultPayload(subject, message string) any { + return map[string]string{ + defaultSubjectKey: subject, + defaultMessageKey: message, + } +} + +// New returns a new instance of a Service notification service. Parameter 'tag' is used as a log prefix and may be left +// empty, it has a fallback value. +func New() *Service { + return &Service{ + client: http.DefaultClient, + webhooks: []*Webhook{}, + preSendHooks: []PreSendHookFn{}, + postSendHooks: []PostSendHookFn{}, + Serializer: defaultMarshaller{}, + } +} + +func newWebhook(url string) *Webhook { + return &Webhook{ + ContentType: defaultContentType, + Header: http.Header{}, + Method: defaultRequestMethod, + URL: url, + BuildPayload: buildDefaultPayload, + } +} + +// String returns a string representation of the webhook. It implements the fmt.Stringer interface. +func (w *Webhook) String() string { + if w == nil { + return "" + } + + return strings.TrimSpace(fmt.Sprintf("%s %s %s", strings.ToUpper(w.Method), w.URL, w.ContentType)) +} + +// AddReceivers accepts a list of Webhooks and adds them as receivers. The Webhooks are expected to be valid HTTP +// endpoints. +func (s *Service) AddReceivers(webhooks ...*Webhook) { + s.webhooks = append(s.webhooks, webhooks...) +} + +// AddReceiversURLs accepts a list of URLs and adds them as receivers. Internally it converts the URLs to Webhooks by +// using the default content-type ("application/json") and request method ("POST"). +func (s *Service) AddReceiversURLs(urls ...string) { + for _, url := range urls { + s.AddReceivers(newWebhook(url)) + } +} + +// WithClient sets the http client to be used for sending requests. Calling this method is optional, the default client +// will be used if this method is not called. +func (s *Service) WithClient(client *http.Client) { + if client != nil { + s.client = client + } +} + +// doPreSendHooks executes all the pre-send hooks. If any of the hooks returns an error, the execution is stopped and +// the error is returned. +func (s *Service) doPreSendHooks(req *http.Request) error { + for _, hook := range s.preSendHooks { + if err := hook(req); err != nil { + return err + } + } + + return nil +} + +// doPostSendHooks executes all the post-send hooks. If any of the hooks returns an error, the execution is stopped and +// the error is returned. +func (s *Service) doPostSendHooks(req *http.Request, resp *http.Response) error { + for _, hook := range s.postSendHooks { + if err := hook(req, resp); err != nil { + return err + } + } + + return nil +} + +// PreSend adds a pre-send hook to the service. The hook will be executed before sending a request to a receiver. +func (s *Service) PreSend(hook PreSendHookFn) { + s.preSendHooks = append(s.preSendHooks, hook) +} + +// PostSend adds a post-send hook to the service. The hook will be executed after sending a request to a receiver. +func (s *Service) PostSend(hook PostSendHookFn) { + s.postSendHooks = append(s.postSendHooks, hook) +} + +// newRequest creates a new http request with the given method, content-type, url and payload. Request created by this +// function will usually be passed to the Service.do method. +func newRequest(ctx context.Context, hook *Webhook, payload io.Reader) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, hook.Method, hook.URL, payload) + if err != nil { + return nil, err + } + + req.Header = hook.Header + + if req.Header.Get("User-Agent") == "" { + req.Header.Set("User-Agent", defaultUserAgent) + } + if req.Header.Get("Content-Type") == "" { + req.Header.Set("Content-Type", hook.ContentType) + } + + return req, nil +} + +// do sends the given request and returns an error if the request failed. A failed request gets identified by either +// an unsuccessful status code or a non-nil error. The given request is expected to be valid and was usually created +// by the newRequest function. +func (s *Service) do(req *http.Request) error { + // Execute all pre-send hooks in order. + if err := s.doPreSendHooks(req); err != nil { + return fmt.Errorf("pre-send hooks: %w", err) + } + + // Actually send the HTTP request. + resp, err := s.client.Do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + + // Execute all post-send hooks in order. + if err = s.doPostSendHooks(req, resp); err != nil { + return fmt.Errorf("post-send hooks: %w", err) + } + + // Check if response code is 2xx. Should this be configurable? + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("responded with status code: %d", resp.StatusCode) + } + + return nil +} + +// send is a helper method that sends a message to a single webhook. It wraps the core logic of the Send method, which +// is creating a new request for the given webhook and sending it. +func (s *Service) send(ctx context.Context, webhook *Webhook, payload []byte) error { + // Create a new HTTP request for the given webhook. + req, err := newRequest(ctx, webhook, bytes.NewReader(payload)) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + defer func() { _ = req.Body.Close() }() + + return s.do(req) +} + +// Send takes a message and sends it to all webhooks. +func (s *Service) Send(ctx context.Context, subject, message string) error { + // Send message to all webhooks. + for _, webhook := range s.webhooks { + select { + case <-ctx.Done(): + return ctx.Err() + default: + // Skip webhook if it is nil. + if webhook == nil { + continue + } + + // Build the payload for the current webhook. + payload := webhook.BuildPayload(subject, message) + + // Marshal the message into a payload. + payloadRaw, err := s.Serializer.Marshal(webhook.ContentType, payload) + if err != nil { + return fmt.Errorf("marshal payload: %w", err) + } + + // Send the payload to the webhook. + if err = s.send(ctx, webhook, payloadRaw); err != nil { + return fmt.Errorf("send to %s: %w", webhook.URL, err) + } + } + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/service/msteams/mock_teams_client.go b/vendor/github.com/nikoksr/notify/service/msteams/mock_teams_client.go new file mode 100644 index 000000000..d1483498f --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/msteams/mock_teams_client.go @@ -0,0 +1,230 @@ +// Code generated by mockery v2.50.4. DO NOT EDIT. + +package msteams + +import ( + context "context" + http "net/http" + + goteamsnotify "github.com/atc0005/go-teams-notify/v2" + mock "github.com/stretchr/testify/mock" +) + +// mockteamsClient is an autogenerated mock type for the teamsClient type +type mockteamsClient struct { + mock.Mock +} + +type mockteamsClient_Expecter struct { + mock *mock.Mock +} + +func (_m *mockteamsClient) EXPECT() *mockteamsClient_Expecter { + return &mockteamsClient_Expecter{mock: &_m.Mock} +} + +// SendWithContext provides a mock function with given fields: ctx, webhookURL, message +func (_m *mockteamsClient) SendWithContext(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage) error { + ret := _m.Called(ctx, webhookURL, message) + + if len(ret) == 0 { + panic("no return value specified for SendWithContext") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string, goteamsnotify.TeamsMessage) error); ok { + r0 = rf(ctx, webhookURL, message) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// mockteamsClient_SendWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendWithContext' +type mockteamsClient_SendWithContext_Call struct { + *mock.Call +} + +// SendWithContext is a helper method to define mock.On call +// - ctx context.Context +// - webhookURL string +// - message goteamsnotify.TeamsMessage +func (_e *mockteamsClient_Expecter) SendWithContext(ctx interface{}, webhookURL interface{}, message interface{}) *mockteamsClient_SendWithContext_Call { + return &mockteamsClient_SendWithContext_Call{Call: _e.mock.On("SendWithContext", ctx, webhookURL, message)} +} + +func (_c *mockteamsClient_SendWithContext_Call) Run(run func(ctx context.Context, webhookURL string, message goteamsnotify.TeamsMessage)) *mockteamsClient_SendWithContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context), args[1].(string), args[2].(goteamsnotify.TeamsMessage)) + }) + return _c +} + +func (_c *mockteamsClient_SendWithContext_Call) Return(_a0 error) *mockteamsClient_SendWithContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *mockteamsClient_SendWithContext_Call) RunAndReturn(run func(context.Context, string, goteamsnotify.TeamsMessage) error) *mockteamsClient_SendWithContext_Call { + _c.Call.Return(run) + return _c +} + +// SetHTTPClient provides a mock function with given fields: httpClient +func (_m *mockteamsClient) SetHTTPClient(httpClient *http.Client) *goteamsnotify.TeamsClient { + ret := _m.Called(httpClient) + + if len(ret) == 0 { + panic("no return value specified for SetHTTPClient") + } + + var r0 *goteamsnotify.TeamsClient + if rf, ok := ret.Get(0).(func(*http.Client) *goteamsnotify.TeamsClient); ok { + r0 = rf(httpClient) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*goteamsnotify.TeamsClient) + } + } + + return r0 +} + +// mockteamsClient_SetHTTPClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetHTTPClient' +type mockteamsClient_SetHTTPClient_Call struct { + *mock.Call +} + +// SetHTTPClient is a helper method to define mock.On call +// - httpClient *http.Client +func (_e *mockteamsClient_Expecter) SetHTTPClient(httpClient interface{}) *mockteamsClient_SetHTTPClient_Call { + return &mockteamsClient_SetHTTPClient_Call{Call: _e.mock.On("SetHTTPClient", httpClient)} +} + +func (_c *mockteamsClient_SetHTTPClient_Call) Run(run func(httpClient *http.Client)) *mockteamsClient_SetHTTPClient_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(*http.Client)) + }) + return _c +} + +func (_c *mockteamsClient_SetHTTPClient_Call) Return(_a0 *goteamsnotify.TeamsClient) *mockteamsClient_SetHTTPClient_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *mockteamsClient_SetHTTPClient_Call) RunAndReturn(run func(*http.Client) *goteamsnotify.TeamsClient) *mockteamsClient_SetHTTPClient_Call { + _c.Call.Return(run) + return _c +} + +// SetUserAgent provides a mock function with given fields: userAgent +func (_m *mockteamsClient) SetUserAgent(userAgent string) *goteamsnotify.TeamsClient { + ret := _m.Called(userAgent) + + if len(ret) == 0 { + panic("no return value specified for SetUserAgent") + } + + var r0 *goteamsnotify.TeamsClient + if rf, ok := ret.Get(0).(func(string) *goteamsnotify.TeamsClient); ok { + r0 = rf(userAgent) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*goteamsnotify.TeamsClient) + } + } + + return r0 +} + +// mockteamsClient_SetUserAgent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetUserAgent' +type mockteamsClient_SetUserAgent_Call struct { + *mock.Call +} + +// SetUserAgent is a helper method to define mock.On call +// - userAgent string +func (_e *mockteamsClient_Expecter) SetUserAgent(userAgent interface{}) *mockteamsClient_SetUserAgent_Call { + return &mockteamsClient_SetUserAgent_Call{Call: _e.mock.On("SetUserAgent", userAgent)} +} + +func (_c *mockteamsClient_SetUserAgent_Call) Run(run func(userAgent string)) *mockteamsClient_SetUserAgent_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(string)) + }) + return _c +} + +func (_c *mockteamsClient_SetUserAgent_Call) Return(_a0 *goteamsnotify.TeamsClient) *mockteamsClient_SetUserAgent_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *mockteamsClient_SetUserAgent_Call) RunAndReturn(run func(string) *goteamsnotify.TeamsClient) *mockteamsClient_SetUserAgent_Call { + _c.Call.Return(run) + return _c +} + +// SkipWebhookURLValidationOnSend provides a mock function with given fields: skip +func (_m *mockteamsClient) SkipWebhookURLValidationOnSend(skip bool) *goteamsnotify.TeamsClient { + ret := _m.Called(skip) + + if len(ret) == 0 { + panic("no return value specified for SkipWebhookURLValidationOnSend") + } + + var r0 *goteamsnotify.TeamsClient + if rf, ok := ret.Get(0).(func(bool) *goteamsnotify.TeamsClient); ok { + r0 = rf(skip) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*goteamsnotify.TeamsClient) + } + } + + return r0 +} + +// mockteamsClient_SkipWebhookURLValidationOnSend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SkipWebhookURLValidationOnSend' +type mockteamsClient_SkipWebhookURLValidationOnSend_Call struct { + *mock.Call +} + +// SkipWebhookURLValidationOnSend is a helper method to define mock.On call +// - skip bool +func (_e *mockteamsClient_Expecter) SkipWebhookURLValidationOnSend(skip interface{}) *mockteamsClient_SkipWebhookURLValidationOnSend_Call { + return &mockteamsClient_SkipWebhookURLValidationOnSend_Call{Call: _e.mock.On("SkipWebhookURLValidationOnSend", skip)} +} + +func (_c *mockteamsClient_SkipWebhookURLValidationOnSend_Call) Run(run func(skip bool)) *mockteamsClient_SkipWebhookURLValidationOnSend_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(bool)) + }) + return _c +} + +func (_c *mockteamsClient_SkipWebhookURLValidationOnSend_Call) Return(_a0 *goteamsnotify.TeamsClient) *mockteamsClient_SkipWebhookURLValidationOnSend_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *mockteamsClient_SkipWebhookURLValidationOnSend_Call) RunAndReturn(run func(bool) *goteamsnotify.TeamsClient) *mockteamsClient_SkipWebhookURLValidationOnSend_Call { + _c.Call.Return(run) + return _c +} + +// newMockteamsClient creates a new instance of mockteamsClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newMockteamsClient(t interface { + mock.TestingT + Cleanup(func()) +}) *mockteamsClient { + mock := &mockteamsClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/vendor/github.com/nikoksr/notify/service/msteams/ms_teams.go b/vendor/github.com/nikoksr/notify/service/msteams/ms_teams.go new file mode 100644 index 000000000..b13c64fa2 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/msteams/ms_teams.go @@ -0,0 +1,102 @@ +package msteams + +import ( + "context" + "fmt" + "net/http" + + teams "github.com/atc0005/go-teams-notify/v2" + "github.com/atc0005/go-teams-notify/v2/adaptivecard" +) + +type teamsClient interface { + // https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2#TeamsClient.SendWithContext + SendWithContext(ctx context.Context, webhookURL string, message teams.TeamsMessage) error + // https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2#TeamsClient.SkipWebhookURLValidationOnSend + SkipWebhookURLValidationOnSend(skip bool) *teams.TeamsClient + // https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2#TeamsClient.SetHTTPClient + SetHTTPClient(httpClient *http.Client) *teams.TeamsClient + // https://pkg.go.dev/github.com/atc0005/go-teams-notify/v2#TeamsClient.SetUserAgent + SetUserAgent(userAgent string) *teams.TeamsClient +} + +// Compile-time check to ensure that teams.Client implements the teamsClient interface. +var _ teamsClient = teams.NewTeamsClient() + +// MSTeams struct holds necessary data to communicate with the MSTeams API. +type MSTeams struct { + client teamsClient + webHooks []string + + wrapText bool +} + +// New returns a new instance of a MSTeams notification service. +// For more information about telegram api token: +// +// -> https://github.com/atc0005/go-teams-notify#example-basic +func New() *MSTeams { + client := teams.NewTeamsClient() + + m := &MSTeams{ + client: client, + webHooks: []string{}, + } + + return m +} + +// DisableWebhookValidation disables the validation of webhook URLs, including the validation of known prefixes so that +// custom/private webhook URL endpoints can be used (e.g., testing purposes). +// For more information about telegram api token: +// +// -> https://github.com/atc0005/go-teams-notify#example-disable-webhook-url-prefix-validation +func (m *MSTeams) DisableWebhookValidation() { + m.client.SkipWebhookURLValidationOnSend(true) +} + +// WithWrapText sets the wrapText field to the provided value. This is disabled by default. +func (m *MSTeams) WithWrapText(wrapText bool) { + m.wrapText = wrapText +} + +// AddReceivers takes MSTeams channel web-hooks and adds them to the internal web-hook list. The Send method will send +// a given message to all those chats. +func (m *MSTeams) AddReceivers(webHooks ...string) { + m.webHooks = append(m.webHooks, webHooks...) +} + +// SetUseragent allows the user to set a custom user agent. +func (m *MSTeams) SetUseragent(userAgent string) { + m.client = m.client.SetUserAgent(userAgent) +} + +// SetHTTPClient allows the user to set a custom http client. +func (m *MSTeams) SetHTTPClient(httpClient *http.Client) { + m.client = m.client.SetHTTPClient(httpClient) +} + +// Send accepts a subject and a message body and sends them to all previously specified channels. Message body supports +// html as markup language. +// For more information about telegram api token: +// +// -> https://github.com/atc0005/go-teams-notify#example-basic +func (m MSTeams) Send(ctx context.Context, subject, message string) error { + msg, err := adaptivecard.NewSimpleMessage(message, subject, m.wrapText) + if err != nil { + return fmt.Errorf("create message: %w", err) + } + + for _, webHook := range m.webHooks { + select { + case <-ctx.Done(): + return ctx.Err() + default: + if err = m.client.SendWithContext(ctx, webHook, msg); err != nil { + return fmt.Errorf("send message to channel %q: %w", webHook, err) + } + } + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/service/slack/mock_slack_client.go b/vendor/github.com/nikoksr/notify/service/slack/mock_slack_client.go new file mode 100644 index 000000000..7ad1f80c2 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/slack/mock_slack_client.go @@ -0,0 +1,116 @@ +// Code generated by mockery v2.43.2. DO NOT EDIT. + +package slack + +import ( + context "context" + + slack_goslack "github.com/slack-go/slack" + mock "github.com/stretchr/testify/mock" +) + +// mockslackClient is an autogenerated mock type for the slackClient type +type mockslackClient struct { + mock.Mock +} + +type mockslackClient_Expecter struct { + mock *mock.Mock +} + +func (_m *mockslackClient) EXPECT() *mockslackClient_Expecter { + return &mockslackClient_Expecter{mock: &_m.Mock} +} + +// PostMessageContext provides a mock function with given fields: ctx, channelID, options +func (_m *mockslackClient) PostMessageContext(ctx context.Context, channelID string, options ...slack_goslack.MsgOption) (string, string, error) { + _va := make([]interface{}, len(options)) + for _i := range options { + _va[_i] = options[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, channelID) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + if len(ret) == 0 { + panic("no return value specified for PostMessageContext") + } + + var r0 string + var r1 string + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string, ...slack_goslack.MsgOption) (string, string, error)); ok { + return rf(ctx, channelID, options...) + } + if rf, ok := ret.Get(0).(func(context.Context, string, ...slack_goslack.MsgOption) string); ok { + r0 = rf(ctx, channelID, options...) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, ...slack_goslack.MsgOption) string); ok { + r1 = rf(ctx, channelID, options...) + } else { + r1 = ret.Get(1).(string) + } + + if rf, ok := ret.Get(2).(func(context.Context, string, ...slack_goslack.MsgOption) error); ok { + r2 = rf(ctx, channelID, options...) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// mockslackClient_PostMessageContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PostMessageContext' +type mockslackClient_PostMessageContext_Call struct { + *mock.Call +} + +// PostMessageContext is a helper method to define mock.On call +// - ctx context.Context +// - channelID string +// - options ...slack_goslack.MsgOption +func (_e *mockslackClient_Expecter) PostMessageContext(ctx interface{}, channelID interface{}, options ...interface{}) *mockslackClient_PostMessageContext_Call { + return &mockslackClient_PostMessageContext_Call{Call: _e.mock.On("PostMessageContext", + append([]interface{}{ctx, channelID}, options...)...)} +} + +func (_c *mockslackClient_PostMessageContext_Call) Run(run func(ctx context.Context, channelID string, options ...slack_goslack.MsgOption)) *mockslackClient_PostMessageContext_Call { + _c.Call.Run(func(args mock.Arguments) { + variadicArgs := make([]slack_goslack.MsgOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(slack_goslack.MsgOption) + } + } + run(args[0].(context.Context), args[1].(string), variadicArgs...) + }) + return _c +} + +func (_c *mockslackClient_PostMessageContext_Call) Return(_a0 string, _a1 string, _a2 error) *mockslackClient_PostMessageContext_Call { + _c.Call.Return(_a0, _a1, _a2) + return _c +} + +func (_c *mockslackClient_PostMessageContext_Call) RunAndReturn(run func(context.Context, string, ...slack_goslack.MsgOption) (string, string, error)) *mockslackClient_PostMessageContext_Call { + _c.Call.Return(run) + return _c +} + +// newMockslackClient creates a new instance of mockslackClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newMockslackClient(t interface { + mock.TestingT + Cleanup(func()) +}) *mockslackClient { + mock := &mockslackClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/vendor/github.com/nikoksr/notify/service/slack/slack.go b/vendor/github.com/nikoksr/notify/service/slack/slack.go new file mode 100644 index 000000000..4b9579c67 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/slack/slack.go @@ -0,0 +1,67 @@ +package slack + +import ( + "context" + "fmt" + + "github.com/slack-go/slack" +) + +type slackClient interface { + PostMessageContext(ctx context.Context, channelID string, options ...slack.MsgOption) (string, string, error) +} + +// Compile-time check to ensure that slack.Client implements the slackClient interface. +var _ slackClient = new(slack.Client) + +// Slack struct holds necessary data to communicate with the Slack API. +type Slack struct { + client slackClient + channelIDs []string +} + +// New returns a new instance of a Slack notification service. +// For more information about slack api token: +// +// -> https://pkg.go.dev/github.com/slack-go/slack#New +func New(apiToken string) *Slack { + client := slack.New(apiToken) + + s := &Slack{ + client: client, + channelIDs: []string{}, + } + + return s +} + +// AddReceivers takes Slack channel IDs and adds them to the internal channel ID list. The Send method will send +// a given message to all those channels. +func (s *Slack) AddReceivers(channelIDs ...string) { + s.channelIDs = append(s.channelIDs, channelIDs...) +} + +// Send takes a message subject and a message body and sends them to all previously set channels. +// you will need a slack app with the chat:write.public and chat:write permissions. +// see https://api.slack.com/ +func (s Slack) Send(ctx context.Context, subject, message string) error { + fullMessage := subject + "\n" + message // Treating subject as message title + + for _, channelID := range s.channelIDs { + select { + case <-ctx.Done(): + return ctx.Err() + default: + _, _, err := s.client.PostMessageContext( + ctx, + channelID, + slack.MsgOptionText(fullMessage, false), + ) + if err != nil { + return fmt.Errorf("send message to channel %q: %w", channelID, err) + } + } + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/service/slack/usage.md b/vendor/github.com/nikoksr/notify/service/slack/usage.md new file mode 100644 index 000000000..f865310ec --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/slack/usage.md @@ -0,0 +1,62 @@ +# Slack Usage + +Ensure that you have already navigated to your GOPATH and installed the following packages: + +* `go get -u github.com/nikoksr/notify` +* `go get github.com/slack-go/slack` - You might need this one too + +## Steps for Slack App + +These are general and very high level instructions + +1. Create a new Slack App +2. Give your bot/app the following OAuth permission scopes: `chat:write`, `chat:write.public` +3. Copy your *Bot User OAuth Access Token* for usage below +4. Copy the *Channel ID* of the channel you want to post a message to. You can grab the *Channel ID* by right clicking a channel and selecting `copy link`. Your *Channel ID* will be in that link. +5. Now you should be good to use the code below + +## Sample Code + +```go +package main + +import ( + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/slack" +) + +func main() { + + notifier := notify.New() + + // Provide your Slack OAuth Access Token + slackService := slack.New("OAUTH_TOKEN") + + // Passing a Slack channel id as receiver for our messages. + // Where to send our messages. + slackService.AddReceivers("CHANNEL_ID") + + // Tell our notifier to use the Slack service. You can repeat the above process + // for as many services as you like and just tell the notifier to use them. + notifier.UseServices(slackService) + + // Send a message + _ = notifier.Send( + context.Background(), + "Hello :wave:\n", + "I am a bot written in Go!", + ) + + // Code isn't working and need to debug? Use this code below: + // x := notifier.Send( + // context.Background(), + // "Hello :wave:\n", + // "I am a bot written in Go!", + // ) + + // if x != nil { + // fmt.Println(x) + // } + +} +``` diff --git a/vendor/github.com/nikoksr/notify/service/telegram/telegram.go b/vendor/github.com/nikoksr/notify/service/telegram/telegram.go new file mode 100644 index 000000000..4a0c2e5ea --- /dev/null +++ b/vendor/github.com/nikoksr/notify/service/telegram/telegram.go @@ -0,0 +1,87 @@ +package telegram + +import ( + "context" + "fmt" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" +) + +const ( + ModeMarkdown = tgbotapi.ModeMarkdown + ModeHTML = tgbotapi.ModeHTML +) + +// HTML is the default mode. +// +//nolint:gochecknoglobals // I agree with the linter, won't bother fixing this now, will be fixed in v2. +var parseMode = ModeHTML + +// Telegram struct holds necessary data to communicate with the Telegram API. +type Telegram struct { + client *tgbotapi.BotAPI + chatIDs []int64 +} + +// New returns a new instance of a Telegram notification service. +// For more information about telegram api token: +// +// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPI +func New(apiToken string) (*Telegram, error) { + client, err := tgbotapi.NewBotAPI(apiToken) + if err != nil { + return nil, err + } + + t := &Telegram{ + client: client, + chatIDs: []int64{}, + } + + return t, nil +} + +// SetClient set a new custom BotAPI instance. +// For example allowing you to use NewBotAPIWithClient: +// +// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#NewBotAPIWithClient +func (t *Telegram) SetClient(client *tgbotapi.BotAPI) { + t.client = client +} + +// SetParseMode sets the parse mode for the message body. +// For more information about telegram constants: +// +// -> https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api#pkg-constants +func (t *Telegram) SetParseMode(mode string) { + parseMode = mode +} + +// AddReceivers takes Telegram chat IDs and adds them to the internal chat ID list. The Send method will send +// a given message to all those chats. +func (t *Telegram) AddReceivers(chatIDs ...int64) { + t.chatIDs = append(t.chatIDs, chatIDs...) +} + +// Send takes a message subject and a message body and sends them to all previously set chats. Message body supports +// html as markup language. +func (t Telegram) Send(ctx context.Context, subject, message string) error { + fullMessage := subject + "\n" + message // Treating subject as message title + + msg := tgbotapi.NewMessage(0, fullMessage) + msg.ParseMode = parseMode + + for _, chatID := range t.chatIDs { + select { + case <-ctx.Done(): + return ctx.Err() + default: + msg.ChatID = chatID + if _, err := t.client.Send(msg); err != nil { + return fmt.Errorf("send message to chat %d: %w", chatID, err) + } + } + } + + return nil +} diff --git a/vendor/github.com/nikoksr/notify/use.go b/vendor/github.com/nikoksr/notify/use.go new file mode 100644 index 000000000..d54a5a2c6 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/use.go @@ -0,0 +1,25 @@ +package notify + +// useService adds a given service to the Notifier's services list. +func (n *Notify) useService(service Notifier) { + if service != nil { + n.notifiers = append(n.notifiers, service) + } +} + +// useServices adds the given service(s) to the Notifier's services list. +func (n *Notify) useServices(services ...Notifier) { + for _, s := range services { + n.useService(s) + } +} + +// UseServices adds the given service(s) to the Notifier's services list. +func (n *Notify) UseServices(services ...Notifier) { + n.useServices(services...) +} + +// UseServices adds the given service(s) to the Notifier's services list. +func UseServices(services ...Notifier) { + std.UseServices(services...) +} diff --git a/vendor/github.com/nikoksr/notify/version.go b/vendor/github.com/nikoksr/notify/version.go new file mode 100644 index 000000000..0f3796f56 --- /dev/null +++ b/vendor/github.com/nikoksr/notify/version.go @@ -0,0 +1,4 @@ +package notify + +// Version is the current version of the library. +const Version = "unknown" diff --git a/vendor/github.com/slack-go/slack/.gitignore b/vendor/github.com/slack-go/slack/.gitignore new file mode 100644 index 000000000..9b3903cd2 --- /dev/null +++ b/vendor/github.com/slack-go/slack/.gitignore @@ -0,0 +1,5 @@ +*.test +*~ +.idea/ +/vendor/ +.env* diff --git a/vendor/github.com/slack-go/slack/.golangci.yml b/vendor/github.com/slack-go/slack/.golangci.yml new file mode 100644 index 000000000..0ef0f87ec --- /dev/null +++ b/vendor/github.com/slack-go/slack/.golangci.yml @@ -0,0 +1,35 @@ +version: "2" +run: + timeout: 6m + issues-exit-code: 1 +linters: + default: none + enable: + - gocritic + - govet + - misspell + - unconvert + - unused + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +issues: + new: true +formatters: + enable: + - goimports + exclusions: + generated: lax + warn-unused: true + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/vendor/github.com/slack-go/slack/CONTRIBUTING.md b/vendor/github.com/slack-go/slack/CONTRIBUTING.md new file mode 100644 index 000000000..8b92d3531 --- /dev/null +++ b/vendor/github.com/slack-go/slack/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing Guide + +Welcome! We are glad that you want to contribute to our project! 💖 + +There are a just a few small guidelines you ask everyone to follow to make things a bit smoother and more consistent. + +## Opening Pull Requests + +1. It's generally best to start by opening a new issue describing the bug or feature you're intending to fix. Even if you think it's relatively minor, it's helpful to know what people are working on. Mention in the initial issue that you are planning to work on that bug or feature so that it can be assigned to you. + +2. Follow the normal process of [forking](https://help.github.com/articles/fork-a-repo) the project, and set up a new branch to work in. It's important that each group of changes be done in separate branches in order to ensure that a pull request only includes the commits related to that bug or feature. + +3. Any significant changes should almost always be accompanied by tests. The project already has some test coverage, so look at some of the existing tests if you're unsure how to go about it. + +4. Run `make pr-prep` to format your code and check that it passes all tests and linters. + +5. Do your best to have [well-formed commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) for each change. This provides consistency throughout the project, and ensures that commit messages are able to be formatted properly by various git tools. _Pull Request Titles_ should generally follow the [conventional commit](https://www.conventionalcommits.org/en/v1.0.0/) format to ease the release note process when cutting releases. + +6. Finally, push the commits to your fork and submit a [pull request](https://help.github.com/articles/creating-a-pull-request). NOTE: Please do not use force-push on PRs in this repo, as it makes it more difficult for reviewers to see what has changed since the last code review. We always perform "squash and merge" actions on PRs in this repo, so it doesn't matter how many commits your PR has, as they will end up being a single commit after merging. This is done to make a much cleaner `git log` history and helps to find regressions in the code using existing tools such as `git bisect`. + +## Code Comments + +Every exported method needs to have code comments that follow [Go Doc Comments](https://go.dev/doc/comment). A typical method's comments will look like this: + +```go +// PostMessage sends a message to a channel. +// +// Slack API docs: https://api.dev.slack.com/methods/chat.postMessage +func (api *Client) PostMessage(ctx context.Context, input PostMesssageInput) (PostMesssageOutput, error) { +... +} +``` + +The first line is the name of the method followed by a short description. This could also be a longer description if needed, but there is no need to repeat any details that are documented in Slack's documentation because users are expected to follow the documentation links to learn more. + +After the description comes a link to the Slack API documentation. + +## Other notes on code organization + +Currently, everything is defined in the main `slack` package, with API methods group separate files by the [Slack API Method Groupings](https://api.dev.slack.com/methods). diff --git a/vendor/github.com/slack-go/slack/LICENSE b/vendor/github.com/slack-go/slack/LICENSE new file mode 100644 index 000000000..5145171f1 --- /dev/null +++ b/vendor/github.com/slack-go/slack/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Norberto Lopes +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/slack-go/slack/Makefile b/vendor/github.com/slack-go/slack/Makefile new file mode 100644 index 000000000..727964016 --- /dev/null +++ b/vendor/github.com/slack-go/slack/Makefile @@ -0,0 +1,36 @@ +.PHONY: help deps fmt lint test test-race test-integration + +help: + @echo "" + @echo "Welcome to slack-go/slack make." + @echo "The following commands are available:" + @echo "" + @echo " make deps : Fetch all dependencies" + @echo " make fmt : Run go fmt to fix any formatting issues" + @echo " make lint : Use go vet to check for linting issues" + @echo " make test : Run all short tests" + @echo " make test-race : Run all tests with race condition checking" + @echo " make test-integration : Run all tests without limiting to short" + @echo "" + @echo " make pr-prep : Run this before making a PR to run fmt, lint and tests" + @echo "" + +deps: + @go mod tidy + +fmt: + @go fmt . + +lint: + @go vet . + +test: + @go test -v -count=1 -timeout 300s -short ./... + +test-race: + @go test -v -count=1 -timeout 300s -short -race ./... + +test-integration: + @go test -v -count=1 -timeout 600s ./... + +pr-prep: fmt lint test-race test-integration diff --git a/vendor/github.com/slack-go/slack/README.md b/vendor/github.com/slack-go/slack/README.md new file mode 100644 index 000000000..127ae253c --- /dev/null +++ b/vendor/github.com/slack-go/slack/README.md @@ -0,0 +1,111 @@ +Slack API in Go [![Go Reference](https://pkg.go.dev/badge/github.com/slack-go/slack.svg)](https://pkg.go.dev/github.com/slack-go/slack) [![CI](https://github.com/slack-go/slack/actions/workflows/test.yml/badge.svg)](https://github.com/slack-go/slack/actions/workflows/test.yml) +=============== + +This is the original Slack library for Go created by Norberto Lopes, transferred to a GitHub organization. + +You can also chat with us on the #slack-go, #slack-go-ja Slack channel on the Gophers Slack. + +![logo](logo.png "icon") + +This library supports most if not all of the `api.slack.com` REST +calls, as well as the Real-Time Messaging protocol over websocket, in +a fully managed way. + +## Project Status +There is currently no major version released. +Therefore, minor version releases may include backward incompatible changes. + +See [Releases](https://github.com/slack-go/slack/releases) for more information about the changes. + +## Installing + +### *go get* + + $ go get -u github.com/slack-go/slack + +## Example + +### Getting all groups + +```golang +import ( + "fmt" + + "github.com/slack-go/slack" +) + +func main() { + api := slack.New("YOUR_TOKEN_HERE") + // If you set debugging, it will log all requests to the console + // Useful when encountering issues + // slack.New("YOUR_TOKEN_HERE", slack.OptionDebug(true)) + groups, err := api.GetUserGroups(slack.GetUserGroupsOptionIncludeUsers(false)) + if err != nil { + fmt.Printf("%s\n", err) + return + } + for _, group := range groups { + fmt.Printf("ID: %s, Name: %s\n", group.ID, group.Name) + } +} +``` + +### Getting User Information + +```golang +import ( + "fmt" + + "github.com/slack-go/slack" +) + +func main() { + api := slack.New("YOUR_TOKEN_HERE") + user, err := api.GetUserInfo("U023BECGF") + if err != nil { + fmt.Printf("%s\n", err) + return + } + fmt.Printf("ID: %s, Fullname: %s, Email: %s\n", user.ID, user.Profile.RealName, user.Profile.Email) +} +``` + +## Minimal Socket Mode usage: + +See https://github.com/slack-go/slack/blob/master/examples/socketmode/socketmode.go + + +## Minimal RTM usage: + +As mentioned in https://api.slack.com/rtm - for most applications, Socket Mode is a better way to communicate with Slack. + +See https://github.com/slack-go/slack/blob/master/examples/websocket/websocket.go + + +## Minimal EventsAPI usage: + +See https://github.com/slack-go/slack/blob/master/examples/eventsapi/events.go + +## Socketmode Event Handler (Experimental) + +When using socket mode, dealing with an event can be pretty lengthy as it requires you to route the event to the right place. + +Instead, you can use `SocketmodeHandler` much like you use an HTTP handler to register which event you would like to listen to and what callback function will process that event when it occurs. + +See [./examples/socketmode_handler/socketmode_handler.go](./examples/socketmode_handler/socketmode_handler.go) +## Contributing + +You are more than welcome to contribute to this project. Fork and +make a Pull Request, or create an Issue if you see any problem. + +Before making any Pull Request please run the following: + +``` +make pr-prep +``` + +This will check/update code formatting, linting and then run all tests + +## License + +BSD 2 Clause license diff --git a/vendor/github.com/slack-go/slack/admin.go b/vendor/github.com/slack-go/slack/admin.go new file mode 100644 index 000000000..d51426b56 --- /dev/null +++ b/vendor/github.com/slack-go/slack/admin.go @@ -0,0 +1,207 @@ +package slack + +import ( + "context" + "fmt" + "net/url" + "strings" +) + +func (api *Client) adminRequest(ctx context.Context, method string, teamName string, values url.Values) error { + resp := &SlackResponse{} + err := parseAdminResponse(ctx, api.httpclient, method, teamName, values, resp, api) + if err != nil { + return err + } + + return resp.Err() +} + +// DisableUser disabled a user account, given a user ID +func (api *Client) DisableUser(teamName string, uid string) error { + return api.DisableUserContext(context.Background(), teamName, uid) +} + +// DisableUserContext disabled a user account, given a user ID with a custom context +func (api *Client) DisableUserContext(ctx context.Context, teamName string, uid string) error { + values := url.Values{ + "user": {uid}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + if err := api.adminRequest(ctx, "setInactive", teamName, values); err != nil { + return fmt.Errorf("failed to disable user with id '%s': %s", uid, err) + } + + return nil +} + +// InviteGuest invites a user to Slack as a single-channel guest +func (api *Client) InviteGuest(teamName, channel, firstName, lastName, emailAddress string) error { + return api.InviteGuestContext(context.Background(), teamName, channel, firstName, lastName, emailAddress) +} + +// InviteGuestContext invites a user to Slack as a single-channel guest with a custom context +func (api *Client) InviteGuestContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error { + values := url.Values{ + "email": {emailAddress}, + "channels": {channel}, + "first_name": {firstName}, + "last_name": {lastName}, + "ultra_restricted": {"1"}, + "token": {api.token}, + "resend": {"true"}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "invite", teamName, values) + if err != nil { + return fmt.Errorf("Failed to invite single-channel guest: %s", err) + } + + return nil +} + +// InviteRestricted invites a user to Slack as a restricted account +func (api *Client) InviteRestricted(teamName, channel, firstName, lastName, emailAddress string) error { + return api.InviteRestrictedContext(context.Background(), teamName, channel, firstName, lastName, emailAddress) +} + +// InviteRestrictedContext invites a user to Slack as a restricted account with a custom context +func (api *Client) InviteRestrictedContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error { + values := url.Values{ + "email": {emailAddress}, + "channels": {channel}, + "first_name": {firstName}, + "last_name": {lastName}, + "restricted": {"1"}, + "token": {api.token}, + "resend": {"true"}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "invite", teamName, values) + if err != nil { + return fmt.Errorf("Failed to restricted account: %s", err) + } + + return nil +} + +// InviteToTeam invites a user to a Slack team +func (api *Client) InviteToTeam(teamName, firstName, lastName, emailAddress string) error { + return api.InviteToTeamContext(context.Background(), teamName, firstName, lastName, emailAddress) +} + +// InviteToTeamContext invites a user to a Slack team with a custom context +func (api *Client) InviteToTeamContext(ctx context.Context, teamName, firstName, lastName, emailAddress string) error { + values := url.Values{ + "email": {emailAddress}, + "first_name": {firstName}, + "last_name": {lastName}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "invite", teamName, values) + if err != nil { + return fmt.Errorf("Failed to invite to team: %s", err) + } + + return nil +} + +// SetRegular enables the specified user +func (api *Client) SetRegular(teamName, user string) error { + return api.SetRegularContext(context.Background(), teamName, user) +} + +// SetRegularContext enables the specified user with a custom context +func (api *Client) SetRegularContext(ctx context.Context, teamName, user string) error { + values := url.Values{ + "user": {user}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "setRegular", teamName, values) + if err != nil { + return fmt.Errorf("Failed to change the user (%s) to a regular user: %s", user, err) + } + + return nil +} + +// SendSSOBindingEmail sends an SSO binding email to the specified user +func (api *Client) SendSSOBindingEmail(teamName, user string) error { + return api.SendSSOBindingEmailContext(context.Background(), teamName, user) +} + +// SendSSOBindingEmailContext sends an SSO binding email to the specified user with a custom context +func (api *Client) SendSSOBindingEmailContext(ctx context.Context, teamName, user string) error { + values := url.Values{ + "user": {user}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "sendSSOBind", teamName, values) + if err != nil { + return fmt.Errorf("Failed to send SSO binding email for user (%s): %s", user, err) + } + + return nil +} + +// SetUltraRestricted converts a user into a single-channel guest +func (api *Client) SetUltraRestricted(teamName, uid, channel string) error { + return api.SetUltraRestrictedContext(context.Background(), teamName, uid, channel) +} + +// SetUltraRestrictedContext converts a user into a single-channel guest with a custom context +func (api *Client) SetUltraRestrictedContext(ctx context.Context, teamName, uid, channel string) error { + values := url.Values{ + "user": {uid}, + "channel": {channel}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + } + + err := api.adminRequest(ctx, "setUltraRestricted", teamName, values) + if err != nil { + return fmt.Errorf("Failed to ultra-restrict account: %s", err) + } + + return nil +} + +// SetRestricted converts a user into a restricted account +func (api *Client) SetRestricted(teamName, uid string, channelIds ...string) error { + return api.SetRestrictedContext(context.Background(), teamName, uid, channelIds...) +} + +// SetRestrictedContext converts a user into a restricted account with a custom context +func (api *Client) SetRestrictedContext(ctx context.Context, teamName, uid string, channelIds ...string) error { + values := url.Values{ + "user": {uid}, + "token": {api.token}, + "set_active": {"true"}, + "_attempts": {"1"}, + "channels": {strings.Join(channelIds, ",")}, + } + + err := api.adminRequest(ctx, "setRestricted", teamName, values) + if err != nil { + return fmt.Errorf("failed to restrict account: %s", err) + } + + return nil +} diff --git a/vendor/github.com/slack-go/slack/admin_conversations.go b/vendor/github.com/slack-go/slack/admin_conversations.go new file mode 100644 index 000000000..6f76568ba --- /dev/null +++ b/vendor/github.com/slack-go/slack/admin_conversations.go @@ -0,0 +1,85 @@ +package slack + +import ( + "context" + "net/url" + "strconv" + "strings" +) + +// AdminConversationsSetTeamsParams contains arguments for AdminConversationsSetTeams +// method calls. +type AdminConversationsSetTeamsParams struct { + ChannelID string + OrgChannel *bool + TargetTeamIDs []string + TeamID *string +} + +// Set the workspaces in an Enterprise Grid organisation that connect to a public or +// private channel. +// See: https://api.slack.com/methods/admin.conversations.setTeams +func (api *Client) AdminConversationsSetTeams(ctx context.Context, params AdminConversationsSetTeamsParams) error { + values := url.Values{ + "token": {api.token}, + "channel_id": {params.ChannelID}, + } + + if params.OrgChannel != nil { + values.Add("org_channel", strconv.FormatBool(*params.OrgChannel)) + } + + if len(params.TargetTeamIDs) > 0 { + values.Add("target_team_ids", strings.Join(params.TargetTeamIDs, ",")) // ["T123", "T456"] - > "T123,T456" + } + + if params.TeamID != nil { + values.Add("team_id", *params.TeamID) + } + + response := &SlackResponse{} + err := api.postMethod(ctx, "admin.conversations.setTeams", values, response) + if err != nil { + return err + } + + return response.Err() +} + +// ConversationsConvertToPrivate converts a public channel to a private channel. To do +// this, you must have the admin.conversations:write scope. There are other requirements: +// you should read the Slack documentation for more details. +// See: https://api.slack.com/methods/admin.conversations.convertToPrivate +func (api *Client) AdminConversationsConvertToPrivate(ctx context.Context, channelID string) error { + values := url.Values{ + "token": []string{api.token}, + "channel_id": []string{channelID}, + } + + response := &SlackResponse{} + err := api.postMethod(ctx, "admin.conversations.convertToPrivate", values, response) + if err != nil { + return err + } + + return response.Err() +} + +// ConversationsConvertToPublic converts a private channel to a public channel. To do +// this, you must have the admin.conversations:write scope. There are other requirements: +// you should read the Slack documentation for more details. +// See: https://api.slack.com/methods/admin.conversations.convertToPublic +func (api *Client) AdminConversationsConvertToPublic(ctx context.Context, channelID string) error { + values := url.Values{ + "token": []string{api.token}, + "channel_id": []string{channelID}, + } + + response := &SlackResponse{} + err := api.postMethod(ctx, "admin.conversations.convertToPublic", values, response) + if err != nil { + return err + } + + return response.Err() +} diff --git a/vendor/github.com/slack-go/slack/apps.go b/vendor/github.com/slack-go/slack/apps.go new file mode 100644 index 000000000..7322b15b9 --- /dev/null +++ b/vendor/github.com/slack-go/slack/apps.go @@ -0,0 +1,72 @@ +package slack + +import ( + "context" + "encoding/json" + "net/url" +) + +type listEventAuthorizationsResponse struct { + SlackResponse + Authorizations []EventAuthorization `json:"authorizations"` +} + +type EventAuthorization struct { + EnterpriseID string `json:"enterprise_id"` + TeamID string `json:"team_id"` + UserID string `json:"user_id"` + IsBot bool `json:"is_bot"` + IsEnterpriseInstall bool `json:"is_enterprise_install"` +} + +// ListEventAuthorizations lists authed users and teams for the given event_context. +// You must provide an app-level token to the client using OptionAppLevelToken. +// For more details, see ListEventAuthorizationsContext documentation. +func (api *Client) ListEventAuthorizations(eventContext string) ([]EventAuthorization, error) { + return api.ListEventAuthorizationsContext(context.Background(), eventContext) +} + +// ListEventAuthorizationsContext lists authed users and teams for the given event_context with a custom context. +// Slack API docs: https://api.slack.com/methods/apps.event.authorizations.list +func (api *Client) ListEventAuthorizationsContext(ctx context.Context, eventContext string) ([]EventAuthorization, error) { + resp := &listEventAuthorizationsResponse{} + + request, _ := json.Marshal(map[string]string{ + "event_context": eventContext, + }) + + err := postJSON(ctx, api.httpclient, api.endpoint+"apps.event.authorizations.list", api.appLevelToken, request, &resp, api) + + if err != nil { + return nil, err + } + if !resp.Ok { + return nil, resp.Err() + } + + return resp.Authorizations, nil +} + +// UninstallApp uninstalls your app from a workspace. +// For more details, see UninstallAppContext documentation. +func (api *Client) UninstallApp(clientID, clientSecret string) error { + return api.UninstallAppContext(context.Background(), clientID, clientSecret) +} + +// UninstallAppContext uninstalls your app from a workspace with a custom context. +// Slack API docs: https://api.slack.com/methods/apps.uninstall +func (api *Client) UninstallAppContext(ctx context.Context, clientID, clientSecret string) error { + values := url.Values{ + "client_id": {clientID}, + "client_secret": {clientSecret}, + } + + response := SlackResponse{} + + err := api.getMethod(ctx, "apps.uninstall", api.token, values, &response) + if err != nil { + return err + } + + return response.Err() +} diff --git a/vendor/github.com/slack-go/slack/assistant.go b/vendor/github.com/slack-go/slack/assistant.go new file mode 100644 index 000000000..8432f89b3 --- /dev/null +++ b/vendor/github.com/slack-go/slack/assistant.go @@ -0,0 +1,157 @@ +package slack + +import ( + "context" + "encoding/json" + "net/url" +) + +// AssistantThreadSetStatusParameters are the parameters for AssistantThreadSetStatus +type AssistantThreadsSetStatusParameters struct { + ChannelID string `json:"channel_id"` + Status string `json:"status"` + ThreadTS string `json:"thread_ts"` +} + +// AssistantThreadSetTitleParameters are the parameters for AssistantThreadSetTitle +type AssistantThreadsSetTitleParameters struct { + ChannelID string `json:"channel_id"` + ThreadTS string `json:"thread_ts"` + Title string `json:"title"` +} + +// AssistantThreadSetSuggestedPromptsParameters are the parameters for AssistantThreadSetSuggestedPrompts +type AssistantThreadsSetSuggestedPromptsParameters struct { + Title string `json:"title"` + ChannelID string `json:"channel_id"` + ThreadTS string `json:"thread_ts"` + Prompts []AssistantThreadsPrompt `json:"prompts"` +} + +// AssistantThreadPrompt is a suggested prompt for a thread +type AssistantThreadsPrompt struct { + Title string `json:"title"` + Message string `json:"message"` +} + +// AssistantThreadSetSuggestedPrompts sets the suggested prompts for a thread +func (p *AssistantThreadsSetSuggestedPromptsParameters) AddPrompt(title, message string) { + p.Prompts = append(p.Prompts, AssistantThreadsPrompt{ + Title: title, + Message: message, + }) +} + +// SetAssistantThreadsSugesstedPrompts sets the suggested prompts for a thread +// @see https://api.slack.com/methods/assistant.threads.setSuggestedPrompts +func (api *Client) SetAssistantThreadsSuggestedPrompts(params AssistantThreadsSetSuggestedPromptsParameters) (err error) { + return api.SetAssistantThreadsSuggestedPromptsContext(context.Background(), params) +} + +// SetAssistantThreadSuggestedPromptsContext sets the suggested prompts for a thread with a custom context +// @see https://api.slack.com/methods/assistant.threads.setSuggestedPrompts +func (api *Client) SetAssistantThreadsSuggestedPromptsContext(ctx context.Context, params AssistantThreadsSetSuggestedPromptsParameters) (err error) { + + values := url.Values{ + "token": {api.token}, + } + + if params.ThreadTS != "" { + values.Add("thread_ts", params.ThreadTS) + } + + values.Add("channel_id", params.ChannelID) + + // Send Prompts as JSON + prompts, err := json.Marshal(params.Prompts) + if err != nil { + return err + } + + values.Add("prompts", string(prompts)) + + response := struct { + SlackResponse + }{} + + err = api.postMethod(ctx, "assistant.threads.setSuggestedPrompts", values, &response) + if err != nil { + return + } + + return response.Err() +} + +// SetAssistantThreadStatus sets the status of a thread +// @see https://api.slack.com/methods/assistant.threads.setStatus +func (api *Client) SetAssistantThreadsStatus(params AssistantThreadsSetStatusParameters) (err error) { + return api.SetAssistantThreadsStatusContext(context.Background(), params) +} + +// SetAssistantThreadStatusContext sets the status of a thread with a custom context +// @see https://api.slack.com/methods/assistant.threads.setStatus +func (api *Client) SetAssistantThreadsStatusContext(ctx context.Context, params AssistantThreadsSetStatusParameters) (err error) { + + values := url.Values{ + "token": {api.token}, + } + + if params.ThreadTS != "" { + values.Add("thread_ts", params.ThreadTS) + } + + values.Add("channel_id", params.ChannelID) + + // Always send the status parameter, if empty, it will clear any existing status + values.Add("status", params.Status) + + response := struct { + SlackResponse + }{} + + err = api.postMethod(ctx, "assistant.threads.setStatus", values, &response) + if err != nil { + return + } + + return response.Err() +} + +// SetAssistantThreadsTitle sets the title of a thread +// @see https://api.slack.com/methods/assistant.threads.setTitle +func (api *Client) SetAssistantThreadsTitle(params AssistantThreadsSetTitleParameters) (err error) { + return api.SetAssistantThreadsTitleContext(context.Background(), params) +} + +// SetAssistantThreadsTitleContext sets the title of a thread with a custom context +// @see https://api.slack.com/methods/assistant.threads.setTitle +func (api *Client) SetAssistantThreadsTitleContext(ctx context.Context, params AssistantThreadsSetTitleParameters) (err error) { + + values := url.Values{ + "token": {api.token}, + } + + if params.ChannelID != "" { + values.Add("channel_id", params.ChannelID) + } + + if params.ThreadTS != "" { + values.Add("thread_ts", params.ThreadTS) + } + + if params.Title != "" { + values.Add("title", params.Title) + } + + response := struct { + SlackResponse + }{} + + err = api.postMethod(ctx, "assistant.threads.setTitle", values, &response) + if err != nil { + return + } + + return response.Err() + +} diff --git a/vendor/github.com/slack-go/slack/attachments.go b/vendor/github.com/slack-go/slack/attachments.go new file mode 100644 index 000000000..f4eb9b932 --- /dev/null +++ b/vendor/github.com/slack-go/slack/attachments.go @@ -0,0 +1,98 @@ +package slack + +import "encoding/json" + +// AttachmentField contains information for an attachment field +// An Attachment can contain multiple of these +type AttachmentField struct { + Title string `json:"title"` + Value string `json:"value"` + Short bool `json:"short"` +} + +// AttachmentAction is a button or menu to be included in the attachment. Required when +// using message buttons or menus and otherwise not useful. A maximum of 5 actions may be +// provided per attachment. +type AttachmentAction struct { + Name string `json:"name"` // Required. + Text string `json:"text"` // Required. + Style string `json:"style,omitempty"` // Optional. Allowed values: "default", "primary", "danger". + Type ActionType `json:"type"` // Required. Must be set to "button" or "select". + Value string `json:"value,omitempty"` // Optional. + DataSource string `json:"data_source,omitempty"` // Optional. + MinQueryLength int `json:"min_query_length,omitempty"` // Optional. Default value is 1. + Options []AttachmentActionOption `json:"options,omitempty"` // Optional. Maximum of 100 options can be provided in each menu. + SelectedOptions []AttachmentActionOption `json:"selected_options,omitempty"` // Optional. The first element of this array will be set as the pre-selected option for this menu. + OptionGroups []AttachmentActionOptionGroup `json:"option_groups,omitempty"` // Optional. + Confirm *ConfirmationField `json:"confirm,omitempty"` // Optional. + URL string `json:"url,omitempty"` // Optional. +} + +// actionType returns the type of the action +func (a AttachmentAction) actionType() ActionType { + return a.Type +} + +// AttachmentActionOption the individual option to appear in action menu. +type AttachmentActionOption struct { + Text string `json:"text"` // Required. + Value string `json:"value"` // Required. + Description string `json:"description,omitempty"` // Optional. Up to 30 characters. +} + +// AttachmentActionOptionGroup is a semi-hierarchal way to list available options to appear in action menu. +type AttachmentActionOptionGroup struct { + Text string `json:"text"` // Required. + Options []AttachmentActionOption `json:"options"` // Required. +} + +// AttachmentActionCallback is sent from Slack when a user clicks a button in an interactive message (aka AttachmentAction) +// DEPRECATED: use InteractionCallback +type AttachmentActionCallback InteractionCallback + +// ConfirmationField are used to ask users to confirm actions +type ConfirmationField struct { + Title string `json:"title,omitempty"` // Optional. + Text string `json:"text"` // Required. + OkText string `json:"ok_text,omitempty"` // Optional. Defaults to "Okay" + DismissText string `json:"dismiss_text,omitempty"` // Optional. Defaults to "Cancel" +} + +// Attachment contains all the information for an attachment +type Attachment struct { + Color string `json:"color,omitempty"` + Fallback string `json:"fallback,omitempty"` + + CallbackID string `json:"callback_id,omitempty"` + ID int `json:"id,omitempty"` + + AuthorID string `json:"author_id,omitempty"` + AuthorName string `json:"author_name,omitempty"` + AuthorSubname string `json:"author_subname,omitempty"` + AuthorLink string `json:"author_link,omitempty"` + AuthorIcon string `json:"author_icon,omitempty"` + + Title string `json:"title,omitempty"` + TitleLink string `json:"title_link,omitempty"` + Pretext string `json:"pretext,omitempty"` + Text string `json:"text,omitempty"` + + ImageURL string `json:"image_url,omitempty"` + ThumbURL string `json:"thumb_url,omitempty"` + + ServiceName string `json:"service_name,omitempty"` + ServiceIcon string `json:"service_icon,omitempty"` + FromURL string `json:"from_url,omitempty"` + OriginalURL string `json:"original_url,omitempty"` + + Fields []AttachmentField `json:"fields,omitempty"` + Actions []AttachmentAction `json:"actions,omitempty"` + MarkdownIn []string `json:"mrkdwn_in,omitempty"` + + Blocks Blocks `json:"blocks,omitempty"` + + Footer string `json:"footer,omitempty"` + FooterIcon string `json:"footer_icon,omitempty"` + + Ts json.Number `json:"ts,omitempty"` +} diff --git a/vendor/github.com/slack-go/slack/audit.go b/vendor/github.com/slack-go/slack/audit.go new file mode 100644 index 000000000..a3ea7ebdf --- /dev/null +++ b/vendor/github.com/slack-go/slack/audit.go @@ -0,0 +1,152 @@ +package slack + +import ( + "context" + "net/url" + "strconv" +) + +type AuditLogResponse struct { + Entries []AuditEntry `json:"entries"` + SlackResponse +} + +type AuditEntry struct { + ID string `json:"id"` + DateCreate int `json:"date_create"` + Action string `json:"action"` + Actor struct { + Type string `json:"type"` + User AuditUser `json:"user"` + } `json:"actor"` + Entity struct { + Type string `json:"type"` + // Only one of the below will be completed, based on the value of Type a user, a channel, a file, an app, a workspace, or an enterprise + User AuditUser `json:"user"` + Channel AuditChannel `json:"channel"` + File AuditFile `json:"file"` + App AuditApp `json:"app"` + Workspace AuditWorkspace `json:"workspace"` + Enterprise AuditEnterprise `json:"enterprise"` + } `json:"entity"` + Context struct { + Location struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + Domain string `json:"domain"` + } `json:"location"` + UA string `json:"ua"` + IPAddress string `json:"ip_address"` + } `json:"context"` + Details struct { + NewValue interface{} `json:"new_value"` + PreviousValue interface{} `json:"previous_value"` + MobileOnly bool `json:"mobile_only"` + WebOnly bool `json:"web_only"` + NonSSOOnly bool `json:"non_sso_only"` + ExportType string `json:"export_type"` + ExportStart string `json:"export_start_ts"` + ExportEnd string `json:"export_end_ts"` + } `json:"details"` +} + +type AuditUser struct { + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Team string `json:"team"` +} + +type AuditChannel struct { + ID string `json:"id"` + Name string `json:"name"` + Privacy string `json:"privacy"` + IsShared bool `json:"is_shared"` + IsOrgShared bool `json:"is_org_shared"` +} + +type AuditFile struct { + ID string `json:"id"` + Name string `json:"name"` + Filetype string `json:"filetype"` + Title string `json:"title"` +} + +type AuditApp struct { + ID string `json:"id"` + Name string `json:"name"` + IsDistributed bool `json:"is_distributed"` + IsDirectoryApproved bool `json:"is_directory_approved"` + IsWorkflowApp bool `json:"is_workflow_app"` + Scopes []string `json:"scopes"` +} + +type AuditWorkspace struct { + ID string `json:"id"` + Name string `json:"name"` + Domain string `json:"domain"` +} + +type AuditEnterprise struct { + ID string `json:"id"` + Name string `json:"name"` + Domain string `json:"domain"` +} + +// AuditLogParameters contains all the parameters necessary (including the optional ones) for a GetAuditLogs() request +type AuditLogParameters struct { + Limit int + Cursor string + Latest int + Oldest int + Action string + Actor string + Entity string +} + +func (api *Client) auditLogsRequest(ctx context.Context, path string, values url.Values) (*AuditLogResponse, error) { + response := &AuditLogResponse{} + err := api.getMethod(ctx, path, api.token, values, response) + if err != nil { + return nil, err + } + return response, response.Err() +} + +// GetAuditLogs retrieves a page of audit entires according to the parameters given +func (api *Client) GetAuditLogs(params AuditLogParameters) (entries []AuditEntry, nextCursor string, err error) { + return api.GetAuditLogsContext(context.Background(), params) +} + +// GetAuditLogsContext retrieves a page of audit entries according to the parameters given with a custom context +func (api *Client) GetAuditLogsContext(ctx context.Context, params AuditLogParameters) (entries []AuditEntry, nextCursor string, err error) { + values := url.Values{} + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Oldest != 0 { + values.Add("oldest", strconv.Itoa(params.Oldest)) + } + if params.Latest != 0 { + values.Add("latest", strconv.Itoa(params.Latest)) + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Action != "" { + values.Add("action", params.Action) + } + if params.Actor != "" { + values.Add("actor", params.Actor) + } + if params.Entity != "" { + values.Add("entity", params.Entity) + } + + response, err := api.auditLogsRequest(ctx, "audit/v1/logs", values) + if err != nil { + return nil, "", err + } + return response.Entries, response.ResponseMetadata.Cursor, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/auth.go b/vendor/github.com/slack-go/slack/auth.go new file mode 100644 index 000000000..972f59ea6 --- /dev/null +++ b/vendor/github.com/slack-go/slack/auth.go @@ -0,0 +1,82 @@ +package slack + +import ( + "context" + "net/url" + "strconv" +) + +// AuthRevokeResponse contains our Auth response from the auth.revoke endpoint +type AuthRevokeResponse struct { + SlackResponse // Contains the "ok", and "Error", if any + Revoked bool `json:"revoked,omitempty"` +} + +// authRequest sends the actual request, and unmarshals the response +func (api *Client) authRequest(ctx context.Context, path string, values url.Values) (*AuthRevokeResponse, error) { + response := &AuthRevokeResponse{} + err := api.postMethod(ctx, path, values, response) + if err != nil { + return nil, err + } + + return response, response.Err() +} + +// SendAuthRevoke will send a revocation for our token. +// For more details, see SendAuthRevokeContext documentation. +func (api *Client) SendAuthRevoke(token string) (*AuthRevokeResponse, error) { + return api.SendAuthRevokeContext(context.Background(), token) +} + +// SendAuthRevokeContext will send a revocation request for our token to api.revoke with a custom context. +// Slack API docs: https://api.slack.com/methods/auth.revoke +func (api *Client) SendAuthRevokeContext(ctx context.Context, token string) (*AuthRevokeResponse, error) { + if token == "" { + token = api.token + } + values := url.Values{ + "token": {token}, + } + + return api.authRequest(ctx, "auth.revoke", values) +} + +type listTeamsResponse struct { + Teams []Team `json:"teams"` + SlackResponse +} + +type ListTeamsParameters struct { + Limit int + Cursor string + IncludeIcon *bool +} + +// ListTeams returns all workspaces a token can access. +// For more details, see ListTeamsContext documentation. +func (api *Client) ListTeams(params ListTeamsParameters) ([]Team, string, error) { + return api.ListTeamsContext(context.Background(), params) +} + +// ListTeamsContext returns all workspaces a token can access with a custom context. +// Slack API docs: https://api.slack.com/methods/auth.teams.list +func (api *Client) ListTeamsContext(ctx context.Context, params ListTeamsParameters) ([]Team, string, error) { + values := url.Values{ + "token": {api.token}, + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.IncludeIcon != nil { + values.Add("include_icon", strconv.FormatBool(*params.IncludeIcon)) + } + + response := &listTeamsResponse{} + err := api.postMethod(ctx, "auth.teams.list", values, response) + if err != nil { + return nil, "", err + } + + return response.Teams, response.ResponseMetadata.Cursor, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/block.go b/vendor/github.com/slack-go/slack/block.go new file mode 100644 index 000000000..7c4f99308 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block.go @@ -0,0 +1,85 @@ +package slack + +// MessageBlockType defines a named string type to define each block type +// as a constant for use within the package. +type MessageBlockType string + +const ( + MBTSection MessageBlockType = "section" + MBTDivider MessageBlockType = "divider" + MBTImage MessageBlockType = "image" + MBTAction MessageBlockType = "actions" + MBTContext MessageBlockType = "context" + MBTFile MessageBlockType = "file" + MBTInput MessageBlockType = "input" + MBTHeader MessageBlockType = "header" + MBTRichText MessageBlockType = "rich_text" + MBTCall MessageBlockType = "call" + MBTVideo MessageBlockType = "video" + MBTMarkdown MessageBlockType = "markdown" +) + +// Block defines an interface all block types should implement +// to ensure consistency between blocks. +type Block interface { + BlockType() MessageBlockType + ID() string +} + +// Blocks is a convenience struct defined to allow dynamic unmarshalling of +// the "blocks" value in Slack's JSON response, which varies depending on block type +type Blocks struct { + BlockSet []Block `json:"blocks,omitempty"` +} + +// BlockAction is the action callback sent when a block is interacted with +type BlockAction struct { + ActionID string `json:"action_id"` + BlockID string `json:"block_id"` + Type ActionType `json:"type"` + Text TextBlockObject `json:"text"` + Value string `json:"value"` + Files []File `json:"files"` + ActionTs string `json:"action_ts"` + SelectedOption OptionBlockObject `json:"selected_option"` + SelectedOptions []OptionBlockObject `json:"selected_options"` + SelectedUser string `json:"selected_user"` + SelectedUsers []string `json:"selected_users"` + SelectedChannel string `json:"selected_channel"` + SelectedChannels []string `json:"selected_channels"` + SelectedConversation string `json:"selected_conversation"` + SelectedConversations []string `json:"selected_conversations"` + SelectedDate string `json:"selected_date"` + SelectedTime string `json:"selected_time"` + SelectedDateTime int64 `json:"selected_date_time"` + Timezone string `json:"timezone"` + InitialOption OptionBlockObject `json:"initial_option"` + InitialUser string `json:"initial_user"` + InitialChannel string `json:"initial_channel"` + InitialConversation string `json:"initial_conversation"` + InitialDate string `json:"initial_date"` + InitialTime string `json:"initial_time"` + RichTextValue RichTextBlock `json:"rich_text_value"` +} + +// actionType returns the type of the action +func (b BlockAction) actionType() ActionType { + return b.Type +} + +// NewBlockMessage creates a new Message that contains one or more blocks to be displayed +func NewBlockMessage(blocks ...Block) Message { + return Message{ + Msg: Msg{ + Blocks: Blocks{ + BlockSet: blocks, + }, + }, + } +} + +// AddBlockMessage appends a block to the end of the existing list of blocks +func AddBlockMessage(message Message, newBlk Block) Message { + message.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk) + return message +} diff --git a/vendor/github.com/slack-go/slack/block_action.go b/vendor/github.com/slack-go/slack/block_action.go new file mode 100644 index 000000000..819c0ef0d --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_action.go @@ -0,0 +1,31 @@ +package slack + +// ActionBlock defines data that is used to hold interactive elements. +// +// More Information: https://api.slack.com/reference/messaging/blocks#actions +type ActionBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + Elements *BlockElements `json:"elements"` +} + +// BlockType returns the type of the block +func (s ActionBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s ActionBlock) ID() string { + return s.BlockID +} + +// NewActionBlock returns a new instance of an Action Block +func NewActionBlock(blockID string, elements ...BlockElement) *ActionBlock { + return &ActionBlock{ + Type: MBTAction, + BlockID: blockID, + Elements: &BlockElements{ + ElementSet: elements, + }, + } +} diff --git a/vendor/github.com/slack-go/slack/block_call.go b/vendor/github.com/slack-go/slack/block_call.go new file mode 100644 index 000000000..c81dcb8be --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_call.go @@ -0,0 +1,28 @@ +package slack + +// CallBlock defines data that is used to display a call in slack. +// +// More Information: https://api.slack.com/apis/calls#post_to_channel +type CallBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + CallID string `json:"call_id"` +} + +// BlockType returns the type of the block +func (s CallBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s CallBlock) ID() string { + return s.BlockID +} + +// NewCallBlock returns a new instance of a call block +func NewCallBlock(callID string) *CallBlock { + return &CallBlock{ + Type: MBTCall, + CallID: callID, + } +} diff --git a/vendor/github.com/slack-go/slack/block_context.go b/vendor/github.com/slack-go/slack/block_context.go new file mode 100644 index 000000000..879ee61ee --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_context.go @@ -0,0 +1,37 @@ +package slack + +// ContextBlock defines data that is used to display message context, which can +// include both images and text. +// +// More Information: https://api.slack.com/reference/messaging/blocks#context +type ContextBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + ContextElements ContextElements `json:"elements"` +} + +// BlockType returns the type of the block +func (s ContextBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s ContextBlock) ID() string { + return s.BlockID +} + +type ContextElements struct { + Elements []MixedElement +} + +// NewContextBlock returns a new instance of a context block +func NewContextBlock(blockID string, mixedElements ...MixedElement) *ContextBlock { + elements := ContextElements{ + Elements: mixedElements, + } + return &ContextBlock{ + Type: MBTContext, + BlockID: blockID, + ContextElements: elements, + } +} diff --git a/vendor/github.com/slack-go/slack/block_conv.go b/vendor/github.com/slack-go/slack/block_conv.go new file mode 100644 index 000000000..7df9b107b --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_conv.go @@ -0,0 +1,456 @@ +package slack + +import ( + "encoding/json" + "fmt" +) + +type sumtype struct { + TypeVal string `json:"type"` +} + +// MarshalJSON implements the Marshaller interface for Blocks so that any JSON +// marshalling is delegated and proper type determination can be made before marshal +func (b Blocks) MarshalJSON() ([]byte, error) { + bytes, err := json.Marshal(b.BlockSet) + if err != nil { + return nil, err + } + + return bytes, nil +} + +// UnmarshalJSON implements the Unmarshaller interface for Blocks, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +func (b *Blocks) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + + if string(data) == "{}" { + return nil + } + + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + var blocks Blocks + for _, r := range raw { + s := sumtype{} + err := json.Unmarshal(r, &s) + if err != nil { + return err + } + + var blockType string + if s.TypeVal != "" { + blockType = s.TypeVal + } + + var block Block + switch blockType { + case "actions": + block = &ActionBlock{} + case "context": + block = &ContextBlock{} + case "divider": + block = &DividerBlock{} + case "file": + block = &FileBlock{} + case "header": + block = &HeaderBlock{} + case "image": + block = &ImageBlock{} + case "input": + block = &InputBlock{} + case "markdown": + block = &MarkdownBlock{} + case "rich_text": + block = &RichTextBlock{} + case "rich_text_input": + block = &RichTextBlock{} + case "section": + block = &SectionBlock{} + case "call": + block = &CallBlock{} + case "video": + block = &VideoBlock{} + default: + block = &UnknownBlock{} + } + + err = json.Unmarshal(r, block) + if err != nil { + return err + } + + blocks.BlockSet = append(blocks.BlockSet, block) + } + + *b = blocks + return nil +} + +// UnmarshalJSON implements the Unmarshaller interface for InputBlock, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +func (b *InputBlock) UnmarshalJSON(data []byte) error { + type alias InputBlock + a := struct { + Element json.RawMessage `json:"element"` + *alias + }{ + alias: (*alias)(b), + } + + if err := json.Unmarshal(data, &a); err != nil { + return err + } + + s := sumtype{} + if err := json.Unmarshal(a.Element, &s); err != nil { + return nil + } + + var e BlockElement + switch s.TypeVal { + case "datepicker": + e = &DatePickerBlockElement{} + case "timepicker": + e = &TimePickerBlockElement{} + case "datetimepicker": + e = &DateTimePickerBlockElement{} + case "plain_text_input": + e = &PlainTextInputBlockElement{} + case "rich_text_input": + e = &RichTextInputBlockElement{} + case "email_text_input": + e = &EmailTextInputBlockElement{} + case "url_text_input": + e = &URLTextInputBlockElement{} + case "static_select", "external_select", "users_select", "conversations_select", "channels_select": + e = &SelectBlockElement{} + case "multi_static_select", "multi_external_select", "multi_users_select", "multi_conversations_select", "multi_channels_select": + e = &MultiSelectBlockElement{} + case "checkboxes": + e = &CheckboxGroupsBlockElement{} + case "overflow": + e = &OverflowBlockElement{} + case "radio_buttons": + e = &RadioButtonsBlockElement{} + case "number_input": + e = &NumberInputBlockElement{} + case "file_input": + e = &FileInputBlockElement{} + default: + return fmt.Errorf("unsupported block element type %v", s.TypeVal) + } + + if err := json.Unmarshal(a.Element, e); err != nil { + return err + } + b.Element = e + + return nil +} + +// MarshalJSON implements the Marshaller interface for BlockElements so that any JSON +// marshalling is delegated and proper type determination can be made before marshal +func (b *BlockElements) MarshalJSON() ([]byte, error) { + bytes, err := json.Marshal(b.ElementSet) + if err != nil { + return nil, err + } + + return bytes, nil +} + +// UnmarshalJSON implements the Unmarshaller interface for BlockElements, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +func (b *BlockElements) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + + if string(data) == "{}" { + return nil + } + + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + var blockElements BlockElements + for _, r := range raw { + s := sumtype{} + err := json.Unmarshal(r, &s) + if err != nil { + return err + } + + var blockElementType string + if s.TypeVal != "" { + blockElementType = s.TypeVal + } + + var blockElement BlockElement + switch blockElementType { + case "image": + blockElement = &ImageBlockElement{} + case "button": + blockElement = &ButtonBlockElement{} + case "overflow": + blockElement = &OverflowBlockElement{} + case "datepicker": + blockElement = &DatePickerBlockElement{} + case "timepicker": + blockElement = &TimePickerBlockElement{} + case "datetimepicker": + blockElement = &DateTimePickerBlockElement{} + case "plain_text_input": + blockElement = &PlainTextInputBlockElement{} + case "rich_text_input": + blockElement = &RichTextInputBlockElement{} + case "email_text_input": + blockElement = &EmailTextInputBlockElement{} + case "url_text_input": + blockElement = &URLTextInputBlockElement{} + case "checkboxes": + blockElement = &CheckboxGroupsBlockElement{} + case "radio_buttons": + blockElement = &RadioButtonsBlockElement{} + case "static_select", "external_select", "users_select", "conversations_select", "channels_select": + blockElement = &SelectBlockElement{} + case "number_input": + blockElement = &NumberInputBlockElement{} + default: + return fmt.Errorf("unsupported block element type %v", blockElementType) + } + + err = json.Unmarshal(r, blockElement) + if err != nil { + return err + } + + blockElements.ElementSet = append(blockElements.ElementSet, blockElement) + } + + *b = blockElements + return nil +} + +// MarshalJSON implements the Marshaller interface for Accessory so that any JSON +// marshalling is delegated and proper type determination can be made before marshal +func (a *Accessory) MarshalJSON() ([]byte, error) { + bytes, err := json.Marshal(toBlockElement(a)) + if err != nil { + return nil, err + } + + return bytes, nil +} + +// UnmarshalJSON implements the Unmarshaller interface for Accessory, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +// Note: datetimepicker is not supported in Accessory +func (a *Accessory) UnmarshalJSON(data []byte) error { + var r json.RawMessage + + if string(data) == "{\"accessory\":null}" { + return nil + } + + err := json.Unmarshal(data, &r) + if err != nil { + return err + } + + s := sumtype{} + err = json.Unmarshal(r, &s) + if err != nil { + return err + } + + var blockElementType string + if s.TypeVal != "" { + blockElementType = s.TypeVal + } + + switch blockElementType { + case "image": + element, err := unmarshalBlockElement(r, &ImageBlockElement{}) + if err != nil { + return err + } + a.ImageElement = element.(*ImageBlockElement) + case "button": + element, err := unmarshalBlockElement(r, &ButtonBlockElement{}) + if err != nil { + return err + } + a.ButtonElement = element.(*ButtonBlockElement) + case "overflow": + element, err := unmarshalBlockElement(r, &OverflowBlockElement{}) + if err != nil { + return err + } + a.OverflowElement = element.(*OverflowBlockElement) + case "datepicker": + element, err := unmarshalBlockElement(r, &DatePickerBlockElement{}) + if err != nil { + return err + } + a.DatePickerElement = element.(*DatePickerBlockElement) + case "timepicker": + element, err := unmarshalBlockElement(r, &TimePickerBlockElement{}) + if err != nil { + return err + } + a.TimePickerElement = element.(*TimePickerBlockElement) + case "plain_text_input": + element, err := unmarshalBlockElement(r, &PlainTextInputBlockElement{}) + if err != nil { + return err + } + a.PlainTextInputElement = element.(*PlainTextInputBlockElement) + case "rich_text_input": + element, err := unmarshalBlockElement(r, &RichTextInputBlockElement{}) + if err != nil { + return err + } + a.RichTextInputElement = element.(*RichTextInputBlockElement) + case "radio_buttons": + element, err := unmarshalBlockElement(r, &RadioButtonsBlockElement{}) + if err != nil { + return err + } + a.RadioButtonsElement = element.(*RadioButtonsBlockElement) + case "static_select", "external_select", "users_select", "conversations_select", "channels_select": + element, err := unmarshalBlockElement(r, &SelectBlockElement{}) + if err != nil { + return err + } + a.SelectElement = element.(*SelectBlockElement) + case "multi_static_select", "multi_external_select", "multi_users_select", "multi_conversations_select", "multi_channels_select": + element, err := unmarshalBlockElement(r, &MultiSelectBlockElement{}) + if err != nil { + return err + } + a.MultiSelectElement = element.(*MultiSelectBlockElement) + case "checkboxes": + element, err := unmarshalBlockElement(r, &CheckboxGroupsBlockElement{}) + if err != nil { + return err + } + a.CheckboxGroupsBlockElement = element.(*CheckboxGroupsBlockElement) + default: + element, err := unmarshalBlockElement(r, &UnknownBlockElement{}) + if err != nil { + return err + } + a.UnknownElement = element.(*UnknownBlockElement) + } + + return nil +} + +func unmarshalBlockElement(r json.RawMessage, element BlockElement) (BlockElement, error) { + err := json.Unmarshal(r, element) + if err != nil { + return nil, err + } + return element, nil +} + +func toBlockElement(element *Accessory) BlockElement { + if element.ImageElement != nil { + return element.ImageElement + } + if element.ButtonElement != nil { + return element.ButtonElement + } + if element.OverflowElement != nil { + return element.OverflowElement + } + if element.DatePickerElement != nil { + return element.DatePickerElement + } + if element.TimePickerElement != nil { + return element.TimePickerElement + } + if element.PlainTextInputElement != nil { + return element.PlainTextInputElement + } + if element.RadioButtonsElement != nil { + return element.RadioButtonsElement + } + if element.CheckboxGroupsBlockElement != nil { + return element.CheckboxGroupsBlockElement + } + if element.SelectElement != nil { + return element.SelectElement + } + if element.MultiSelectElement != nil { + return element.MultiSelectElement + } + + return nil +} + +// MarshalJSON implements the Marshaller interface for ContextElements so that any JSON +// marshalling is delegated and proper type determination can be made before marshal +func (e *ContextElements) MarshalJSON() ([]byte, error) { + bytes, err := json.Marshal(e.Elements) + if err != nil { + return nil, err + } + + return bytes, nil +} + +// UnmarshalJSON implements the Unmarshaller interface for ContextElements, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +func (e *ContextElements) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + + if string(data) == "{\"elements\":null}" { + return nil + } + + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + for _, r := range raw { + s := sumtype{} + err := json.Unmarshal(r, &s) + if err != nil { + return err + } + + var contextElementType string + if s.TypeVal != "" { + contextElementType = s.TypeVal + } + + switch contextElementType { + case PlainTextType, MarkdownType: + elem, err := unmarshalBlockObject(r, &TextBlockObject{}) + if err != nil { + return err + } + + e.Elements = append(e.Elements, elem.(*TextBlockObject)) + case "image": + elem, err := unmarshalBlockElement(r, &ImageBlockElement{}) + if err != nil { + return err + } + + e.Elements = append(e.Elements, elem.(*ImageBlockElement)) + default: + return fmt.Errorf("unsupported context element type %v", contextElementType) + } + } + + return nil +} diff --git a/vendor/github.com/slack-go/slack/block_divider.go b/vendor/github.com/slack-go/slack/block_divider.go new file mode 100644 index 000000000..e10d7b053 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_divider.go @@ -0,0 +1,26 @@ +package slack + +// DividerBlock for displaying a divider line between blocks (similar to
tag in html) +// +// More Information: https://api.slack.com/reference/messaging/blocks#divider +type DividerBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` +} + +// BlockType returns the type of the block +func (s DividerBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s DividerBlock) ID() string { + return s.BlockID +} + +// NewDividerBlock returns a new instance of a divider block +func NewDividerBlock() *DividerBlock { + return &DividerBlock{ + Type: MBTDivider, + } +} diff --git a/vendor/github.com/slack-go/slack/block_element.go b/vendor/github.com/slack-go/slack/block_element.go new file mode 100644 index 000000000..2b32d331e --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_element.go @@ -0,0 +1,813 @@ +package slack + +// https://api.slack.com/reference/messaging/block-elements + +const ( + METCheckboxGroups MessageElementType = "checkboxes" + METImage MessageElementType = "image" + METButton MessageElementType = "button" + METOverflow MessageElementType = "overflow" + METDatepicker MessageElementType = "datepicker" + METTimepicker MessageElementType = "timepicker" + METDatetimepicker MessageElementType = "datetimepicker" + METPlainTextInput MessageElementType = "plain_text_input" + METRadioButtons MessageElementType = "radio_buttons" + METRichTextInput MessageElementType = "rich_text_input" + METEmailTextInput MessageElementType = "email_text_input" + METURLTextInput MessageElementType = "url_text_input" + METNumber MessageElementType = "number_input" + METFileInput MessageElementType = "file_input" + + MixedElementImage MixedElementType = "mixed_image" + MixedElementText MixedElementType = "mixed_text" + + OptTypeStatic string = "static_select" + OptTypeExternal string = "external_select" + OptTypeUser string = "users_select" + OptTypeConversations string = "conversations_select" + OptTypeChannels string = "channels_select" + + MultiOptTypeStatic string = "multi_static_select" + MultiOptTypeExternal string = "multi_external_select" + MultiOptTypeUser string = "multi_users_select" + MultiOptTypeConversations string = "multi_conversations_select" + MultiOptTypeChannels string = "multi_channels_select" +) + +type MessageElementType string +type MixedElementType string + +// BlockElement defines an interface that all block element types should implement. +type BlockElement interface { + ElementType() MessageElementType +} + +type MixedElement interface { + MixedElementType() MixedElementType +} + +type Accessory struct { + ImageElement *ImageBlockElement + ButtonElement *ButtonBlockElement + OverflowElement *OverflowBlockElement + DatePickerElement *DatePickerBlockElement + TimePickerElement *TimePickerBlockElement + PlainTextInputElement *PlainTextInputBlockElement + RichTextInputElement *RichTextInputBlockElement + RadioButtonsElement *RadioButtonsBlockElement + SelectElement *SelectBlockElement + MultiSelectElement *MultiSelectBlockElement + CheckboxGroupsBlockElement *CheckboxGroupsBlockElement + UnknownElement *UnknownBlockElement +} + +// NewAccessory returns a new Accessory for a given block element +func NewAccessory(element BlockElement) *Accessory { + switch element.(type) { + case *ImageBlockElement: + return &Accessory{ImageElement: element.(*ImageBlockElement)} + case *ButtonBlockElement: + return &Accessory{ButtonElement: element.(*ButtonBlockElement)} + case *OverflowBlockElement: + return &Accessory{OverflowElement: element.(*OverflowBlockElement)} + case *DatePickerBlockElement: + return &Accessory{DatePickerElement: element.(*DatePickerBlockElement)} + case *TimePickerBlockElement: + return &Accessory{TimePickerElement: element.(*TimePickerBlockElement)} + case *PlainTextInputBlockElement: + return &Accessory{PlainTextInputElement: element.(*PlainTextInputBlockElement)} + case *RichTextInputBlockElement: + return &Accessory{RichTextInputElement: element.(*RichTextInputBlockElement)} + case *RadioButtonsBlockElement: + return &Accessory{RadioButtonsElement: element.(*RadioButtonsBlockElement)} + case *SelectBlockElement: + return &Accessory{SelectElement: element.(*SelectBlockElement)} + case *MultiSelectBlockElement: + return &Accessory{MultiSelectElement: element.(*MultiSelectBlockElement)} + case *CheckboxGroupsBlockElement: + return &Accessory{CheckboxGroupsBlockElement: element.(*CheckboxGroupsBlockElement)} + default: + return &Accessory{UnknownElement: element.(*UnknownBlockElement)} + } +} + +// BlockElements is a convenience struct defined to allow dynamic unmarshalling of +// the "elements" value in Slack's JSON response, which varies depending on BlockElement type +type BlockElements struct { + ElementSet []BlockElement `json:"elements,omitempty"` +} + +// UnknownBlockElement any block element that this library does not directly support. +// See the "Rich Elements" section at the following URL: +// https://api.slack.com/changelog/2019-09-what-they-see-is-what-you-get-and-more-and-less +// New block element types may be introduced by Slack at any time; this is a catch-all for any such block elements. +type UnknownBlockElement struct { + Type MessageElementType `json:"type"` + Elements BlockElements +} + +// ElementType returns the type of the Element +func (s UnknownBlockElement) ElementType() MessageElementType { + return s.Type +} + +// ImageBlockElement An element to insert an image - this element can be used +// in section and context blocks only. If you want a block with only an image +// in it, you're looking for the image block. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#image +type ImageBlockElement struct { + Type MessageElementType `json:"type"` + ImageURL string `json:"image_url"` + AltText string `json:"alt_text"` + SlackFile *SlackFileObject `json:"slack_file,omitempty"` +} + +// ElementType returns the type of the Element +func (s ImageBlockElement) ElementType() MessageElementType { + return s.Type +} + +func (s ImageBlockElement) MixedElementType() MixedElementType { + return MixedElementImage +} + +// NewImageBlockElement returns a new instance of an image block element +func NewImageBlockElement(imageURL, altText string) *ImageBlockElement { + return &ImageBlockElement{ + Type: METImage, + ImageURL: imageURL, + AltText: altText, + } +} + +// NewImageBlockElementSlackFile returns a new instance of an image block element +// TODO: BREAKING CHANGE - This should be combined with the function above +func NewImageBlockElementSlackFile(slackFile *SlackFileObject, altText string) *ImageBlockElement { + return &ImageBlockElement{ + Type: METImage, + SlackFile: slackFile, + AltText: altText, + } +} + +// Style is a style of Button element +// https://api.slack.com/reference/block-kit/block-elements#button__fields +type Style string + +const ( + StyleDefault Style = "" + StylePrimary Style = "primary" + StyleDanger Style = "danger" +) + +// ButtonBlockElement defines an interactive element that inserts a button. The +// button can be a trigger for anything from opening a simple link to starting +// a complex workflow. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#button +type ButtonBlockElement struct { + Type MessageElementType `json:"type,omitempty"` + Text *TextBlockObject `json:"text"` + ActionID string `json:"action_id,omitempty"` + URL string `json:"url,omitempty"` + Value string `json:"value,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` + Style Style `json:"style,omitempty"` +} + +// ElementType returns the type of the element +func (s ButtonBlockElement) ElementType() MessageElementType { + return s.Type +} + +// WithStyle adds styling to the button object and returns the modified ButtonBlockElement +func (s *ButtonBlockElement) WithStyle(style Style) *ButtonBlockElement { + s.Style = style + return s +} + +// WithConfirm adds a confirmation dialogue to the button object and returns the modified ButtonBlockElement +func (s *ButtonBlockElement) WithConfirm(confirm *ConfirmationBlockObject) *ButtonBlockElement { + s.Confirm = confirm + return s +} + +// WithURL adds a URL for the button to link to and returns the modified ButtonBlockElement +func (s *ButtonBlockElement) WithURL(url string) *ButtonBlockElement { + s.URL = url + return s +} + +// NewButtonBlockElement returns an instance of a new button element to be used within a block +func NewButtonBlockElement(actionID, value string, text *TextBlockObject) *ButtonBlockElement { + return &ButtonBlockElement{ + Type: METButton, + ActionID: actionID, + Text: text, + Value: value, + } +} + +// OptionsResponse defines the response used for select block typahead. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#external_multi_select +type OptionsResponse struct { + Options []*OptionBlockObject `json:"options,omitempty"` +} + +// OptionGroupsResponse defines the response used for select block typahead. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#external_multi_select +type OptionGroupsResponse struct { + OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"` +} + +// SelectBlockElement defines the simplest form of select menu, with a static list +// of options passed in when defining the element. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#select +type SelectBlockElement struct { + Type string `json:"type,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + ActionID string `json:"action_id,omitempty"` + Options []*OptionBlockObject `json:"options,omitempty"` + OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"` + InitialOption *OptionBlockObject `json:"initial_option,omitempty"` + InitialUser string `json:"initial_user,omitempty"` + InitialConversation string `json:"initial_conversation,omitempty"` + InitialChannel string `json:"initial_channel,omitempty"` + DefaultToCurrentConversation bool `json:"default_to_current_conversation,omitempty"` + ResponseURLEnabled bool `json:"response_url_enabled,omitempty"` + Filter *SelectBlockElementFilter `json:"filter,omitempty"` + MinQueryLength *int `json:"min_query_length,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// SelectBlockElementFilter allows to filter select element conversation options by type. +// +// More Information: https://api.slack.com/reference/block-kit/composition-objects#filter_conversations +type SelectBlockElementFilter struct { + Include []string `json:"include,omitempty"` + ExcludeExternalSharedChannels bool `json:"exclude_external_shared_channels,omitempty"` + ExcludeBotUsers bool `json:"exclude_bot_users,omitempty"` +} + +// ElementType returns the type of the Element +func (s SelectBlockElement) ElementType() MessageElementType { + return MessageElementType(s.Type) +} + +// NewOptionsSelectBlockElement returns a new instance of SelectBlockElement for use with +// the Options object only. +func NewOptionsSelectBlockElement(optType string, placeholder *TextBlockObject, actionID string, options ...*OptionBlockObject) *SelectBlockElement { + return &SelectBlockElement{ + Type: optType, + Placeholder: placeholder, + ActionID: actionID, + Options: options, + } +} + +// WithInitialOption sets the initial option for the select element +func (s *SelectBlockElement) WithInitialOption(option *OptionBlockObject) *SelectBlockElement { + s.InitialOption = option + return s +} + +// WithInitialUser sets the initial user for the select element +func (s *SelectBlockElement) WithInitialUser(user string) *SelectBlockElement { + s.InitialUser = user + return s +} + +// WithInitialConversation sets the initial conversation for the select element +func (s *SelectBlockElement) WithInitialConversation(conversation string) *SelectBlockElement { + s.InitialConversation = conversation + return s +} + +// WithInitialChannel sets the initial channel for the select element +func (s *SelectBlockElement) WithInitialChannel(channel string) *SelectBlockElement { + s.InitialChannel = channel + return s +} + +// WithConfirm adds a confirmation dialogue to the select element +func (s *SelectBlockElement) WithConfirm(confirm *ConfirmationBlockObject) *SelectBlockElement { + s.Confirm = confirm + return s +} + +// NewOptionsGroupSelectBlockElement returns a new instance of SelectBlockElement for use with +// the Options object only. +func NewOptionsGroupSelectBlockElement( + optType string, + placeholder *TextBlockObject, + actionID string, + optGroups ...*OptionGroupBlockObject, +) *SelectBlockElement { + return &SelectBlockElement{ + Type: optType, + Placeholder: placeholder, + ActionID: actionID, + OptionGroups: optGroups, + } +} + +// MultiSelectBlockElement defines a multiselect menu, with a static list +// of options passed in when defining the element. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#multi_select +type MultiSelectBlockElement struct { + Type string `json:"type,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + ActionID string `json:"action_id,omitempty"` + Options []*OptionBlockObject `json:"options,omitempty"` + OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"` + InitialOptions []*OptionBlockObject `json:"initial_options,omitempty"` + InitialUsers []string `json:"initial_users,omitempty"` + InitialConversations []string `json:"initial_conversations,omitempty"` + InitialChannels []string `json:"initial_channels,omitempty"` + Filter *SelectBlockElementFilter `json:"filter,omitempty"` + MinQueryLength *int `json:"min_query_length,omitempty"` + MaxSelectedItems *int `json:"max_selected_items,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// ElementType returns the type of the Element +func (s MultiSelectBlockElement) ElementType() MessageElementType { + return MessageElementType(s.Type) +} + +// NewOptionsMultiSelectBlockElement returns a new instance of SelectBlockElement for use with +// the Options object only. +func NewOptionsMultiSelectBlockElement(optType string, placeholder *TextBlockObject, actionID string, options ...*OptionBlockObject) *MultiSelectBlockElement { + return &MultiSelectBlockElement{ + Type: optType, + Placeholder: placeholder, + ActionID: actionID, + Options: options, + } +} + +// WithInitialOptions sets the initial options for the multi-select element +func (s *MultiSelectBlockElement) WithInitialOptions(options ...*OptionBlockObject) *MultiSelectBlockElement { + s.InitialOptions = options + return s +} + +// WithInitialUsers sets the initial users for the multi-select element +func (s *MultiSelectBlockElement) WithInitialUsers(users ...string) *MultiSelectBlockElement { + s.InitialUsers = users + return s +} + +// WithInitialConversations sets the initial conversations for the multi-select element +func (s *MultiSelectBlockElement) WithInitialConversations(conversations ...string) *MultiSelectBlockElement { + s.InitialConversations = conversations + return s +} + +// WithInitialChannels sets the initial channels for the multi-select element +func (s *MultiSelectBlockElement) WithInitialChannels(channels ...string) *MultiSelectBlockElement { + s.InitialChannels = channels + return s +} + +// WithConfirm adds a confirmation dialogue to the multi-select element +func (s *MultiSelectBlockElement) WithConfirm(confirm *ConfirmationBlockObject) *MultiSelectBlockElement { + s.Confirm = confirm + return s +} + +// WithMaxSelectedItems sets the maximum number of items that can be selected +func (s *MultiSelectBlockElement) WithMaxSelectedItems(maxSelectedItems int) *MultiSelectBlockElement { + s.MaxSelectedItems = &maxSelectedItems + return s +} + +// WithMinQueryLength sets the minimum query length for the multi-select element +func (s *MultiSelectBlockElement) WithMinQueryLength(minQueryLength int) *MultiSelectBlockElement { + s.MinQueryLength = &minQueryLength + return s +} + +// NewOptionsGroupMultiSelectBlockElement returns a new instance of MultiSelectBlockElement for use with +// the Options object only. +func NewOptionsGroupMultiSelectBlockElement( + optType string, + placeholder *TextBlockObject, + actionID string, + optGroups ...*OptionGroupBlockObject, +) *MultiSelectBlockElement { + return &MultiSelectBlockElement{ + Type: optType, + Placeholder: placeholder, + ActionID: actionID, + OptionGroups: optGroups, + } +} + +// OverflowBlockElement defines the fields needed to use an overflow element. +// And Overflow Element is like a cross between a button and a select menu - +// when a user clicks on this overflow button, they will be presented with a +// list of options to choose from. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#overflow +type OverflowBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Options []*OptionBlockObject `json:"options"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// ElementType returns the type of the Element +func (s OverflowBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewOverflowBlockElement returns an instance of a new Overflow Block Element +func NewOverflowBlockElement(actionID string, options ...*OptionBlockObject) *OverflowBlockElement { + return &OverflowBlockElement{ + Type: METOverflow, + ActionID: actionID, + Options: options, + } +} + +// WithConfirm adds a confirmation dialogue to the overflow element +func (s *OverflowBlockElement) WithConfirm(confirm *ConfirmationBlockObject) *OverflowBlockElement { + s.Confirm = confirm + return s +} + +// DatePickerBlockElement defines an element which lets users easily select a +// date from a calendar style UI. Date picker elements can be used inside of +// section and actions blocks. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#datepicker +type DatePickerBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialDate string `json:"initial_date,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// ElementType returns the type of the Element +func (s DatePickerBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewDatePickerBlockElement returns an instance of a date picker element +func NewDatePickerBlockElement(actionID string) *DatePickerBlockElement { + return &DatePickerBlockElement{ + Type: METDatepicker, + ActionID: actionID, + } +} + +// TimePickerBlockElement defines an element which lets users easily select a +// time from nice UI. Time picker elements can be used inside of +// section and actions blocks. +// +// More Information: https://api.slack.com/reference/messaging/block-elements#timepicker +type TimePickerBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialTime string `json:"initial_time,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` + Timezone string `json:"timezone,omitempty"` +} + +// ElementType returns the type of the Element +func (s TimePickerBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewTimePickerBlockElement returns an instance of a date picker element +func NewTimePickerBlockElement(actionID string) *TimePickerBlockElement { + return &TimePickerBlockElement{ + Type: METTimepicker, + ActionID: actionID, + } +} + +// DateTimePickerBlockElement defines an element that allows the selection of both +// a date and a time of day formatted as a UNIX timestamp. +// More Information: https://api.slack.com/reference/messaging/block-elements#datetimepicker +type DateTimePickerBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + InitialDateTime int64 `json:"initial_date_time,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` + FocusOnLoad bool `json:"focus_on_load,omitempty"` +} + +// ElementType returns the type of the Element +func (s DateTimePickerBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewDatePickerBlockElement returns an instance of a datetime picker element +func NewDateTimePickerBlockElement(actionID string) *DateTimePickerBlockElement { + return &DateTimePickerBlockElement{ + Type: METDatetimepicker, + ActionID: actionID, + } +} + +// EmailTextInputBlockElement creates a field where a user can enter email +// data. +// email-text-input elements are currently only available in modals. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#email +type EmailTextInputBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialValue string `json:"initial_value,omitempty"` + DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"` + FocusOnLoad bool `json:"focus_on_load,omitempty"` +} + +// ElementType returns the type of the Element +func (s EmailTextInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewEmailTextInputBlockElement returns an instance of a plain-text input +// element +func NewEmailTextInputBlockElement(placeholder *TextBlockObject, actionID string) *EmailTextInputBlockElement { + return &EmailTextInputBlockElement{ + Type: METEmailTextInput, + ActionID: actionID, + Placeholder: placeholder, + } +} + +// URLTextInputBlockElement creates a field where a user can enter url data. +// +// url-text-input elements are currently only available in modals. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#url +type URLTextInputBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialValue string `json:"initial_value,omitempty"` + DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"` + FocusOnLoad bool `json:"focus_on_load,omitempty"` +} + +// ElementType returns the type of the Element +func (s URLTextInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewURLTextInputBlockElement returns an instance of a plain-text input +// element +func NewURLTextInputBlockElement(placeholder *TextBlockObject, actionID string) *URLTextInputBlockElement { + return &URLTextInputBlockElement{ + Type: METURLTextInput, + ActionID: actionID, + Placeholder: placeholder, + } +} + +// PlainTextInputBlockElement creates a field where a user can enter freeform +// data. +// Plain-text input elements are currently only available in modals. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#input +type PlainTextInputBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialValue string `json:"initial_value,omitempty"` + Multiline bool `json:"multiline,omitempty"` + MinLength int `json:"min_length,omitempty"` + MaxLength int `json:"max_length,omitempty"` + DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"` +} + +type DispatchActionConfig struct { + TriggerActionsOn []string `json:"trigger_actions_on,omitempty"` +} + +// ElementType returns the type of the Element +func (s PlainTextInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewPlainTextInputBlockElement returns an instance of a plain-text input +// element +func NewPlainTextInputBlockElement(placeholder *TextBlockObject, actionID string) *PlainTextInputBlockElement { + return &PlainTextInputBlockElement{ + Type: METPlainTextInput, + ActionID: actionID, + Placeholder: placeholder, + } +} + +// WithInitialValue sets the initial value for the plain-text input element +func (s *PlainTextInputBlockElement) WithInitialValue(initialValue string) *PlainTextInputBlockElement { + s.InitialValue = initialValue + return s +} + +// WithMinLength sets the minimum length for the plain-text input element +func (s *PlainTextInputBlockElement) WithMinLength(minLength int) *PlainTextInputBlockElement { + s.MinLength = minLength + return s +} + +// WithMaxLength sets the maximum length for the plain-text input element +func (s *PlainTextInputBlockElement) WithMaxLength(maxLength int) *PlainTextInputBlockElement { + s.MaxLength = maxLength + return s +} + +// WithMultiline sets the multiline property for the plain-text input element +func (s *PlainTextInputBlockElement) WithMultiline(multiline bool) *PlainTextInputBlockElement { + s.Multiline = multiline + return s +} + +// WithDispatchActionConfig sets the dispatch action config for the plain-text input element +func (s *PlainTextInputBlockElement) WithDispatchActionConfig(config *DispatchActionConfig) *PlainTextInputBlockElement { + s.DispatchActionConfig = config + return s +} + +// RichTextInputBlockElement creates a field where allows users to enter formatted text +// in a WYSIWYG composer, offering the same messaging writing experience as in Slack +// More Information: https://api.slack.com/reference/block-kit/block-elements#rich_text_input +type RichTextInputBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialValue *RichTextBlock `json:"initial_value,omitempty"` + DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"` + FocusOnLoad bool `json:"focus_on_load,omitempty"` +} + +// ElementType returns the type of the Element +func (s RichTextInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewRichTextInputBlockElement returns an instance of a rich-text input element +func NewRichTextInputBlockElement(placeholder *TextBlockObject, actionID string) *RichTextInputBlockElement { + return &RichTextInputBlockElement{ + Type: METRichTextInput, + ActionID: actionID, + Placeholder: placeholder, + } +} + +// CheckboxGroupsBlockElement defines an element which allows users to choose +// one or more items from a list of possible options. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#checkboxes +type CheckboxGroupsBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Options []*OptionBlockObject `json:"options"` + InitialOptions []*OptionBlockObject `json:"initial_options,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// ElementType returns the type of the Element +func (c CheckboxGroupsBlockElement) ElementType() MessageElementType { + return c.Type +} + +// NewCheckboxGroupsBlockElement returns an instance of a checkbox-group block element +func NewCheckboxGroupsBlockElement(actionID string, options ...*OptionBlockObject) *CheckboxGroupsBlockElement { + return &CheckboxGroupsBlockElement{ + Type: METCheckboxGroups, + ActionID: actionID, + Options: options, + } +} + +// RadioButtonsBlockElement defines an element which lets users choose one item +// from a list of possible options. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#radio +type RadioButtonsBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + Options []*OptionBlockObject `json:"options"` + InitialOption *OptionBlockObject `json:"initial_option,omitempty"` + Confirm *ConfirmationBlockObject `json:"confirm,omitempty"` +} + +// ElementType returns the type of the Element +func (s RadioButtonsBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewRadioButtonsBlockElement returns an instance of a radio buttons element. +func NewRadioButtonsBlockElement(actionID string, options ...*OptionBlockObject) *RadioButtonsBlockElement { + return &RadioButtonsBlockElement{ + Type: METRadioButtons, + ActionID: actionID, + Options: options, + } +} + +// NumberInputBlockElement creates a field where a user can enter number +// data. +// Number input elements are currently only available in modals. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#number +type NumberInputBlockElement struct { + Type MessageElementType `json:"type"` + IsDecimalAllowed bool `json:"is_decimal_allowed"` + ActionID string `json:"action_id,omitempty"` + Placeholder *TextBlockObject `json:"placeholder,omitempty"` + InitialValue string `json:"initial_value,omitempty"` + MinValue string `json:"min_value,omitempty"` + MaxValue string `json:"max_value,omitempty"` + DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"` +} + +// ElementType returns the type of the Element +func (s NumberInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewNumberInputBlockElement returns an instance of a number input element +func NewNumberInputBlockElement(placeholder *TextBlockObject, actionID string, isDecimalAllowed bool) *NumberInputBlockElement { + return &NumberInputBlockElement{ + Type: METNumber, + ActionID: actionID, + Placeholder: placeholder, + IsDecimalAllowed: isDecimalAllowed, + } +} + +// WithInitialValue sets the initial value for the number input element +func (s *NumberInputBlockElement) WithInitialValue(initialValue string) *NumberInputBlockElement { + s.InitialValue = initialValue + return s +} + +// WithMinValue sets the minimum value for the number input element +func (s *NumberInputBlockElement) WithMinValue(minValue string) *NumberInputBlockElement { + s.MinValue = minValue + return s +} + +// WithMaxValue sets the maximum value for the number input element +func (s *NumberInputBlockElement) WithMaxValue(maxValue string) *NumberInputBlockElement { + s.MaxValue = maxValue + return s +} + +// WithDispatchActionConfig sets the dispatch action config for the number input element +func (s *NumberInputBlockElement) WithDispatchActionConfig(config *DispatchActionConfig) *NumberInputBlockElement { + s.DispatchActionConfig = config + return s +} + +// FileInputBlockElement creates a field where a user can upload a file. +// +// File input elements are currently only available in modals. +// +// More Information: https://api.slack.com/reference/block-kit/block-elements#file_input +type FileInputBlockElement struct { + Type MessageElementType `json:"type"` + ActionID string `json:"action_id,omitempty"` + FileTypes []string `json:"filetypes,omitempty"` + MaxFiles int `json:"max_files,omitempty"` +} + +// ElementType returns the type of the Element +func (s FileInputBlockElement) ElementType() MessageElementType { + return s.Type +} + +// NewFileInputBlockElement returns an instance of a file input element +func NewFileInputBlockElement(actionID string) *FileInputBlockElement { + return &FileInputBlockElement{ + Type: METFileInput, + ActionID: actionID, + } +} + +// WithFileTypes sets the file types that can be uploaded +func (s *FileInputBlockElement) WithFileTypes(fileTypes ...string) *FileInputBlockElement { + s.FileTypes = fileTypes + return s +} + +// WithMaxFiles sets the maximum number of files that can be uploaded +func (s *FileInputBlockElement) WithMaxFiles(maxFiles int) *FileInputBlockElement { + s.MaxFiles = maxFiles + return s +} diff --git a/vendor/github.com/slack-go/slack/block_file.go b/vendor/github.com/slack-go/slack/block_file.go new file mode 100644 index 000000000..2f669b02a --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_file.go @@ -0,0 +1,31 @@ +package slack + +// FileBlock defines data that is used to display a remote file. +// +// More Information: https://api.slack.com/reference/block-kit/blocks#file +type FileBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + ExternalID string `json:"external_id"` + Source string `json:"source"` +} + +// BlockType returns the type of the block +func (s FileBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s FileBlock) ID() string { + return s.BlockID +} + +// NewFileBlock returns a new instance of a file block +func NewFileBlock(blockID string, externalID string, source string) *FileBlock { + return &FileBlock{ + Type: MBTFile, + BlockID: blockID, + ExternalID: externalID, + Source: source, + } +} diff --git a/vendor/github.com/slack-go/slack/block_header.go b/vendor/github.com/slack-go/slack/block_header.go new file mode 100644 index 000000000..3afb4c95f --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_header.go @@ -0,0 +1,43 @@ +package slack + +// HeaderBlock defines a new block of type header +// +// More Information: https://api.slack.com/reference/messaging/blocks#header +type HeaderBlock struct { + Type MessageBlockType `json:"type"` + Text *TextBlockObject `json:"text,omitempty"` + BlockID string `json:"block_id,omitempty"` +} + +// BlockType returns the type of the block +func (s HeaderBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s HeaderBlock) ID() string { + return s.BlockID +} + +// HeaderBlockOption allows configuration of options for a new header block +type HeaderBlockOption func(*HeaderBlock) + +func HeaderBlockOptionBlockID(blockID string) HeaderBlockOption { + return func(block *HeaderBlock) { + block.BlockID = blockID + } +} + +// NewHeaderBlock returns a new instance of a header block to be rendered +func NewHeaderBlock(textObj *TextBlockObject, options ...HeaderBlockOption) *HeaderBlock { + block := HeaderBlock{ + Type: MBTHeader, + Text: textObj, + } + + for _, option := range options { + option(&block) + } + + return &block +} diff --git a/vendor/github.com/slack-go/slack/block_image.go b/vendor/github.com/slack-go/slack/block_image.go new file mode 100644 index 000000000..2a914e5a0 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_image.go @@ -0,0 +1,55 @@ +package slack + +// ImageBlock defines data required to display an image as a block element +// +// More Information: https://api.slack.com/reference/messaging/blocks#image +type ImageBlock struct { + Type MessageBlockType `json:"type"` + ImageURL string `json:"image_url,omitempty"` + AltText string `json:"alt_text"` + BlockID string `json:"block_id,omitempty"` + Title *TextBlockObject `json:"title,omitempty"` + SlackFile *SlackFileObject `json:"slack_file,omitempty"` +} + +// ID returns the ID of the block +func (s ImageBlock) ID() string { + return s.BlockID +} + +// SlackFileObject Defines an object containing Slack file information to be used in an +// image block or image element. +// +// More Information: https://api.slack.com/reference/block-kit/composition-objects#slack_file +type SlackFileObject struct { + ID string `json:"id,omitempty"` + URL string `json:"url,omitempty"` +} + +// BlockType returns the type of the block +func (s ImageBlock) BlockType() MessageBlockType { + return s.Type +} + +// NewImageBlock returns an instance of a new Image Block type +func NewImageBlock(imageURL, altText, blockID string, title *TextBlockObject) *ImageBlock { + return &ImageBlock{ + Type: MBTImage, + ImageURL: imageURL, + AltText: altText, + BlockID: blockID, + Title: title, + } +} + +// NewImageBlockSlackFile returns an instance of a new Image Block type +// TODO: BREAKING CHANGE - This should be combined with the function above +func NewImageBlockSlackFile(slackFile *SlackFileObject, altText string, blockID string, title *TextBlockObject) *ImageBlock { + return &ImageBlock{ + Type: MBTImage, + SlackFile: slackFile, + AltText: altText, + BlockID: blockID, + Title: title, + } +} diff --git a/vendor/github.com/slack-go/slack/block_input.go b/vendor/github.com/slack-go/slack/block_input.go new file mode 100644 index 000000000..f74eda6d2 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_input.go @@ -0,0 +1,47 @@ +package slack + +// InputBlock defines data that is used to display user input fields. +// +// More Information: https://api.slack.com/reference/block-kit/blocks#input +type InputBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + Label *TextBlockObject `json:"label"` + Element BlockElement `json:"element"` + Hint *TextBlockObject `json:"hint,omitempty"` + Optional bool `json:"optional,omitempty"` + DispatchAction bool `json:"dispatch_action,omitempty"` +} + +// BlockType returns the type of the block +func (s InputBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s InputBlock) ID() string { + return s.BlockID +} + +// NewInputBlock returns a new instance of an input block +func NewInputBlock(blockID string, label, hint *TextBlockObject, element BlockElement) *InputBlock { + return &InputBlock{ + Type: MBTInput, + BlockID: blockID, + Label: label, + Element: element, + Hint: hint, + } +} + +// WithOptional sets the optional flag on the input block +func (s *InputBlock) WithOptional(optional bool) *InputBlock { + s.Optional = optional + return s +} + +// WithDispatchAction sets the dispatch action flag on the input block +func (s *InputBlock) WithDispatchAction(dispatchAction bool) *InputBlock { + s.DispatchAction = dispatchAction + return s +} diff --git a/vendor/github.com/slack-go/slack/block_markdown.go b/vendor/github.com/slack-go/slack/block_markdown.go new file mode 100644 index 000000000..e22a0d16d --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_markdown.go @@ -0,0 +1,34 @@ +package slack + +// MarkdownBlock defines a block that lets you use markdown to format your text. +// +// This block can be used with AI apps when you expect a markdown response from an LLM +// that can get lost in translation rendering in Slack. Providing it in a markdown block +// leaves the translating to Slack to ensure your message appears as intended. Note that +// passing a single block may result in multiple blocks after translation. +// +// More Information: https://api.slack.com/reference/block-kit/blocks#markdown +type MarkdownBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + Text string `json:"text"` +} + +// BlockType returns the type of the block +func (s MarkdownBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s MarkdownBlock) ID() string { + return s.BlockID +} + +// NewMarkdownBlock returns an instance of a new Markdown Block type +func NewMarkdownBlock(blockID, text string) *MarkdownBlock { + return &MarkdownBlock{ + Type: MBTMarkdown, + BlockID: blockID, + Text: text, + } +} diff --git a/vendor/github.com/slack-go/slack/block_object.go b/vendor/github.com/slack-go/slack/block_object.go new file mode 100644 index 000000000..fd73b6c4a --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_object.go @@ -0,0 +1,274 @@ +package slack + +import ( + "encoding/json" + "errors" +) + +// Block Objects are also known as Composition Objects +// +// For more information: https://api.slack.com/reference/messaging/composition-objects + +// BlockObject defines an interface that all block object types should +// implement. +// @TODO: Is this interface needed? + +// blockObject object types +const ( + MarkdownType = "mrkdwn" + PlainTextType = "plain_text" + // The following objects don't actually have types and their corresponding + // const values are just for internal use + motConfirmation = "confirm" + motOption = "option" + motOptionGroup = "option_group" +) + +type MessageObjectType string + +type blockObject interface { + validateType() MessageObjectType +} + +type BlockObjects struct { + TextObjects []*TextBlockObject + ConfirmationObjects []*ConfirmationBlockObject + OptionObjects []*OptionBlockObject + OptionGroupObjects []*OptionGroupBlockObject +} + +// UnmarshalJSON implements the Unmarshaller interface for BlockObjects, so that any JSON +// unmarshalling is delegated and proper type determination can be made before unmarshal +func (b *BlockObjects) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + for _, r := range raw { + var obj map[string]interface{} + err := json.Unmarshal(r, &obj) + if err != nil { + return err + } + + blockObjectType := getBlockObjectType(obj) + + switch blockObjectType { + case PlainTextType, MarkdownType: + object, err := unmarshalBlockObject(r, &TextBlockObject{}) + if err != nil { + return err + } + b.TextObjects = append(b.TextObjects, object.(*TextBlockObject)) + case motConfirmation: + object, err := unmarshalBlockObject(r, &ConfirmationBlockObject{}) + if err != nil { + return err + } + b.ConfirmationObjects = append(b.ConfirmationObjects, object.(*ConfirmationBlockObject)) + case motOption: + object, err := unmarshalBlockObject(r, &OptionBlockObject{}) + if err != nil { + return err + } + b.OptionObjects = append(b.OptionObjects, object.(*OptionBlockObject)) + case motOptionGroup: + object, err := unmarshalBlockObject(r, &OptionGroupBlockObject{}) + if err != nil { + return err + } + b.OptionGroupObjects = append(b.OptionGroupObjects, object.(*OptionGroupBlockObject)) + + } + } + + return nil +} + +// Ideally would have a better way to identify the block objects for +// type casting at time of unmarshalling, should be adapted if possible +// to accomplish in a more reliable manner. +func getBlockObjectType(obj map[string]interface{}) string { + if t, ok := obj["type"].(string); ok { + return t + } + if _, ok := obj["confirm"].(string); ok { + return "confirm" + } + if _, ok := obj["options"].(string); ok { + return "option_group" + } + if _, ok := obj["text"].(string); ok { + if _, ok := obj["value"].(string); ok { + return "option" + } + } + return "" +} + +func unmarshalBlockObject(r json.RawMessage, object blockObject) (blockObject, error) { + err := json.Unmarshal(r, object) + if err != nil { + return nil, err + } + return object, nil +} + +// TextBlockObject defines a text element object to be used with blocks +// +// More Information: https://api.slack.com/reference/messaging/composition-objects#text +type TextBlockObject struct { + Type string `json:"type"` + Text string `json:"text"` + Emoji *bool `json:"emoji,omitempty"` + Verbatim bool `json:"verbatim,omitempty"` +} + +// validateType enforces block objects for element and block parameters +func (s TextBlockObject) validateType() MessageObjectType { + return MessageObjectType(s.Type) +} + +// validateType enforces block objects for element and block parameters +func (s TextBlockObject) MixedElementType() MixedElementType { + return MixedElementText +} + +// Validate checks if TextBlockObject has valid values +func (s TextBlockObject) Validate() error { + if s.Type != "plain_text" && s.Type != "mrkdwn" { + return errors.New("type must be either of plain_text or mrkdwn") + } + + if s.Type == "mrkdwn" && s.Emoji != nil { + return errors.New("emoji cannot be set for mrkdwn type") + } + + // https://api.slack.com/reference/block-kit/composition-objects#text__fields + if len(s.Text) == 0 { + return errors.New("text must have a minimum length of 1") + } + + // https://api.slack.com/reference/block-kit/composition-objects#text__fields + if len(s.Text) > 3000 { + return errors.New("text cannot be longer than 3000 characters") + } + + return nil +} + +// NewTextBlockObject returns an instance of a new Text Block Object +// +// If you want to create a mrkdwn object, you should set the emoji parameter to false. The +// reason is that Slack doesn't accept emoji in mrkdwn. +func NewTextBlockObject(elementType, text string, emoji bool, verbatim bool) *TextBlockObject { + // If we're trying to build a mrkdwn object, we can't send emoji at all. I think the + // right approach here is to be a bit clever, and not break the function interface. + // + // So, here's the plan: + // 1. If the type is mrkdwn, set emoji to nil, regardless of what the user passed in + // 2. Else, set emoji to the value passed in + var emojiPtr *bool + + if elementType == "mrkdwn" { + emojiPtr = nil + } else { + emojiPtr = &emoji + } + + return &TextBlockObject{ + Type: elementType, + Text: text, + Emoji: emojiPtr, + Verbatim: verbatim, + } +} + +// BlockType returns the type of the block +func (t TextBlockObject) BlockType() MessageBlockType { + if t.Type == "mrkdwn" { + return MarkdownType + } + return PlainTextType +} + +// ConfirmationBlockObject defines a dialog that provides a confirmation step to +// any interactive element. This dialog will ask the user to confirm their action by +// offering a confirm and deny buttons. +// +// More Information: https://api.slack.com/reference/messaging/composition-objects#confirm +type ConfirmationBlockObject struct { + Title *TextBlockObject `json:"title"` + Text *TextBlockObject `json:"text"` + Confirm *TextBlockObject `json:"confirm"` + Deny *TextBlockObject `json:"deny,omitempty"` + Style Style `json:"style,omitempty"` +} + +// validateType enforces block objects for element and block parameters +func (s ConfirmationBlockObject) validateType() MessageObjectType { + return motConfirmation +} + +// WithStyle add styling to confirmation object +func (s *ConfirmationBlockObject) WithStyle(style Style) *ConfirmationBlockObject { + s.Style = style + return s +} + +// NewConfirmationBlockObject returns an instance of a new Confirmation Block Object +func NewConfirmationBlockObject(title, text, confirm, deny *TextBlockObject) *ConfirmationBlockObject { + return &ConfirmationBlockObject{ + Title: title, + Text: text, + Confirm: confirm, + Deny: deny, + } +} + +// OptionBlockObject represents a single selectable item in a select menu +// +// More Information: https://api.slack.com/reference/messaging/composition-objects#option +type OptionBlockObject struct { + Text *TextBlockObject `json:"text"` + Value string `json:"value"` + Description *TextBlockObject `json:"description,omitempty"` + URL string `json:"url,omitempty"` +} + +// NewOptionBlockObject returns an instance of a new Option Block Element +func NewOptionBlockObject(value string, text, description *TextBlockObject) *OptionBlockObject { + return &OptionBlockObject{ + Text: text, + Value: value, + Description: description, + } +} + +// validateType enforces block objects for element and block parameters +func (s OptionBlockObject) validateType() MessageObjectType { + return motOption +} + +// OptionGroupBlockObject Provides a way to group options in a select menu. +// +// More Information: https://api.slack.com/reference/messaging/composition-objects#option-group +type OptionGroupBlockObject struct { + Label *TextBlockObject `json:"label,omitempty"` + Options []*OptionBlockObject `json:"options"` +} + +// validateType enforces block objects for element and block parameters +func (s OptionGroupBlockObject) validateType() MessageObjectType { + return motOptionGroup +} + +// NewOptionGroupBlockElement returns an instance of a new option group block element +func NewOptionGroupBlockElement(label *TextBlockObject, options ...*OptionBlockObject) *OptionGroupBlockObject { + return &OptionGroupBlockObject{ + Label: label, + Options: options, + } +} diff --git a/vendor/github.com/slack-go/slack/block_rich_text.go b/vendor/github.com/slack-go/slack/block_rich_text.go new file mode 100644 index 000000000..73233d23a --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_rich_text.go @@ -0,0 +1,550 @@ +package slack + +import ( + "encoding/json" +) + +// RichTextBlock defines a new block of type rich_text. +// More Information: https://api.slack.com/changelog/2019-09-what-they-see-is-what-you-get-and-more-and-less +type RichTextBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` + Elements []RichTextElement `json:"elements"` +} + +func (b RichTextBlock) BlockType() MessageBlockType { + return b.Type +} + +// ID returns the ID of the block +func (s RichTextBlock) ID() string { + return s.BlockID +} + +func (e *RichTextBlock) UnmarshalJSON(b []byte) error { + var raw struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id"` + RawElements []json.RawMessage `json:"elements"` + } + if string(b) == "{}" { + return nil + } + if err := json.Unmarshal(b, &raw); err != nil { + return err + } + elems := make([]RichTextElement, 0, len(raw.RawElements)) + for _, r := range raw.RawElements { + var s struct { + Type RichTextElementType `json:"type"` + } + if err := json.Unmarshal(r, &s); err != nil { + return err + } + var elem RichTextElement + switch s.Type { + case RTESection: + elem = &RichTextSection{} + case RTEList: + elem = &RichTextList{} + case RTEQuote: + elem = &RichTextQuote{} + case RTEPreformatted: + elem = &RichTextPreformatted{} + default: + elems = append(elems, &RichTextUnknown{ + Type: s.Type, + Raw: string(r), + }) + continue + } + if err := json.Unmarshal(r, &elem); err != nil { + return err + } + elems = append(elems, elem) + } + *e = RichTextBlock{ + Type: raw.Type, + BlockID: raw.BlockID, + Elements: elems, + } + return nil +} + +// NewRichTextBlock returns a new instance of RichText Block. +func NewRichTextBlock(blockID string, elements ...RichTextElement) *RichTextBlock { + return &RichTextBlock{ + Type: MBTRichText, + BlockID: blockID, + Elements: elements, + } +} + +type RichTextElementType string + +type RichTextElement interface { + RichTextElementType() RichTextElementType +} + +const ( + RTEList RichTextElementType = "rich_text_list" + RTEPreformatted RichTextElementType = "rich_text_preformatted" + RTEQuote RichTextElementType = "rich_text_quote" + RTESection RichTextElementType = "rich_text_section" + RTEUnknown RichTextElementType = "rich_text_unknown" +) + +type RichTextUnknown struct { + Type RichTextElementType + Raw string +} + +func (u RichTextUnknown) RichTextElementType() RichTextElementType { + return u.Type +} + +type RichTextListElementType string + +const ( + RTEListOrdered RichTextListElementType = "ordered" + RTEListBullet RichTextListElementType = "bullet" +) + +type RichTextList struct { + Type RichTextElementType `json:"type"` + Elements []RichTextElement `json:"elements"` + Style RichTextListElementType `json:"style"` + Indent int `json:"indent"` + Border int `json:"border"` + Offset int `json:"offset"` +} + +// NewRichTextList returns a new rich text list element. +func NewRichTextList(style RichTextListElementType, indent int, elements ...RichTextElement) *RichTextList { + return &RichTextList{ + Type: RTEList, + Elements: elements, + Style: style, + Indent: indent, + } +} + +// ElementType returns the type of the Element +func (s RichTextList) RichTextElementType() RichTextElementType { + return s.Type +} + +func (e *RichTextList) UnmarshalJSON(b []byte) error { + var raw struct { + RawElements []json.RawMessage `json:"elements"` + Style RichTextListElementType `json:"style"` + Indent int `json:"indent"` + Border int `json:"border"` + Offset int `json:"offset"` + } + if string(b) == "{}" { + return nil + } + if err := json.Unmarshal(b, &raw); err != nil { + return err + } + elems := make([]RichTextElement, 0, len(raw.RawElements)) + for _, r := range raw.RawElements { + var s struct { + Type RichTextElementType `json:"type"` + } + if err := json.Unmarshal(r, &s); err != nil { + return err + } + var elem RichTextElement + switch s.Type { + case RTESection: + elem = &RichTextSection{} + case RTEList: + elem = &RichTextList{} + case RTEQuote: + elem = &RichTextQuote{} + case RTEPreformatted: + elem = &RichTextPreformatted{} + default: + elems = append(elems, &RichTextUnknown{ + Type: s.Type, + Raw: string(r), + }) + continue + } + if err := json.Unmarshal(r, elem); err != nil { + return err + } + elems = append(elems, elem) + } + *e = RichTextList{ + Type: RTEList, + Elements: elems, + Style: raw.Style, + Indent: raw.Indent, + Border: raw.Border, + Offset: raw.Offset, + } + return nil +} + +type RichTextSection struct { + Type RichTextElementType `json:"type"` + Elements []RichTextSectionElement `json:"elements"` +} + +// RichTextElementType returns the type of the Element +func (s RichTextSection) RichTextElementType() RichTextElementType { + return s.Type +} + +func (e *RichTextSection) UnmarshalJSON(b []byte) error { + var raw struct { + RawElements []json.RawMessage `json:"elements"` + Type RichTextElementType `json:"type"` + } + if string(b) == "{}" { + return nil + } + if err := json.Unmarshal(b, &raw); err != nil { + return err + } + elems := make([]RichTextSectionElement, 0, len(raw.RawElements)) + for _, r := range raw.RawElements { + var s struct { + Type RichTextSectionElementType `json:"type"` + } + if err := json.Unmarshal(r, &s); err != nil { + return err + } + var elem RichTextSectionElement + switch s.Type { + case RTSEText: + elem = &RichTextSectionTextElement{} + case RTSEChannel: + elem = &RichTextSectionChannelElement{} + case RTSEUser: + elem = &RichTextSectionUserElement{} + case RTSEEmoji: + elem = &RichTextSectionEmojiElement{} + case RTSELink: + elem = &RichTextSectionLinkElement{} + case RTSETeam: + elem = &RichTextSectionTeamElement{} + case RTSEUserGroup: + elem = &RichTextSectionUserGroupElement{} + case RTSEDate: + elem = &RichTextSectionDateElement{} + case RTSEBroadcast: + elem = &RichTextSectionBroadcastElement{} + case RTSEColor: + elem = &RichTextSectionColorElement{} + default: + elems = append(elems, &RichTextSectionUnknownElement{ + Type: s.Type, + Raw: string(r), + }) + continue + } + if err := json.Unmarshal(r, elem); err != nil { + return err + } + elems = append(elems, elem) + } + if raw.Type == "" { + raw.Type = RTESection + } + *e = RichTextSection{ + Type: raw.Type, + Elements: elems, + } + return nil +} + +// NewRichTextSectionBlockElement . +func NewRichTextSection(elements ...RichTextSectionElement) *RichTextSection { + return &RichTextSection{ + Type: RTESection, + Elements: elements, + } +} + +type RichTextSectionElementType string + +const ( + RTSEBroadcast RichTextSectionElementType = "broadcast" + RTSEChannel RichTextSectionElementType = "channel" + RTSEColor RichTextSectionElementType = "color" + RTSEDate RichTextSectionElementType = "date" + RTSEEmoji RichTextSectionElementType = "emoji" + RTSELink RichTextSectionElementType = "link" + RTSETeam RichTextSectionElementType = "team" + RTSEText RichTextSectionElementType = "text" + RTSEUser RichTextSectionElementType = "user" + RTSEUserGroup RichTextSectionElementType = "usergroup" + + RTSEUnknown RichTextSectionElementType = "unknown" +) + +type RichTextSectionElement interface { + RichTextSectionElementType() RichTextSectionElementType +} + +type RichTextSectionTextStyle struct { + Bold bool `json:"bold,omitempty"` + Italic bool `json:"italic,omitempty"` + Strike bool `json:"strike,omitempty"` + Code bool `json:"code,omitempty"` +} + +type RichTextSectionTextElement struct { + Type RichTextSectionElementType `json:"type"` + Text string `json:"text"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionTextElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionTextElement(text string, style *RichTextSectionTextStyle) *RichTextSectionTextElement { + return &RichTextSectionTextElement{ + Type: RTSEText, + Text: text, + Style: style, + } +} + +type RichTextSectionChannelElement struct { + Type RichTextSectionElementType `json:"type"` + ChannelID string `json:"channel_id"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionChannelElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionChannelElement(channelID string, style *RichTextSectionTextStyle) *RichTextSectionChannelElement { + return &RichTextSectionChannelElement{ + Type: RTSEText, + ChannelID: channelID, + Style: style, + } +} + +type RichTextSectionUserElement struct { + Type RichTextSectionElementType `json:"type"` + UserID string `json:"user_id"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionUserElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionUserElement(userID string, style *RichTextSectionTextStyle) *RichTextSectionUserElement { + return &RichTextSectionUserElement{ + Type: RTSEUser, + UserID: userID, + Style: style, + } +} + +type RichTextSectionEmojiElement struct { + Type RichTextSectionElementType `json:"type"` + Name string `json:"name"` + SkinTone int `json:"skin_tone,omitempty"` + Unicode string `json:"unicode,omitempty"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionEmojiElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionEmojiElement(name string, skinTone int, style *RichTextSectionTextStyle) *RichTextSectionEmojiElement { + return &RichTextSectionEmojiElement{ + Type: RTSEEmoji, + Name: name, + SkinTone: skinTone, + Style: style, + } +} + +type RichTextSectionLinkElement struct { + Type RichTextSectionElementType `json:"type"` + URL string `json:"url"` + Text string `json:"text,omitempty"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionLinkElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionLinkElement(url, text string, style *RichTextSectionTextStyle) *RichTextSectionLinkElement { + return &RichTextSectionLinkElement{ + Type: RTSELink, + URL: url, + Text: text, + Style: style, + } +} + +type RichTextSectionTeamElement struct { + Type RichTextSectionElementType `json:"type"` + TeamID string `json:"team_id"` + Style *RichTextSectionTextStyle `json:"style,omitempty"` +} + +func (r RichTextSectionTeamElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionTeamElement(teamID string, style *RichTextSectionTextStyle) *RichTextSectionTeamElement { + return &RichTextSectionTeamElement{ + Type: RTSETeam, + TeamID: teamID, + Style: style, + } +} + +type RichTextSectionUserGroupElement struct { + Type RichTextSectionElementType `json:"type"` + UsergroupID string `json:"usergroup_id"` +} + +func (r RichTextSectionUserGroupElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionUserGroupElement(usergroupID string) *RichTextSectionUserGroupElement { + return &RichTextSectionUserGroupElement{ + Type: RTSEUserGroup, + UsergroupID: usergroupID, + } +} + +type RichTextSectionDateElement struct { + Type RichTextSectionElementType `json:"type"` + Timestamp JSONTime `json:"timestamp"` + Format string `json:"format"` + URL *string `json:"url,omitempty"` + Fallback *string `json:"fallback,omitempty"` +} + +func (r RichTextSectionDateElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionDateElement(timestamp int64, format string, url *string, fallback *string) *RichTextSectionDateElement { + return &RichTextSectionDateElement{ + Type: RTSEDate, + Timestamp: JSONTime(timestamp), + Format: format, + URL: url, + Fallback: fallback, + } +} + +type RichTextSectionBroadcastElement struct { + Type RichTextSectionElementType `json:"type"` + Range string `json:"range"` +} + +func (r RichTextSectionBroadcastElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionBroadcastElement(rangeStr string) *RichTextSectionBroadcastElement { + return &RichTextSectionBroadcastElement{ + Type: RTSEBroadcast, + Range: rangeStr, + } +} + +type RichTextSectionColorElement struct { + Type RichTextSectionElementType `json:"type"` + Value string `json:"value"` +} + +func (r RichTextSectionColorElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +func NewRichTextSectionColorElement(value string) *RichTextSectionColorElement { + return &RichTextSectionColorElement{ + Type: RTSEColor, + Value: value, + } +} + +type RichTextSectionUnknownElement struct { + Type RichTextSectionElementType `json:"type"` + Raw string +} + +func (r RichTextSectionUnknownElement) RichTextSectionElementType() RichTextSectionElementType { + return r.Type +} + +// RichTextQuote represents rich_text_quote element type. +type RichTextQuote RichTextSection + +// RichTextElementType returns the type of the Element +func (s *RichTextQuote) RichTextElementType() RichTextElementType { + return s.Type +} + +func (s *RichTextQuote) UnmarshalJSON(b []byte) error { + // reusing the RichTextSection struct, as it's the same as RichTextQuote. + var rts RichTextSection + if err := json.Unmarshal(b, &rts); err != nil { + return err + } + *s = RichTextQuote(rts) + s.Type = RTEQuote + return nil +} + +// RichTextPreformatted represents rich_text_quote element type. +type RichTextPreformatted struct { + RichTextSection + Border int `json:"border"` +} + +// RichTextElementType returns the type of the Element +func (s *RichTextPreformatted) RichTextElementType() RichTextElementType { + return s.Type +} + +func (s *RichTextPreformatted) UnmarshalJSON(b []byte) error { + var rts RichTextSection + if err := json.Unmarshal(b, &rts); err != nil { + return err + } + // we define standalone fields because we need to unmarshal the border + // field. We can not directly unmarshal the data into + // RichTextPreformatted because it will cause an infinite loop. We also + // can not define a struct with embedded RichTextSection and Border fields + // because the json package will not unmarshal the data into the + // standalone fields, once it sees UnmarshalJSON method on the embedded + // struct. The drawback is that we have to process the data twice, and + // have to define a standalone struct with the same set of fields as the + // original struct, which may become a maintenance burden (i.e. update the + // fields in two places, should it ever change). + var standalone struct { + Border int `json:"border"` + } + if err := json.Unmarshal(b, &standalone); err != nil { + return err + } + *s = RichTextPreformatted{ + RichTextSection: rts, + Border: standalone.Border, + } + s.Type = RTEPreformatted + return nil +} diff --git a/vendor/github.com/slack-go/slack/block_section.go b/vendor/github.com/slack-go/slack/block_section.go new file mode 100644 index 000000000..0d2352a03 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_section.go @@ -0,0 +1,57 @@ +package slack + +// SectionBlock defines a new block of type section +// +// More Information: https://api.slack.com/reference/messaging/blocks#section +type SectionBlock struct { + Type MessageBlockType `json:"type"` + Text *TextBlockObject `json:"text,omitempty"` + BlockID string `json:"block_id,omitempty"` + Fields []*TextBlockObject `json:"fields,omitempty"` + Accessory *Accessory `json:"accessory,omitempty"` + Expand bool `json:"expand,omitempty"` +} + +// BlockType returns the type of the block +func (s SectionBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s SectionBlock) ID() string { + return s.BlockID +} + +// SectionBlockOption allows configuration of options for a new section block +type SectionBlockOption func(*SectionBlock) + +func SectionBlockOptionBlockID(blockID string) SectionBlockOption { + return func(block *SectionBlock) { + block.BlockID = blockID + } +} + +// SectionBlockOptionExpand allows long text to be auto-expanded when displaying +// +// @see https://api.slack.com/reference/block-kit/blocks#section +func SectionBlockOptionExpand(shouldExpand bool) SectionBlockOption { + return func(block *SectionBlock) { + block.Expand = shouldExpand + } +} + +// NewSectionBlock returns a new instance of a section block to be rendered +func NewSectionBlock(textObj *TextBlockObject, fields []*TextBlockObject, accessory *Accessory, options ...SectionBlockOption) *SectionBlock { + block := SectionBlock{ + Type: MBTSection, + Text: textObj, + Fields: fields, + Accessory: accessory, + } + + for _, option := range options { + option(&block) + } + + return &block +} diff --git a/vendor/github.com/slack-go/slack/block_unknown.go b/vendor/github.com/slack-go/slack/block_unknown.go new file mode 100644 index 000000000..7a49a2c8d --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_unknown.go @@ -0,0 +1,18 @@ +package slack + +// UnknownBlock represents a block type that is not yet known. This block type exists to prevent Slack from introducing +// new and unknown block types that break this library. +type UnknownBlock struct { + Type MessageBlockType `json:"type"` + BlockID string `json:"block_id,omitempty"` +} + +// BlockType returns the type of the block +func (b UnknownBlock) BlockType() MessageBlockType { + return b.Type +} + +// ID returns the ID of the block +func (s UnknownBlock) ID() string { + return s.BlockID +} diff --git a/vendor/github.com/slack-go/slack/block_video.go b/vendor/github.com/slack-go/slack/block_video.go new file mode 100644 index 000000000..4d6739c46 --- /dev/null +++ b/vendor/github.com/slack-go/slack/block_video.go @@ -0,0 +1,70 @@ +package slack + +// VideoBlock defines data required to display a video as a block element +// +// More Information: https://api.slack.com/reference/block-kit/blocks#video +type VideoBlock struct { + Type MessageBlockType `json:"type"` + VideoURL string `json:"video_url"` + ThumbnailURL string `json:"thumbnail_url"` + AltText string `json:"alt_text"` + Title *TextBlockObject `json:"title"` + BlockID string `json:"block_id,omitempty"` + TitleURL string `json:"title_url,omitempty"` + AuthorName string `json:"author_name,omitempty"` + ProviderName string `json:"provider_name,omitempty"` + ProviderIconURL string `json:"provider_icon_url,omitempty"` + Description *TextBlockObject `json:"description,omitempty"` +} + +// BlockType returns the type of the block +func (s VideoBlock) BlockType() MessageBlockType { + return s.Type +} + +// ID returns the ID of the block +func (s VideoBlock) ID() string { + return s.BlockID +} + +// NewVideoBlock returns an instance of a new Video Block type +func NewVideoBlock(videoURL, thumbnailURL, altText, blockID string, title *TextBlockObject) *VideoBlock { + return &VideoBlock{ + Type: MBTVideo, + VideoURL: videoURL, + ThumbnailURL: thumbnailURL, + AltText: altText, + BlockID: blockID, + Title: title, + } +} + +// WithAuthorName sets the author name for the VideoBlock +func (s *VideoBlock) WithAuthorName(authorName string) *VideoBlock { + s.AuthorName = authorName + return s +} + +// WithTitleURL sets the title URL for the VideoBlock +func (s *VideoBlock) WithTitleURL(titleURL string) *VideoBlock { + s.TitleURL = titleURL + return s +} + +// WithDescription sets the description for the VideoBlock +func (s *VideoBlock) WithDescription(description *TextBlockObject) *VideoBlock { + s.Description = description + return s +} + +// WithProviderIconURL sets the provider icon URL for the VideoBlock +func (s *VideoBlock) WithProviderIconURL(providerIconURL string) *VideoBlock { + s.ProviderIconURL = providerIconURL + return s +} + +// WithProviderName sets the provider name for the VideoBlock +func (s *VideoBlock) WithProviderName(providerName string) *VideoBlock { + s.ProviderName = providerName + return s +} diff --git a/vendor/github.com/slack-go/slack/bookmarks.go b/vendor/github.com/slack-go/slack/bookmarks.go new file mode 100644 index 000000000..1f07e59b0 --- /dev/null +++ b/vendor/github.com/slack-go/slack/bookmarks.go @@ -0,0 +1,169 @@ +package slack + +import ( + "context" + "net/url" +) + +type Bookmark struct { + ID string `json:"id"` + ChannelID string `json:"channel_id"` + Title string `json:"title"` + Link string `json:"link"` + Emoji string `json:"emoji"` + IconURL string `json:"icon_url"` + Type string `json:"type"` + Created JSONTime `json:"date_created"` + Updated JSONTime `json:"date_updated"` + Rank string `json:"rank"` + + LastUpdatedByUserID string `json:"last_updated_by_user_id"` + LastUpdatedByTeamID string `json:"last_updated_by_team_id"` + + ShortcutID string `json:"shortcut_id"` + EntityID string `json:"entity_id"` + AppID string `json:"app_id"` +} + +type AddBookmarkParameters struct { + Title string // A required title for the bookmark + Type string // A required type for the bookmark + Link string // URL required for type:link + Emoji string // An optional emoji + EntityID string + ParentID string +} + +type EditBookmarkParameters struct { + Title *string // Change the title. Set to "" to clear + Emoji *string // Change the emoji. Set to "" to clear + Link string // Change the link +} + +type addBookmarkResponse struct { + Bookmark Bookmark `json:"bookmark"` + SlackResponse +} + +type editBookmarkResponse struct { + Bookmark Bookmark `json:"bookmark"` + SlackResponse +} + +type listBookmarksResponse struct { + Bookmarks []Bookmark `json:"bookmarks"` + SlackResponse +} + +// AddBookmark adds a bookmark in a channel. +// For more details, see AddBookmarkContext documentation. +func (api *Client) AddBookmark(channelID string, params AddBookmarkParameters) (Bookmark, error) { + return api.AddBookmarkContext(context.Background(), channelID, params) +} + +// AddBookmarkContext adds a bookmark in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/bookmarks.add +func (api *Client) AddBookmarkContext(ctx context.Context, channelID string, params AddBookmarkParameters) (Bookmark, error) { + values := url.Values{ + "channel_id": {channelID}, + "token": {api.token}, + "title": {params.Title}, + "type": {params.Type}, + } + if params.Link != "" { + values.Set("link", params.Link) + } + if params.Emoji != "" { + values.Set("emoji", params.Emoji) + } + if params.EntityID != "" { + values.Set("entity_id", params.EntityID) + } + if params.ParentID != "" { + values.Set("parent_id", params.ParentID) + } + + response := &addBookmarkResponse{} + if err := api.postMethod(ctx, "bookmarks.add", values, response); err != nil { + return Bookmark{}, err + } + + return response.Bookmark, response.Err() +} + +// RemoveBookmark removes a bookmark from a channel. +// For more details, see RemoveBookmarkContext documentation. +func (api *Client) RemoveBookmark(channelID, bookmarkID string) error { + return api.RemoveBookmarkContext(context.Background(), channelID, bookmarkID) +} + +// RemoveBookmarkContext removes a bookmark from a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/bookmarks.remove +func (api *Client) RemoveBookmarkContext(ctx context.Context, channelID, bookmarkID string) error { + values := url.Values{ + "channel_id": {channelID}, + "token": {api.token}, + "bookmark_id": {bookmarkID}, + } + + response := &SlackResponse{} + if err := api.postMethod(ctx, "bookmarks.remove", values, response); err != nil { + return err + } + + return response.Err() +} + +// ListBookmarks returns all bookmarks for a channel. +// For more details, see ListBookmarksContext documentation. +func (api *Client) ListBookmarks(channelID string) ([]Bookmark, error) { + return api.ListBookmarksContext(context.Background(), channelID) +} + +// ListBookmarksContext returns all bookmarks for a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/bookmarks.edit +func (api *Client) ListBookmarksContext(ctx context.Context, channelID string) ([]Bookmark, error) { + values := url.Values{ + "channel_id": {channelID}, + "token": {api.token}, + } + + response := &listBookmarksResponse{} + err := api.postMethod(ctx, "bookmarks.list", values, response) + if err != nil { + return nil, err + } + return response.Bookmarks, response.Err() +} + +// EditBookmark edits a bookmark in a channel. +// For more details, see EditBookmarkContext documentation. +func (api *Client) EditBookmark(channelID, bookmarkID string, params EditBookmarkParameters) (Bookmark, error) { + return api.EditBookmarkContext(context.Background(), channelID, bookmarkID, params) +} + +// EditBookmarkContext edits a bookmark in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/bookmarks.edit +func (api *Client) EditBookmarkContext(ctx context.Context, channelID, bookmarkID string, params EditBookmarkParameters) (Bookmark, error) { + values := url.Values{ + "channel_id": {channelID}, + "token": {api.token}, + "bookmark_id": {bookmarkID}, + } + if params.Link != "" { + values.Set("link", params.Link) + } + if params.Emoji != nil { + values.Set("emoji", *params.Emoji) + } + if params.Title != nil { + values.Set("title", *params.Title) + } + + response := &editBookmarkResponse{} + if err := api.postMethod(ctx, "bookmarks.edit", values, response); err != nil { + return Bookmark{}, err + } + + return response.Bookmark, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/bots.go b/vendor/github.com/slack-go/slack/bots.go new file mode 100644 index 000000000..1ab946962 --- /dev/null +++ b/vendor/github.com/slack-go/slack/bots.go @@ -0,0 +1,69 @@ +package slack + +import ( + "context" + "net/url" +) + +// Bot contains information about a bot +type Bot struct { + ID string `json:"id"` + Name string `json:"name"` + Deleted bool `json:"deleted"` + UserID string `json:"user_id"` + AppID string `json:"app_id"` + Updated JSONTime `json:"updated"` + Icons Icons `json:"icons"` +} + +type botResponseFull struct { + Bot `json:"bot,omitempty"` // GetBotInfo + SlackResponse +} + +func (api *Client) botRequest(ctx context.Context, path string, values url.Values) (*botResponseFull, error) { + response := &botResponseFull{} + err := api.postMethod(ctx, path, values, response) + if err != nil { + return nil, err + } + + if err := response.Err(); err != nil { + return nil, err + } + + return response, nil +} + +type GetBotInfoParameters struct { + Bot string + TeamID string +} + +// GetBotInfo will retrieve the complete bot information. +// For more details, see GetBotInfoContext documentation. +func (api *Client) GetBotInfo(parameters GetBotInfoParameters) (*Bot, error) { + return api.GetBotInfoContext(context.Background(), parameters) +} + +// GetBotInfoContext will retrieve the complete bot information using a custom context. +// Slack API docs: https://api.slack.com/methods/bots.info +func (api *Client) GetBotInfoContext(ctx context.Context, parameters GetBotInfoParameters) (*Bot, error) { + values := url.Values{ + "token": {api.token}, + } + + if parameters.Bot != "" { + values.Add("bot", parameters.Bot) + } + + if parameters.TeamID != "" { + values.Add("team_id", parameters.TeamID) + } + + response, err := api.botRequest(ctx, "bots.info", values) + if err != nil { + return nil, err + } + return &response.Bot, nil +} diff --git a/vendor/github.com/slack-go/slack/calls.go b/vendor/github.com/slack-go/slack/calls.go new file mode 100644 index 000000000..2d6e91f16 --- /dev/null +++ b/vendor/github.com/slack-go/slack/calls.go @@ -0,0 +1,216 @@ +package slack + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + "time" +) + +type Call struct { + ID string `json:"id"` + Title string `json:"title"` + DateStart JSONTime `json:"date_start"` + DateEnd JSONTime `json:"date_end"` + ExternalUniqueID string `json:"external_unique_id"` + JoinURL string `json:"join_url"` + DesktopAppJoinURL string `json:"desktop_app_join_url"` + ExternalDisplayID string `json:"external_display_id"` + Participants []CallParticipant `json:"users"` + Channels []string `json:"channels"` +} + +// CallParticipant is a thin user representation which has a SlackID, ExternalID, or both. +// +// See: https://api.slack.com/apis/calls#users +type CallParticipant struct { + SlackID string `json:"slack_id,omitempty"` + ExternalID string `json:"external_id,omitempty"` + DisplayName string `json:"display_name,omitempty"` + AvatarURL string `json:"avatar_url,omitempty"` +} + +// Valid checks if the CallUser has a is valid with a SlackID or ExternalID or both. +func (u CallParticipant) Valid() bool { + return u.SlackID != "" || u.ExternalID != "" +} + +type AddCallParameters struct { + JoinURL string // Required + ExternalUniqueID string // Required + CreatedBy string // Required if using a bot token + Title string + DesktopAppJoinURL string + ExternalDisplayID string + DateStart JSONTime + Participants []CallParticipant +} + +type UpdateCallParameters struct { + Title string + DesktopAppJoinURL string + JoinURL string +} + +type EndCallParameters struct { + // Duration is the duration of the call in seconds. Omitted if 0. + Duration time.Duration +} + +type callResponse struct { + Call Call `json:"call"` + SlackResponse +} + +// AddCall adds a new Call to the Slack API. +func (api *Client) AddCall(params AddCallParameters) (Call, error) { + return api.AddCallContext(context.Background(), params) +} + +// AddCallContext adds a new Call to the Slack API. +func (api *Client) AddCallContext(ctx context.Context, params AddCallParameters) (Call, error) { + values := url.Values{ + "token": {api.token}, + "join_url": {params.JoinURL}, + "external_unique_id": {params.ExternalUniqueID}, + } + if params.CreatedBy != "" { + values.Set("created_by", params.CreatedBy) + } + if params.DateStart != 0 { + values.Set("date_start", strconv.FormatInt(int64(params.DateStart), 10)) + } + if params.DesktopAppJoinURL != "" { + values.Set("desktop_app_join_url", params.DesktopAppJoinURL) + } + if params.ExternalDisplayID != "" { + values.Set("external_display_id", params.ExternalDisplayID) + } + if params.Title != "" { + values.Set("title", params.Title) + } + if len(params.Participants) > 0 { + data, err := json.Marshal(params.Participants) + if err != nil { + return Call{}, err + } + values.Set("users", string(data)) + } + + response := &callResponse{} + if err := api.postMethod(ctx, "calls.add", values, response); err != nil { + return Call{}, err + } + + return response.Call, response.Err() +} + +// GetCallInfo returns information about a Call. +func (api *Client) GetCall(callID string) (Call, error) { + return api.GetCallContext(context.Background(), callID) +} + +// GetCallInfoContext returns information about a Call. +func (api *Client) GetCallContext(ctx context.Context, callID string) (Call, error) { + values := url.Values{ + "token": {api.token}, + "id": {callID}, + } + + response := &callResponse{} + if err := api.postMethod(ctx, "calls.info", values, response); err != nil { + return Call{}, err + } + return response.Call, response.Err() +} + +func (api *Client) UpdateCall(callID string, params UpdateCallParameters) (Call, error) { + return api.UpdateCallContext(context.Background(), callID, params) +} + +// UpdateCallContext updates a Call with the given parameters. +func (api *Client) UpdateCallContext(ctx context.Context, callID string, params UpdateCallParameters) (Call, error) { + values := url.Values{ + "token": {api.token}, + "id": {callID}, + } + + if params.DesktopAppJoinURL != "" { + values.Set("desktop_app_join_url", params.DesktopAppJoinURL) + } + if params.JoinURL != "" { + values.Set("join_url", params.JoinURL) + } + if params.Title != "" { + values.Set("title", params.Title) + } + + response := &callResponse{} + if err := api.postMethod(ctx, "calls.update", values, response); err != nil { + return Call{}, err + } + return response.Call, response.Err() +} + +// EndCall ends a Call. +func (api *Client) EndCall(callID string, params EndCallParameters) error { + return api.EndCallContext(context.Background(), callID, params) +} + +// EndCallContext ends a Call. +func (api *Client) EndCallContext(ctx context.Context, callID string, params EndCallParameters) error { + values := url.Values{ + "token": {api.token}, + "id": {callID}, + } + + if params.Duration != 0 { + values.Set("duration", strconv.FormatInt(int64(params.Duration.Seconds()), 10)) + } + + response := &SlackResponse{} + if err := api.postMethod(ctx, "calls.end", values, response); err != nil { + return err + } + return response.Err() +} + +// CallAddParticipants adds users to a Call. +func (api *Client) CallAddParticipants(callID string, participants []CallParticipant) error { + return api.CallAddParticipantsContext(context.Background(), callID, participants) +} + +// CallAddParticipantsContext adds users to a Call. +func (api *Client) CallAddParticipantsContext(ctx context.Context, callID string, participants []CallParticipant) error { + return api.setCallParticipants(ctx, "calls.participants.add", callID, participants) +} + +// CallRemoveParticipants removes users from a Call. +func (api *Client) CallRemoveParticipants(callID string, participants []CallParticipant) error { + return api.CallRemoveParticipantsContext(context.Background(), callID, participants) +} + +// CallRemoveParticipantsContext removes users from a Call. +func (api *Client) CallRemoveParticipantsContext(ctx context.Context, callID string, participants []CallParticipant) error { + return api.setCallParticipants(ctx, "calls.participants.remove", callID, participants) +} + +func (api *Client) setCallParticipants(ctx context.Context, method, callID string, participants []CallParticipant) error { + values := url.Values{ + "token": {api.token}, + "id": {callID}, + } + + data, err := json.Marshal(participants) + if err != nil { + return err + } + values.Set("users", string(data)) + + response := &SlackResponse{} + if err := api.postMethod(ctx, method, values, response); err != nil { + return err + } + return response.Err() +} diff --git a/vendor/github.com/slack-go/slack/canvas.go b/vendor/github.com/slack-go/slack/canvas.go new file mode 100644 index 000000000..5225afa35 --- /dev/null +++ b/vendor/github.com/slack-go/slack/canvas.go @@ -0,0 +1,264 @@ +package slack + +import ( + "context" + "encoding/json" + "net/url" +) + +type CanvasDetails struct { + CanvasID string `json:"canvas_id"` +} + +type DocumentContent struct { + Type string `json:"type"` + Markdown string `json:"markdown,omitempty"` +} + +type CanvasChange struct { + Operation string `json:"operation"` + SectionID string `json:"section_id,omitempty"` + DocumentContent DocumentContent `json:"document_content"` +} + +type EditCanvasParams struct { + CanvasID string `json:"canvas_id"` + Changes []CanvasChange `json:"changes"` +} + +type SetCanvasAccessParams struct { + CanvasID string `json:"canvas_id"` + AccessLevel string `json:"access_level"` + ChannelIDs []string `json:"channel_ids,omitempty"` + UserIDs []string `json:"user_ids,omitempty"` +} + +type DeleteCanvasAccessParams struct { + CanvasID string `json:"canvas_id"` + ChannelIDs []string `json:"channel_ids,omitempty"` + UserIDs []string `json:"user_ids,omitempty"` +} + +type LookupCanvasSectionsCriteria struct { + SectionTypes []string `json:"section_types,omitempty"` + ContainsText string `json:"contains_text,omitempty"` +} + +type LookupCanvasSectionsParams struct { + CanvasID string `json:"canvas_id"` + Criteria LookupCanvasSectionsCriteria `json:"criteria"` +} + +type CanvasSection struct { + ID string `json:"id"` +} + +type LookupCanvasSectionsResponse struct { + SlackResponse + Sections []CanvasSection `json:"sections"` +} + +// CreateCanvas creates a new canvas. +// For more details, see CreateCanvasContext documentation. +func (api *Client) CreateCanvas(title string, documentContent DocumentContent) (string, error) { + return api.CreateCanvasContext(context.Background(), title, documentContent) +} + +// CreateCanvasContext creates a new canvas with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.create +func (api *Client) CreateCanvasContext(ctx context.Context, title string, documentContent DocumentContent) (string, error) { + values := url.Values{ + "token": {api.token}, + } + if title != "" { + values.Add("title", title) + } + if documentContent.Type != "" { + documentContentJSON, err := json.Marshal(documentContent) + if err != nil { + return "", err + } + values.Add("document_content", string(documentContentJSON)) + } + + response := struct { + SlackResponse + CanvasID string `json:"canvas_id"` + }{} + + err := api.postMethod(ctx, "canvases.create", values, &response) + if err != nil { + return "", err + } + + return response.CanvasID, response.Err() +} + +// DeleteCanvas deletes an existing canvas. +// For more details, see DeleteCanvasContext documentation. +func (api *Client) DeleteCanvas(canvasID string) error { + return api.DeleteCanvasContext(context.Background(), canvasID) +} + +// DeleteCanvasContext deletes an existing canvas with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.delete +func (api *Client) DeleteCanvasContext(ctx context.Context, canvasID string) error { + values := url.Values{ + "token": {api.token}, + "canvas_id": {canvasID}, + } + + response := struct { + SlackResponse + }{} + + err := api.postMethod(ctx, "canvases.delete", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// EditCanvas edits an existing canvas. +// For more details, see EditCanvasContext documentation. +func (api *Client) EditCanvas(params EditCanvasParams) error { + return api.EditCanvasContext(context.Background(), params) +} + +// EditCanvasContext edits an existing canvas with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.edit +func (api *Client) EditCanvasContext(ctx context.Context, params EditCanvasParams) error { + values := url.Values{ + "token": {api.token}, + "canvas_id": {params.CanvasID}, + } + + changesJSON, err := json.Marshal(params.Changes) + if err != nil { + return err + } + values.Add("changes", string(changesJSON)) + + response := struct { + SlackResponse + }{} + + err = api.postMethod(ctx, "canvases.edit", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// SetCanvasAccess sets the access level to a canvas for specified entities. +// For more details, see SetCanvasAccessContext documentation. +func (api *Client) SetCanvasAccess(params SetCanvasAccessParams) error { + return api.SetCanvasAccessContext(context.Background(), params) +} + +// SetCanvasAccessContext sets the access level to a canvas for specified entities with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.access.set +func (api *Client) SetCanvasAccessContext(ctx context.Context, params SetCanvasAccessParams) error { + values := url.Values{ + "token": {api.token}, + "canvas_id": {params.CanvasID}, + "access_level": {params.AccessLevel}, + } + if len(params.ChannelIDs) > 0 { + channelIDsJSON, err := json.Marshal(params.ChannelIDs) + if err != nil { + return err + } + values.Add("channel_ids", string(channelIDsJSON)) + } + if len(params.UserIDs) > 0 { + userIDsJSON, err := json.Marshal(params.UserIDs) + if err != nil { + return err + } + values.Add("user_ids", string(userIDsJSON)) + } + + response := struct { + SlackResponse + }{} + + err := api.postMethod(ctx, "canvases.access.set", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// DeleteCanvasAccess removes access to a canvas for specified entities. +// For more details, see DeleteCanvasAccessContext documentation. +func (api *Client) DeleteCanvasAccess(params DeleteCanvasAccessParams) error { + return api.DeleteCanvasAccessContext(context.Background(), params) +} + +// DeleteCanvasAccessContext removes access to a canvas for specified entities with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.access.delete +func (api *Client) DeleteCanvasAccessContext(ctx context.Context, params DeleteCanvasAccessParams) error { + values := url.Values{ + "token": {api.token}, + "canvas_id": {params.CanvasID}, + } + if len(params.ChannelIDs) > 0 { + channelIDsJSON, err := json.Marshal(params.ChannelIDs) + if err != nil { + return err + } + values.Add("channel_ids", string(channelIDsJSON)) + } + if len(params.UserIDs) > 0 { + userIDsJSON, err := json.Marshal(params.UserIDs) + if err != nil { + return err + } + values.Add("user_ids", string(userIDsJSON)) + } + + response := struct { + SlackResponse + }{} + + err := api.postMethod(ctx, "canvases.access.delete", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// LookupCanvasSections finds sections matching the provided criteria. +// For more details, see LookupCanvasSectionsContext documentation. +func (api *Client) LookupCanvasSections(params LookupCanvasSectionsParams) ([]CanvasSection, error) { + return api.LookupCanvasSectionsContext(context.Background(), params) +} + +// LookupCanvasSectionsContext finds sections matching the provided criteria with a custom context. +// Slack API docs: https://api.slack.com/methods/canvases.sections.lookup +func (api *Client) LookupCanvasSectionsContext(ctx context.Context, params LookupCanvasSectionsParams) ([]CanvasSection, error) { + values := url.Values{ + "token": {api.token}, + "canvas_id": {params.CanvasID}, + } + + criteriaJSON, err := json.Marshal(params.Criteria) + if err != nil { + return nil, err + } + values.Add("criteria", string(criteriaJSON)) + + response := LookupCanvasSectionsResponse{} + + err = api.postMethod(ctx, "canvases.sections.lookup", values, &response) + if err != nil { + return nil, err + } + + return response.Sections, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/channels.go b/vendor/github.com/slack-go/slack/channels.go new file mode 100644 index 000000000..88d567bff --- /dev/null +++ b/vendor/github.com/slack-go/slack/channels.go @@ -0,0 +1,37 @@ +package slack + +import ( + "context" + "net/url" +) + +type channelResponseFull struct { + Channel Channel `json:"channel"` + Channels []Channel `json:"channels"` + Purpose string `json:"purpose"` + Topic string `json:"topic"` + NotInChannel bool `json:"not_in_channel"` + History + SlackResponse + Metadata ResponseMetadata `json:"response_metadata"` +} + +// Channel contains information about the channel +type Channel struct { + GroupConversation + IsChannel bool `json:"is_channel"` + IsGeneral bool `json:"is_general"` + IsMember bool `json:"is_member"` + Locale string `json:"locale"` + Properties *Properties `json:"properties"` +} + +func (api *Client) channelRequest(ctx context.Context, path string, values url.Values) (*channelResponseFull, error) { + response := &channelResponseFull{} + err := postForm(ctx, api.httpclient, api.endpoint+path, values, response, api) + if err != nil { + return nil, err + } + + return response, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/chat.go b/vendor/github.com/slack-go/slack/chat.go new file mode 100644 index 000000000..85c4848ba --- /dev/null +++ b/vendor/github.com/slack-go/slack/chat.go @@ -0,0 +1,926 @@ +package slack + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "regexp" + "strconv" + + "github.com/slack-go/slack/slackutilsx" +) + +const ( + DEFAULT_MESSAGE_USERNAME = "" + DEFAULT_MESSAGE_REPLY_BROADCAST = false + DEFAULT_MESSAGE_ASUSER = false + DEFAULT_MESSAGE_PARSE = "" + DEFAULT_MESSAGE_THREAD_TIMESTAMP = "" + DEFAULT_MESSAGE_LINK_NAMES = 0 + DEFAULT_MESSAGE_UNFURL_LINKS = false + DEFAULT_MESSAGE_UNFURL_MEDIA = true + DEFAULT_MESSAGE_ICON_URL = "" + DEFAULT_MESSAGE_ICON_EMOJI = "" + DEFAULT_MESSAGE_MARKDOWN = true + DEFAULT_MESSAGE_ESCAPE_TEXT = true +) + +type chatResponseFull struct { + Channel string `json:"channel"` + Timestamp string `json:"ts"` // Regular message timestamp + MessageTimeStamp string `json:"message_ts"` // Ephemeral message timestamp + ScheduledMessageID string `json:"scheduled_message_id,omitempty"` // Scheduled message id + Text string `json:"text"` + SlackResponse +} + +// getMessageTimestamp will inspect the `chatResponseFull` to return a timestamp value +// in `chat.postMessage` its under `ts` +// in `chat.postEphemeral` its under `message_ts` +func (c chatResponseFull) getMessageTimestamp() string { + if len(c.Timestamp) > 0 { + return c.Timestamp + } + return c.MessageTimeStamp +} + +// PostMessageParameters contains all the parameters necessary (including the optional ones) for a PostMessage() request +type PostMessageParameters struct { + Username string `json:"username"` + AsUser bool `json:"as_user"` + Parse string `json:"parse"` + ThreadTimestamp string `json:"thread_ts"` + ReplyBroadcast bool `json:"reply_broadcast"` + LinkNames int `json:"link_names"` + UnfurlLinks bool `json:"unfurl_links"` + UnfurlMedia bool `json:"unfurl_media"` + IconURL string `json:"icon_url"` + IconEmoji string `json:"icon_emoji"` + Markdown bool `json:"mrkdwn,omitempty"` + EscapeText bool `json:"escape_text"` + + // chat.postEphemeral support + Channel string `json:"channel"` + User string `json:"user"` + + // chat metadata support + MetaData SlackMetadata `json:"metadata"` + + // file_ids support + FileIDs []string `json:"file_ids,omitempty"` +} + +// NewPostMessageParameters provides an instance of PostMessageParameters with all the sane default values set +func NewPostMessageParameters() PostMessageParameters { + return PostMessageParameters{ + Username: DEFAULT_MESSAGE_USERNAME, + User: DEFAULT_MESSAGE_USERNAME, + AsUser: DEFAULT_MESSAGE_ASUSER, + Parse: DEFAULT_MESSAGE_PARSE, + ThreadTimestamp: DEFAULT_MESSAGE_THREAD_TIMESTAMP, + LinkNames: DEFAULT_MESSAGE_LINK_NAMES, + UnfurlLinks: DEFAULT_MESSAGE_UNFURL_LINKS, + UnfurlMedia: DEFAULT_MESSAGE_UNFURL_MEDIA, + IconURL: DEFAULT_MESSAGE_ICON_URL, + IconEmoji: DEFAULT_MESSAGE_ICON_EMOJI, + Markdown: DEFAULT_MESSAGE_MARKDOWN, + EscapeText: DEFAULT_MESSAGE_ESCAPE_TEXT, + } +} + +// DeleteMessage deletes a message in a channel. +// For more details, see DeleteMessageContext documentation. +func (api *Client) DeleteMessage(channel, messageTimestamp string) (string, string, error) { + return api.DeleteMessageContext(context.Background(), channel, messageTimestamp) +} + +// DeleteMessageContext deletes a message in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.delete +func (api *Client) DeleteMessageContext(ctx context.Context, channel, messageTimestamp string) (string, string, error) { + respChannel, respTimestamp, _, err := api.SendMessageContext( + ctx, + channel, + MsgOptionDelete(messageTimestamp), + ) + return respChannel, respTimestamp, err +} + +// ScheduleMessage sends a message to a channel. +// Message is escaped by default according to https://api.slack.com/docs/formatting +// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message. +// For more details, see ScheduleMessageContext documentation. +func (api *Client) ScheduleMessage(channelID, postAt string, options ...MsgOption) (string, string, error) { + return api.ScheduleMessageContext(context.Background(), channelID, postAt, options...) +} + +// ScheduleMessageContext sends a message to a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.scheduleMessage +func (api *Client) ScheduleMessageContext(ctx context.Context, channelID, postAt string, options ...MsgOption) (string, string, error) { + respChannel, scheduledMessageId, _, err := api.SendMessageContext( + ctx, + channelID, + MsgOptionSchedule(postAt), + MsgOptionCompose(options...), + ) + return respChannel, scheduledMessageId, err +} + +// PostMessage sends a message to a channel. +// Message is escaped by default according to https://api.slack.com/docs/formatting +// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message. +// For more details, see PostMessageContext documentation. +func (api *Client) PostMessage(channelID string, options ...MsgOption) (string, string, error) { + return api.PostMessageContext(context.Background(), channelID, options...) +} + +// PostMessageContext sends a message to a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.postMessage +func (api *Client) PostMessageContext(ctx context.Context, channelID string, options ...MsgOption) (string, string, error) { + respChannel, respTimestamp, _, err := api.SendMessageContext( + ctx, + channelID, + MsgOptionPost(), + MsgOptionCompose(options...), + ) + return respChannel, respTimestamp, err +} + +// PostEphemeral sends an ephemeral message to a user in a channel. +// Message is escaped by default according to https://api.slack.com/docs/formatting +// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message. +// For more details, see PostEphemeralContext documentation. +func (api *Client) PostEphemeral(channelID, userID string, options ...MsgOption) (string, error) { + return api.PostEphemeralContext(context.Background(), channelID, userID, options...) +} + +// PostEphemeralContext sends an ephemeral message to a user in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.postEphemeral +func (api *Client) PostEphemeralContext(ctx context.Context, channelID, userID string, options ...MsgOption) (timestamp string, err error) { + _, timestamp, _, err = api.SendMessageContext( + ctx, + channelID, + MsgOptionPostEphemeral(userID), + MsgOptionCompose(options...), + ) + return timestamp, err +} + +// UpdateMessage updates a message in a channel. +// For more details, see UpdateMessageContext documentation. +func (api *Client) UpdateMessage(channelID, timestamp string, options ...MsgOption) (string, string, string, error) { + return api.UpdateMessageContext(context.Background(), channelID, timestamp, options...) +} + +// UpdateMessageContext updates a message in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.update +func (api *Client) UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...MsgOption) (string, string, string, error) { + return api.SendMessageContext( + ctx, + channelID, + MsgOptionUpdate(timestamp), + MsgOptionCompose(options...), + ) +} + +// UnfurlMessage unfurls a message in a channel. +// For more details, see UnfurlMessageContext documentation. +func (api *Client) UnfurlMessage(channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) { + return api.UnfurlMessageContext(context.Background(), channelID, timestamp, unfurls, options...) +} + +// UnfurlMessageContext unfurls a message in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.unfurl +func (api *Client) UnfurlMessageContext(ctx context.Context, channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) { + return api.SendMessageContext(ctx, channelID, MsgOptionUnfurl(timestamp, unfurls), MsgOptionCompose(options...)) +} + +// UnfurlMessageWithAuthURL sends an unfurl request containing an authentication URL. +// For more details, see UnfurlMessageWithAuthURLContext documentation. +func (api *Client) UnfurlMessageWithAuthURL(channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) { + return api.UnfurlMessageWithAuthURLContext(context.Background(), channelID, timestamp, userAuthURL, options...) +} + +// UnfurlMessageWithAuthURLContext sends an unfurl request containing an authentication URL with a custom context. +// For more details see: https://api.slack.com/reference/messaging/link-unfurling#authenticated_unfurls +func (api *Client) UnfurlMessageWithAuthURLContext(ctx context.Context, channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) { + return api.SendMessageContext(ctx, channelID, MsgOptionUnfurlAuthURL(timestamp, userAuthURL), MsgOptionCompose(options...)) +} + +// SendMessage more flexible method for configuring messages. +// For more details, see SendMessageContext documentation. +func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error) { + return api.SendMessageContext(context.Background(), channel, options...) +} + +// SendMessageContext more flexible method for configuring messages with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.postMessage +func (api *Client) SendMessageContext(ctx context.Context, channelID string, options ...MsgOption) (_channel string, _timestampOrScheduledMessageId string, _text string, err error) { + var ( + req *http.Request + parser func(*chatResponseFull) responseParser + response chatResponseFull + ) + + if req, parser, err = buildSender(api.endpoint, options...).BuildRequestContext(ctx, api.token, channelID); err != nil { + return "", "", "", err + } + + if api.Debug() { + reqBody, err := io.ReadAll(req.Body) + if err != nil { + return "", "", "", err + } + req.Body = io.NopCloser(bytes.NewBuffer(reqBody)) + api.Debugf("Sending request: %s", redactToken(reqBody)) + } + + if err = doPost(api.httpclient, req, parser(&response), api); err != nil { + return "", "", "", err + } + + if response.ScheduledMessageID != "" { + return response.Channel, response.ScheduledMessageID, response.Text, response.Err() + } else { + return response.Channel, response.getMessageTimestamp(), response.Text, response.Err() + } +} + +func redactToken(b []byte) []byte { + // See https://api.slack.com/authentication/token-types + // and https://api.slack.com/authentication/rotation + re, err := regexp.Compile(`(token=x[a-z.]+)-[0-9A-Za-z-]+`) + if err != nil { + // The regular expression above should never result in errors, + // but just in case, do no harm. + return b + } + // Keep "token=" and the first element of the token, which identifies its type + // (this could be useful for debugging, e.g. when using a wrong token). + return re.ReplaceAll(b, []byte("$1-REDACTED")) +} + +// UnsafeApplyMsgOptions utility function for debugging/testing chat requests. +// NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this function +// will be supported by the library. +func UnsafeApplyMsgOptions(token, channel, apiurl string, options ...MsgOption) (string, url.Values, error) { + config, err := applyMsgOptions(token, channel, apiurl, options...) + return config.endpoint, config.values, err +} + +func applyMsgOptions(token, channel, apiurl string, options ...MsgOption) (sendConfig, error) { + config := sendConfig{ + apiurl: apiurl, + endpoint: apiurl + string(chatPostMessage), + values: url.Values{ + "token": {token}, + "channel": {channel}, + }, + } + + for _, opt := range options { + if err := opt(&config); err != nil { + return config, err + } + } + + return config, nil +} + +func buildSender(apiurl string, options ...MsgOption) sendConfig { + return sendConfig{ + apiurl: apiurl, + options: options, + } +} + +type sendMode string + +const ( + chatUpdate sendMode = "chat.update" + chatPostMessage sendMode = "chat.postMessage" + chatScheduleMessage sendMode = "chat.scheduleMessage" + chatDelete sendMode = "chat.delete" + chatPostEphemeral sendMode = "chat.postEphemeral" + chatResponse sendMode = "chat.responseURL" + chatMeMessage sendMode = "chat.meMessage" + chatUnfurl sendMode = "chat.unfurl" +) + +type sendConfig struct { + apiurl string + options []MsgOption + mode sendMode + endpoint string + values url.Values + attachments []Attachment + metadata SlackMetadata + blocks Blocks + responseType string + replaceOriginal bool + deleteOriginal bool +} + +func (t sendConfig) BuildRequest(token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) { + return t.BuildRequestContext(context.Background(), token, channelID) +} + +func (t sendConfig) BuildRequestContext(ctx context.Context, token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) { + if t, err = applyMsgOptions(token, channelID, t.apiurl, t.options...); err != nil { + return nil, nil, err + } + + switch t.mode { + case chatResponse: + return responseURLSender{ + endpoint: t.endpoint, + values: t.values, + attachments: t.attachments, + metadata: t.metadata, + blocks: t.blocks, + responseType: t.responseType, + replaceOriginal: t.replaceOriginal, + deleteOriginal: t.deleteOriginal, + }.BuildRequestContext(ctx) + default: + return formSender{endpoint: t.endpoint, values: t.values}.BuildRequestContext(ctx) + } +} + +type formSender struct { + endpoint string + values url.Values +} + +func (t formSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) { + return t.BuildRequestContext(context.Background()) +} + +func (t formSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) { + req, err := formReq(ctx, t.endpoint, t.values) + return req, func(resp *chatResponseFull) responseParser { + return newJSONParser(resp) + }, err +} + +type responseURLSender struct { + endpoint string + values url.Values + attachments []Attachment + metadata SlackMetadata + blocks Blocks + responseType string + replaceOriginal bool + deleteOriginal bool +} + +func (t responseURLSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) { + return t.BuildRequestContext(context.Background()) +} + +func (t responseURLSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) { + req, err := jsonReq(ctx, t.endpoint, Msg{ + Text: t.values.Get("text"), + Timestamp: t.values.Get("ts"), + ThreadTimestamp: t.values.Get("thread_ts"), + Attachments: t.attachments, + Blocks: t.blocks, + Metadata: t.metadata, + ResponseType: t.responseType, + ReplaceOriginal: t.replaceOriginal, + DeleteOriginal: t.deleteOriginal, + }) + return req, func(resp *chatResponseFull) responseParser { + return newContentTypeParser(resp) + }, err +} + +// MsgOption option provided when sending a message. +type MsgOption func(*sendConfig) error + +// MsgOptionSchedule schedules a messages. +func MsgOptionSchedule(postAt string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatScheduleMessage) + config.values.Add("post_at", postAt) + return nil + } +} + +// MsgOptionPost posts a messages, this is the default. +func MsgOptionPost() MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatPostMessage) + config.values.Del("ts") + return nil + } +} + +// MsgOptionPostEphemeral - posts an ephemeral message to the provided user. +func MsgOptionPostEphemeral(userID string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatPostEphemeral) + MsgOptionUser(userID)(config) + config.values.Del("ts") + + return nil + } +} + +// MsgOptionMeMessage posts a "me message" type from the calling user +func MsgOptionMeMessage() MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatMeMessage) + return nil + } +} + +// MsgOptionUpdate updates a message based on the timestamp. +func MsgOptionUpdate(timestamp string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatUpdate) + config.values.Add("ts", timestamp) + return nil + } +} + +// MsgOptionDelete deletes a message based on the timestamp. +func MsgOptionDelete(timestamp string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatDelete) + config.values.Add("ts", timestamp) + return nil + } +} + +// MsgOptionUnfurl unfurls a message based on the timestamp. +func MsgOptionUnfurl(timestamp string, unfurls map[string]Attachment) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatUnfurl) + config.values.Add("ts", timestamp) + unfurlsStr, err := json.Marshal(unfurls) + if err == nil { + config.values.Add("unfurls", string(unfurlsStr)) + } + return err + } +} + +// MsgOptionUnfurlAuthURL unfurls a message using an auth url based on the timestamp. +func MsgOptionUnfurlAuthURL(timestamp string, userAuthURL string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatUnfurl) + config.values.Add("ts", timestamp) + config.values.Add("user_auth_url", userAuthURL) + return nil + } +} + +// MsgOptionUnfurlAuthRequired requests that the user installs the +// Slack app for unfurling. +func MsgOptionUnfurlAuthRequired(timestamp string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatUnfurl) + config.values.Add("ts", timestamp) + config.values.Add("user_auth_required", "true") + return nil + } +} + +// MsgOptionUnfurlAuthMessage attaches a message inviting the user to +// authenticate. +func MsgOptionUnfurlAuthMessage(timestamp string, msg string) MsgOption { + return func(config *sendConfig) error { + config.endpoint = config.apiurl + string(chatUnfurl) + config.values.Add("ts", timestamp) + config.values.Add("user_auth_message", msg) + return nil + } +} + +// MsgOptionResponseURL supplies a url to use as the endpoint. +func MsgOptionResponseURL(url string, responseType string) MsgOption { + return func(config *sendConfig) error { + config.mode = chatResponse + config.endpoint = url + config.responseType = responseType + config.values.Del("ts") + return nil + } +} + +// MsgOptionReplaceOriginal replaces original message with response url +func MsgOptionReplaceOriginal(responseURL string) MsgOption { + return func(config *sendConfig) error { + config.mode = chatResponse + config.endpoint = responseURL + config.replaceOriginal = true + return nil + } +} + +// MsgOptionDeleteOriginal deletes original message with response url +func MsgOptionDeleteOriginal(responseURL string) MsgOption { + return func(config *sendConfig) error { + config.mode = chatResponse + config.endpoint = responseURL + config.deleteOriginal = true + return nil + } +} + +// MsgOptionAsUser whether or not to send the message as the user. +func MsgOptionAsUser(b bool) MsgOption { + return func(config *sendConfig) error { + if b != DEFAULT_MESSAGE_ASUSER { + config.values.Set("as_user", "true") + } + return nil + } +} + +// MsgOptionUser set the user for the message. +func MsgOptionUser(userID string) MsgOption { + return func(config *sendConfig) error { + config.values.Set("user", userID) + return nil + } +} + +// MsgOptionUsername set the username for the message. +func MsgOptionUsername(username string) MsgOption { + return func(config *sendConfig) error { + config.values.Set("username", username) + return nil + } +} + +// MsgOptionText provide the text for the message, optionally escape the provided +// text. +func MsgOptionText(text string, escape bool) MsgOption { + return func(config *sendConfig) error { + if escape { + text = slackutilsx.EscapeMessage(text) + } + config.values.Add("text", text) + return nil + } +} + +// MsgOptionAttachments provide attachments for the message. +func MsgOptionAttachments(attachments ...Attachment) MsgOption { + return func(config *sendConfig) error { + if attachments == nil { + return nil + } + + config.attachments = attachments + + // FIXME: We are setting the attachments on the message twice: above for + // the json version, and below for the html version. The marshalled bytes + // we put into config.values below don't work directly in the Msg version. + + attachmentBytes, err := json.Marshal(attachments) + if err == nil { + config.values.Set("attachments", string(attachmentBytes)) + } + + return err + } +} + +// MsgOptionBlocks sets blocks for the message +func MsgOptionBlocks(blocks ...Block) MsgOption { + return func(config *sendConfig) error { + if blocks == nil { + return nil + } + + config.blocks.BlockSet = append(config.blocks.BlockSet, blocks...) + + blocks, err := json.Marshal(blocks) + if err == nil { + config.values.Set("blocks", string(blocks)) + } + return err + } +} + +// MsgOptionEnableLinkUnfurl enables link unfurling +func MsgOptionEnableLinkUnfurl() MsgOption { + return func(config *sendConfig) error { + config.values.Set("unfurl_links", "true") + return nil + } +} + +// MsgOptionDisableLinkUnfurl disables link unfurling +func MsgOptionDisableLinkUnfurl() MsgOption { + return func(config *sendConfig) error { + config.values.Set("unfurl_links", "false") + return nil + } +} + +// MsgOptionDisableMediaUnfurl disables media unfurling. +func MsgOptionDisableMediaUnfurl() MsgOption { + return func(config *sendConfig) error { + config.values.Set("unfurl_media", "false") + return nil + } +} + +// MsgOptionDisableMarkdown disables markdown. +func MsgOptionDisableMarkdown() MsgOption { + return func(config *sendConfig) error { + config.values.Set("mrkdwn", "false") + return nil + } +} + +// MsgOptionTS sets the thread TS of the message to enable creating or replying to a thread +func MsgOptionTS(ts string) MsgOption { + return func(config *sendConfig) error { + config.values.Set("thread_ts", ts) + return nil + } +} + +// MsgOptionBroadcast sets reply_broadcast to true +func MsgOptionBroadcast() MsgOption { + return func(config *sendConfig) error { + config.values.Set("reply_broadcast", "true") + return nil + } +} + +// MsgOptionCompose combines multiple options into a single option. +func MsgOptionCompose(options ...MsgOption) MsgOption { + return func(config *sendConfig) error { + for _, opt := range options { + if err := opt(config); err != nil { + return err + } + } + return nil + } +} + +// MsgOptionParse set parse option. +func MsgOptionParse(b bool) MsgOption { + return func(config *sendConfig) error { + var v string + if b { + v = "full" + } else { + v = "none" + } + config.values.Set("parse", v) + return nil + } +} + +// MsgOptionIconURL sets an icon URL +func MsgOptionIconURL(iconURL string) MsgOption { + return func(config *sendConfig) error { + config.values.Set("icon_url", iconURL) + return nil + } +} + +// MsgOptionIconEmoji sets an icon emoji +func MsgOptionIconEmoji(iconEmoji string) MsgOption { + return func(config *sendConfig) error { + config.values.Set("icon_emoji", iconEmoji) + return nil + } +} + +// MsgOptionMetadata sets message metadata +func MsgOptionMetadata(metadata SlackMetadata) MsgOption { + return func(config *sendConfig) error { + config.metadata = metadata + meta, err := json.Marshal(metadata) + if err == nil { + config.values.Set("metadata", string(meta)) + } + return err + } +} + +// MsgOptionLinkNames finds and links user groups. Does not support linking individual users +func MsgOptionLinkNames(linkName bool) MsgOption { + return func(config *sendConfig) error { + config.values.Set("link_names", strconv.FormatBool(linkName)) + return nil + } +} + +// MsgOptionFileIDs sets file IDs for the message +func MsgOptionFileIDs(fileIDs []string) MsgOption { + return func(config *sendConfig) error { + if len(fileIDs) == 0 { + return nil + } + + fileIDsBytes, err := json.Marshal(fileIDs) + if err != nil { + return err + } + + config.values.Set("file_ids", string(fileIDsBytes)) + return nil + } +} + +// UnsafeMsgOptionEndpoint deliver the message to the specified endpoint. +// NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this Option +// will be supported by the library, it is subject to change without notice that +// may result in compilation errors or runtime behaviour changes. +func UnsafeMsgOptionEndpoint(endpoint string, update func(url.Values)) MsgOption { + return func(config *sendConfig) error { + config.endpoint = endpoint + update(config.values) + return nil + } +} + +// MsgOptionPostMessageParameters maintain backwards compatibility. +func MsgOptionPostMessageParameters(params PostMessageParameters) MsgOption { + return func(config *sendConfig) error { + if params.Username != DEFAULT_MESSAGE_USERNAME { + config.values.Set("username", params.Username) + } + + // chat.postEphemeral support + if params.User != DEFAULT_MESSAGE_USERNAME { + config.values.Set("user", params.User) + } + + // never generates an error. + MsgOptionAsUser(params.AsUser)(config) + + if params.Parse != DEFAULT_MESSAGE_PARSE { + config.values.Set("parse", params.Parse) + } + if params.LinkNames != DEFAULT_MESSAGE_LINK_NAMES { + config.values.Set("link_names", "1") + } + + if params.UnfurlLinks != DEFAULT_MESSAGE_UNFURL_LINKS { + config.values.Set("unfurl_links", "true") + } + + // I want to send a message with explicit `as_user` `true` and `unfurl_links` `false` in request. + // Because setting `as_user` to `true` will change the default value for `unfurl_links` to `true` on Slack API side. + if params.AsUser != DEFAULT_MESSAGE_ASUSER && params.UnfurlLinks == DEFAULT_MESSAGE_UNFURL_LINKS { + config.values.Set("unfurl_links", "false") + } + if params.UnfurlMedia != DEFAULT_MESSAGE_UNFURL_MEDIA { + config.values.Set("unfurl_media", "false") + } + if params.IconURL != DEFAULT_MESSAGE_ICON_URL { + config.values.Set("icon_url", params.IconURL) + } + if params.IconEmoji != DEFAULT_MESSAGE_ICON_EMOJI { + config.values.Set("icon_emoji", params.IconEmoji) + } + if params.Markdown != DEFAULT_MESSAGE_MARKDOWN { + config.values.Set("mrkdwn", "false") + } + + if params.ThreadTimestamp != DEFAULT_MESSAGE_THREAD_TIMESTAMP { + config.values.Set("thread_ts", params.ThreadTimestamp) + } + if params.ReplyBroadcast != DEFAULT_MESSAGE_REPLY_BROADCAST { + config.values.Set("reply_broadcast", "true") + } + + if len(params.FileIDs) > 0 { + return MsgOptionFileIDs(params.FileIDs)(config) + } + + return nil + } +} + +// PermalinkParameters are the parameters required to get a permalink to a message. +type PermalinkParameters struct { + Channel string + Ts string +} + +// GetPermalink returns the permalink for a message. It takes PermalinkParameters and returns a string containing the +// permalink. It returns an error if unable to retrieve the permalink. +// For more details, see GetPermalinkContext documentation. +func (api *Client) GetPermalink(params *PermalinkParameters) (string, error) { + return api.GetPermalinkContext(context.Background(), params) +} + +// GetPermalinkContext returns the permalink for a message using a custom context. +// Slack API docs: https://api.slack.com/methods/chat.getPermalink +func (api *Client) GetPermalinkContext(ctx context.Context, params *PermalinkParameters) (string, error) { + values := url.Values{ + "channel": {params.Channel}, + "message_ts": {params.Ts}, + } + + response := struct { + Channel string `json:"channel"` + Permalink string `json:"permalink"` + SlackResponse + }{} + err := api.getMethod(ctx, "chat.getPermalink", api.token, values, &response) + if err != nil { + return "", err + } + return response.Permalink, response.Err() +} + +type GetScheduledMessagesParameters struct { + Channel string + TeamID string + Cursor string + Latest string + Limit int + Oldest string +} + +// GetScheduledMessages returns the list of scheduled messages based on params. +// For more details, see GetScheduledMessagesContext documentation. +func (api *Client) GetScheduledMessages(params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) { + return api.GetScheduledMessagesContext(context.Background(), params) +} + +// GetScheduledMessagesContext returns the list of scheduled messages based on params with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.getScheduledMessages.list +func (api *Client) GetScheduledMessagesContext(ctx context.Context, params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) { + values := url.Values{ + "token": {api.token}, + } + if params.Channel != "" { + values.Add("channel", params.Channel) + } + if params.TeamID != "" { + values.Add("team_id", params.TeamID) + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Latest != "" { + values.Add("latest", params.Latest) + } + if params.Oldest != "" { + values.Add("oldest", params.Oldest) + } + response := struct { + Messages []ScheduledMessage `json:"scheduled_messages"` + ResponseMetaData responseMetaData `json:"response_metadata"` + SlackResponse + }{} + + err = api.postMethod(ctx, "chat.scheduledMessages.list", values, &response) + if err != nil { + return nil, "", err + } + + return response.Messages, response.ResponseMetaData.NextCursor, response.Err() +} + +type DeleteScheduledMessageParameters struct { + Channel string + ScheduledMessageID string + AsUser bool +} + +// DeleteScheduledMessage deletes a pending scheduled message. +// For more details, see DeleteScheduledMessageContext documentation. +func (api *Client) DeleteScheduledMessage(params *DeleteScheduledMessageParameters) (bool, error) { + return api.DeleteScheduledMessageContext(context.Background(), params) +} + +// DeleteScheduledMessageContext deletes a pending scheduled message with a custom context. +// Slack API docs: https://api.slack.com/methods/chat.deleteScheduledMessage +func (api *Client) DeleteScheduledMessageContext(ctx context.Context, params *DeleteScheduledMessageParameters) (bool, error) { + values := url.Values{ + "token": {api.token}, + "channel": {params.Channel}, + "scheduled_message_id": {params.ScheduledMessageID}, + "as_user": {strconv.FormatBool(params.AsUser)}, + } + response := struct { + SlackResponse + }{} + + err := api.postMethod(ctx, "chat.deleteScheduledMessage", values, &response) + if err != nil { + return false, err + } + + return response.Ok, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/comment.go b/vendor/github.com/slack-go/slack/comment.go new file mode 100644 index 000000000..7d1c0d4eb --- /dev/null +++ b/vendor/github.com/slack-go/slack/comment.go @@ -0,0 +1,10 @@ +package slack + +// Comment contains all the information relative to a comment +type Comment struct { + ID string `json:"id,omitempty"` + Created JSONTime `json:"created,omitempty"` + Timestamp JSONTime `json:"timestamp,omitempty"` + User string `json:"user,omitempty"` + Comment string `json:"comment,omitempty"` +} diff --git a/vendor/github.com/slack-go/slack/conversation.go b/vendor/github.com/slack-go/slack/conversation.go new file mode 100644 index 000000000..33eb0ff9b --- /dev/null +++ b/vendor/github.com/slack-go/slack/conversation.go @@ -0,0 +1,914 @@ +package slack + +import ( + "context" + "encoding/json" + "errors" + "net/url" + "strconv" + "strings" +) + +// Conversation is the foundation for IM and BaseGroupConversation +type Conversation struct { + ID string `json:"id"` + Created JSONTime `json:"created"` + IsOpen bool `json:"is_open"` + LastRead string `json:"last_read,omitempty"` + Latest *Message `json:"latest,omitempty"` + UnreadCount int `json:"unread_count,omitempty"` + UnreadCountDisplay int `json:"unread_count_display,omitempty"` + IsGroup bool `json:"is_group"` + IsShared bool `json:"is_shared"` + IsIM bool `json:"is_im"` + IsExtShared bool `json:"is_ext_shared"` + IsOrgShared bool `json:"is_org_shared"` + IsGlobalShared bool `json:"is_global_shared"` + IsPendingExtShared bool `json:"is_pending_ext_shared"` + IsPrivate bool `json:"is_private"` + IsReadOnly bool `json:"is_read_only"` + IsMpIM bool `json:"is_mpim"` + Unlinked int `json:"unlinked"` + NameNormalized string `json:"name_normalized"` + NumMembers int `json:"num_members"` + Priority float64 `json:"priority"` + User string `json:"user"` + ConnectedTeamIDs []string `json:"connected_team_ids,omitempty"` + SharedTeamIDs []string `json:"shared_team_ids,omitempty"` + InternalTeamIDs []string `json:"internal_team_ids,omitempty"` + ContextTeamID string `json:"context_team_id,omitempty"` + ConversationHostID string `json:"conversation_host_id,omitempty"` + PreviousNames []string `json:"previous_names,omitempty"` + PendingShared []string `json:"pending_shared,omitempty"` +} + +// GroupConversation is the foundation for Group and Channel +type GroupConversation struct { + Conversation + Name string `json:"name"` + Creator string `json:"creator"` + IsArchived bool `json:"is_archived"` + Members []string `json:"members"` + Topic Topic `json:"topic"` + Purpose Purpose `json:"purpose"` +} + +// Topic contains information about the topic +type Topic struct { + Value string `json:"value"` + Creator string `json:"creator"` + LastSet JSONTime `json:"last_set"` +} + +// Purpose contains information about the purpose +type Purpose struct { + Value string `json:"value"` + Creator string `json:"creator"` + LastSet JSONTime `json:"last_set"` +} + +// Properties contains the Canvas associated to the channel. +type Properties struct { + Canvas Canvas `json:"canvas"` + PostingRestrictedTo RestrictedTo `json:"posting_restricted_to"` + Tabs []Tab `json:"tabs"` + ThreadsRestrictedTo RestrictedTo `json:"threads_restricted_to"` +} + +type RestrictedTo struct { + Type []string `json:"type"` + User []string `json:"user"` +} + +type Tab struct { + ID string `json:"id"` + Label string `json:"label"` + Type string `json:"type"` +} + +type Canvas struct { + FileId string `json:"file_id"` + IsEmpty bool `json:"is_empty"` + QuipThreadId string `json:"quip_thread_id"` +} + +type GetUsersInConversationParameters struct { + ChannelID string + Cursor string + Limit int +} + +type GetConversationsForUserParameters struct { + UserID string + Cursor string + Types []string + Limit int + ExcludeArchived bool + TeamID string +} + +type responseMetaData struct { + NextCursor string `json:"next_cursor"` +} + +// GetUsersInConversation returns the list of users in a conversation. +// For more details, see GetUsersInConversationContext documentation. +func (api *Client) GetUsersInConversation(params *GetUsersInConversationParameters) ([]string, string, error) { + return api.GetUsersInConversationContext(context.Background(), params) +} + +// GetUsersInConversationContext returns the list of users in a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.members +func (api *Client) GetUsersInConversationContext(ctx context.Context, params *GetUsersInConversationParameters) ([]string, string, error) { + values := url.Values{ + "token": {api.token}, + "channel": {params.ChannelID}, + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + response := struct { + Members []string `json:"members"` + ResponseMetaData responseMetaData `json:"response_metadata"` + SlackResponse + }{} + + err := api.postMethod(ctx, "conversations.members", values, &response) + if err != nil { + return nil, "", err + } + + if err := response.Err(); err != nil { + return nil, "", err + } + + return response.Members, response.ResponseMetaData.NextCursor, nil +} + +// GetConversationsForUser returns the list conversations for a given user. +// For more details, see GetConversationsForUserContext documentation. +func (api *Client) GetConversationsForUser(params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) { + return api.GetConversationsForUserContext(context.Background(), params) +} + +// GetConversationsForUserContext returns the list conversations for a given user with a custom context +// Slack API docs: https://api.slack.com/methods/users.conversations +func (api *Client) GetConversationsForUserContext(ctx context.Context, params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) { + values := url.Values{ + "token": {api.token}, + } + if params.UserID != "" { + values.Add("user", params.UserID) + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Types != nil { + values.Add("types", strings.Join(params.Types, ",")) + } + if params.ExcludeArchived { + values.Add("exclude_archived", "true") + } + if params.TeamID != "" { + values.Add("team_id", params.TeamID) + } + + response := struct { + Channels []Channel `json:"channels"` + ResponseMetaData responseMetaData `json:"response_metadata"` + SlackResponse + }{} + err = api.postMethod(ctx, "users.conversations", values, &response) + if err != nil { + return nil, "", err + } + + return response.Channels, response.ResponseMetaData.NextCursor, response.Err() +} + +// ArchiveConversation archives a conversation. +// For more details, see ArchiveConversationContext documentation. +func (api *Client) ArchiveConversation(channelID string) error { + return api.ArchiveConversationContext(context.Background(), channelID) +} + +// ArchiveConversationContext archives a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.archive +func (api *Client) ArchiveConversationContext(ctx context.Context, channelID string) error { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + } + + response := SlackResponse{} + err := api.postMethod(ctx, "conversations.archive", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// UnArchiveConversation reverses conversation archival. +// For more details, see UnArchiveConversationContext documentation. +func (api *Client) UnArchiveConversation(channelID string) error { + return api.UnArchiveConversationContext(context.Background(), channelID) +} + +// UnArchiveConversationContext reverses conversation archival with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.unarchive +func (api *Client) UnArchiveConversationContext(ctx context.Context, channelID string) error { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + } + response := SlackResponse{} + err := api.postMethod(ctx, "conversations.unarchive", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// SetTopicOfConversation sets the topic for a conversation. +// For more details, see SetTopicOfConversationContext documentation. +func (api *Client) SetTopicOfConversation(channelID, topic string) (*Channel, error) { + return api.SetTopicOfConversationContext(context.Background(), channelID, topic) +} + +// SetTopicOfConversationContext sets the topic for a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.setTopic +func (api *Client) SetTopicOfConversationContext(ctx context.Context, channelID, topic string) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "topic": {topic}, + } + response := struct { + SlackResponse + Channel *Channel `json:"channel"` + }{} + err := api.postMethod(ctx, "conversations.setTopic", values, &response) + if err != nil { + return nil, err + } + + return response.Channel, response.Err() +} + +// SetPurposeOfConversation sets the purpose for a conversation. +// For more details, see SetPurposeOfConversationContext documentation. +func (api *Client) SetPurposeOfConversation(channelID, purpose string) (*Channel, error) { + return api.SetPurposeOfConversationContext(context.Background(), channelID, purpose) +} + +// SetPurposeOfConversationContext sets the purpose for a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.setPurpose +func (api *Client) SetPurposeOfConversationContext(ctx context.Context, channelID, purpose string) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "purpose": {purpose}, + } + response := struct { + SlackResponse + Channel *Channel `json:"channel"` + }{} + + err := api.postMethod(ctx, "conversations.setPurpose", values, &response) + if err != nil { + return nil, err + } + + return response.Channel, response.Err() +} + +// RenameConversation renames a conversation. +// For more details, see RenameConversationContext documentation. +func (api *Client) RenameConversation(channelID, channelName string) (*Channel, error) { + return api.RenameConversationContext(context.Background(), channelID, channelName) +} + +// RenameConversationContext renames a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.rename +func (api *Client) RenameConversationContext(ctx context.Context, channelID, channelName string) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "name": {channelName}, + } + response := struct { + SlackResponse + Channel *Channel `json:"channel"` + }{} + + err := api.postMethod(ctx, "conversations.rename", values, &response) + if err != nil { + return nil, err + } + + return response.Channel, response.Err() +} + +// InviteUsersToConversation invites users to a channel. +// For more details, see InviteUsersToConversation documentation. +func (api *Client) InviteUsersToConversation(channelID string, users ...string) (*Channel, error) { + return api.InviteUsersToConversationContext(context.Background(), channelID, users...) +} + +// InviteUsersToConversationContext invites users to a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.invite +func (api *Client) InviteUsersToConversationContext(ctx context.Context, channelID string, users ...string) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "users": {strings.Join(users, ",")}, + } + response := struct { + SlackResponse + Channel *Channel `json:"channel"` + }{} + + err := api.postMethod(ctx, "conversations.invite", values, &response) + if err != nil { + return nil, err + } + + return response.Channel, response.Err() +} + +// The following functions are for inviting users to a channel but setting the `force` +// parameter to true. We have added this so that we don't break the existing API. +// +// IMPORTANT: If we ever get here for _another_ parameter, we should consider refactoring +// this to be more flexible. +// +// ForceInviteUsersToConversation invites users to a channel but sets the `force` +// parameter to true. +// +// For more details, see ForceInviteUsersToConversationContext documentation. +func (api *Client) ForceInviteUsersToConversation(channelID string, users ...string) (*Channel, error) { + return api.ForceInviteUsersToConversationContext(context.Background(), channelID, users...) +} + +// ForceInviteUsersToConversationContext invites users to a channel with a custom context +// while setting the `force` argument to true. +// +// Slack API docs: https://api.slack.com/methods/conversations.invite +func (api *Client) ForceInviteUsersToConversationContext(ctx context.Context, channelID string, users ...string) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "users": {strings.Join(users, ",")}, + "force": {"true"}, + } + response := struct { + SlackResponse + Channel *Channel `json:"channel"` + }{} + + err := api.postMethod(ctx, "conversations.invite", values, &response) + if err != nil { + return nil, err + } + + return response.Channel, response.Err() +} + +// InviteSharedEmailsToConversation invites users to a shared channels by email. +// For more details, see InviteSharedToConversationContext documentation. +func (api *Client) InviteSharedEmailsToConversation(channelID string, emails ...string) (string, bool, error) { + return api.InviteSharedToConversationContext(context.Background(), InviteSharedToConversationParams{ + ChannelID: channelID, + Emails: emails, + }) +} + +// InviteSharedEmailsToConversationContext invites users to a shared channels by email using context. +// For more details, see InviteSharedToConversationContext documentation. +func (api *Client) InviteSharedEmailsToConversationContext(ctx context.Context, channelID string, emails ...string) (string, bool, error) { + return api.InviteSharedToConversationContext(ctx, InviteSharedToConversationParams{ + ChannelID: channelID, + Emails: emails, + }) +} + +// InviteSharedUserIDsToConversation invites users to a shared channels by user id. +// For more details, see InviteSharedToConversationContext documentation. +func (api *Client) InviteSharedUserIDsToConversation(channelID string, userIDs ...string) (string, bool, error) { + return api.InviteSharedToConversationContext(context.Background(), InviteSharedToConversationParams{ + ChannelID: channelID, + UserIDs: userIDs, + }) +} + +// InviteSharedUserIDsToConversationContext invites users to a shared channels by user id with context. +// For more details, see InviteSharedToConversationContext documentation. +func (api *Client) InviteSharedUserIDsToConversationContext(ctx context.Context, channelID string, userIDs ...string) (string, bool, error) { + return api.InviteSharedToConversationContext(ctx, InviteSharedToConversationParams{ + ChannelID: channelID, + UserIDs: userIDs, + }) +} + +// InviteSharedToConversationParams defines the parameters for the InviteSharedToConversation and InviteSharedToConversationContext functions. +type InviteSharedToConversationParams struct { + ChannelID string + Emails []string + UserIDs []string + ExternalLimited *bool +} + +// InviteSharedToConversation invites emails or userIDs to a channel. +// For more details, see InviteSharedToConversationContext documentation. +func (api *Client) InviteSharedToConversation(params InviteSharedToConversationParams) (string, bool, error) { + return api.InviteSharedToConversationContext(context.Background(), params) +} + +// InviteSharedToConversationContext invites emails or userIDs to a channel with a custom context. +// This is a helper function for InviteSharedEmailsToConversation and InviteSharedUserIDsToConversation. +// It accepts either emails or userIDs, but not both. +// Slack API docs: https://api.slack.com/methods/conversations.inviteShared +func (api *Client) InviteSharedToConversationContext(ctx context.Context, params InviteSharedToConversationParams) (string, bool, error) { + values := url.Values{ + "token": {api.token}, + "channel": {params.ChannelID}, + } + if len(params.Emails) > 0 { + values.Add("emails", strings.Join(params.Emails, ",")) + } else if len(params.UserIDs) > 0 { + values.Add("user_ids", strings.Join(params.UserIDs, ",")) + } + if params.ExternalLimited != nil { + values.Add("external_limited", strconv.FormatBool(*params.ExternalLimited)) + } + response := struct { + SlackResponse + InviteID string `json:"invite_id"` + IsLegacySharedChannel bool `json:"is_legacy_shared_channel"` + }{} + + err := api.postMethod(ctx, "conversations.inviteShared", values, &response) + if err != nil { + return "", false, err + } + + return response.InviteID, response.IsLegacySharedChannel, response.Err() +} + +// KickUserFromConversation removes a user from a conversation. +// For more details, see KickUserFromConversationContext documentation. +func (api *Client) KickUserFromConversation(channelID string, user string) error { + return api.KickUserFromConversationContext(context.Background(), channelID, user) +} + +// KickUserFromConversationContext removes a user from a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.kick +func (api *Client) KickUserFromConversationContext(ctx context.Context, channelID string, user string) error { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + "user": {user}, + } + + response := SlackResponse{} + err := api.postMethod(ctx, "conversations.kick", values, &response) + if err != nil { + return err + } + + return response.Err() +} + +// CloseConversation closes a direct message or multi-person direct message. +// For more details, see CloseConversationContext documentation. +func (api *Client) CloseConversation(channelID string) (noOp bool, alreadyClosed bool, err error) { + return api.CloseConversationContext(context.Background(), channelID) +} + +// CloseConversationContext closes a direct message or multi-person direct message with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.close +func (api *Client) CloseConversationContext(ctx context.Context, channelID string) (noOp bool, alreadyClosed bool, err error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + } + response := struct { + SlackResponse + NoOp bool `json:"no_op"` + AlreadyClosed bool `json:"already_closed"` + }{} + + err = api.postMethod(ctx, "conversations.close", values, &response) + if err != nil { + return false, false, err + } + + return response.NoOp, response.AlreadyClosed, response.Err() +} + +type CreateConversationParams struct { + ChannelName string + IsPrivate bool + TeamID string +} + +// CreateConversation initiates a public or private channel-based conversation. +// For more details, see CreateConversationContext documentation. +func (api *Client) CreateConversation(params CreateConversationParams) (*Channel, error) { + return api.CreateConversationContext(context.Background(), params) +} + +// CreateConversationContext initiates a public or private channel-based conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.create +func (api *Client) CreateConversationContext(ctx context.Context, params CreateConversationParams) (*Channel, error) { + values := url.Values{ + "token": {api.token}, + "name": {params.ChannelName}, + "is_private": {strconv.FormatBool(params.IsPrivate)}, + } + if params.TeamID != "" { + values.Set("team_id", params.TeamID) + } + response, err := api.channelRequest(ctx, "conversations.create", values) + if err != nil { + return nil, err + } + + return &response.Channel, nil +} + +// GetConversationInfoInput Defines the parameters of a GetConversationInfo and GetConversationInfoContext function +type GetConversationInfoInput struct { + ChannelID string + IncludeLocale bool + IncludeNumMembers bool +} + +// GetConversationInfo retrieves information about a conversation. +// For more details, see GetConversationInfoContext documentation. +func (api *Client) GetConversationInfo(input *GetConversationInfoInput) (*Channel, error) { + return api.GetConversationInfoContext(context.Background(), input) +} + +// GetConversationInfoContext retrieves information about a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.info +func (api *Client) GetConversationInfoContext(ctx context.Context, input *GetConversationInfoInput) (*Channel, error) { + if input == nil { + return nil, errors.New("GetConversationInfoInput must not be nil") + } + + if input.ChannelID == "" { + return nil, errors.New("ChannelID must be defined") + } + + values := url.Values{ + "token": {api.token}, + "channel": {input.ChannelID}, + "include_locale": {strconv.FormatBool(input.IncludeLocale)}, + "include_num_members": {strconv.FormatBool(input.IncludeNumMembers)}, + } + response, err := api.channelRequest(ctx, "conversations.info", values) + if err != nil { + return nil, err + } + + return &response.Channel, response.Err() +} + +// LeaveConversation leaves a conversation. +// For more details, see LeaveConversationContext documentation. +func (api *Client) LeaveConversation(channelID string) (bool, error) { + return api.LeaveConversationContext(context.Background(), channelID) +} + +// LeaveConversationContext leaves a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.leave +func (api *Client) LeaveConversationContext(ctx context.Context, channelID string) (bool, error) { + values := url.Values{ + "token": {api.token}, + "channel": {channelID}, + } + + response, err := api.channelRequest(ctx, "conversations.leave", values) + if err != nil { + return false, err + } + + return response.NotInChannel, err +} + +type GetConversationRepliesParameters struct { + ChannelID string + Timestamp string + Cursor string + Inclusive bool + Latest string + Limit int + Oldest string + IncludeAllMetadata bool +} + +// GetConversationReplies retrieves a thread of messages posted to a conversation. +// For more details, see GetConversationRepliesContext documentation. +func (api *Client) GetConversationReplies(params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) { + return api.GetConversationRepliesContext(context.Background(), params) +} + +// GetConversationRepliesContext retrieves a thread of messages posted to a conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.replies +func (api *Client) GetConversationRepliesContext(ctx context.Context, params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) { + values := url.Values{ + "token": {api.token}, + "channel": {params.ChannelID}, + "ts": {params.Timestamp}, + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Latest != "" { + values.Add("latest", params.Latest) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Oldest != "" { + values.Add("oldest", params.Oldest) + } + if params.Inclusive { + values.Add("inclusive", "1") + } else { + values.Add("inclusive", "0") + } + if params.IncludeAllMetadata { + values.Add("include_all_metadata", "1") + } else { + values.Add("include_all_metadata", "0") + } + response := struct { + SlackResponse + HasMore bool `json:"has_more"` + ResponseMetaData struct { + NextCursor string `json:"next_cursor"` + } `json:"response_metadata"` + Messages []Message `json:"messages"` + }{} + + err = api.postMethod(ctx, "conversations.replies", values, &response) + if err != nil { + return nil, false, "", err + } + + return response.Messages, response.HasMore, response.ResponseMetaData.NextCursor, response.Err() +} + +type GetConversationsParameters struct { + Cursor string + ExcludeArchived bool + Limit int + Types []string + TeamID string +} + +// GetConversations returns the list of channels in a Slack team. +// For more details, see GetConversationsContext documentation. +func (api *Client) GetConversations(params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) { + return api.GetConversationsContext(context.Background(), params) +} + +// GetConversationsContext returns the list of channels in a Slack team with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.list +func (api *Client) GetConversationsContext(ctx context.Context, params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) { + values := url.Values{ + "token": {api.token}, + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Types != nil { + values.Add("types", strings.Join(params.Types, ",")) + } + if params.ExcludeArchived { + values.Add("exclude_archived", strconv.FormatBool(params.ExcludeArchived)) + } + if params.TeamID != "" { + values.Add("team_id", params.TeamID) + } + + response := struct { + Channels []Channel `json:"channels"` + ResponseMetaData responseMetaData `json:"response_metadata"` + SlackResponse + }{} + + err = api.postMethod(ctx, "conversations.list", values, &response) + if err != nil { + return nil, "", err + } + + return response.Channels, response.ResponseMetaData.NextCursor, response.Err() +} + +type OpenConversationParameters struct { + ChannelID string + ReturnIM bool + Users []string +} + +// OpenConversation opens or resumes a direct message or multi-person direct message. +// For more details, see OpenConversationContext documentation. +func (api *Client) OpenConversation(params *OpenConversationParameters) (*Channel, bool, bool, error) { + return api.OpenConversationContext(context.Background(), params) +} + +// OpenConversationContext opens or resumes a direct message or multi-person direct message with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.open +func (api *Client) OpenConversationContext(ctx context.Context, params *OpenConversationParameters) (*Channel, bool, bool, error) { + values := url.Values{ + "token": {api.token}, + "return_im": {strconv.FormatBool(params.ReturnIM)}, + } + if params.ChannelID != "" { + values.Add("channel", params.ChannelID) + } + if params.Users != nil { + values.Add("users", strings.Join(params.Users, ",")) + } + response := struct { + Channel *Channel `json:"channel"` + NoOp bool `json:"no_op"` + AlreadyOpen bool `json:"already_open"` + SlackResponse + }{} + + err := api.postMethod(ctx, "conversations.open", values, &response) + if err != nil { + return nil, false, false, err + } + + return response.Channel, response.NoOp, response.AlreadyOpen, response.Err() +} + +// JoinConversation joins an existing conversation. +// For more details, see JoinConversationContext documentation. +func (api *Client) JoinConversation(channelID string) (*Channel, string, []string, error) { + return api.JoinConversationContext(context.Background(), channelID) +} + +// JoinConversationContext joins an existing conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.join +func (api *Client) JoinConversationContext(ctx context.Context, channelID string) (*Channel, string, []string, error) { + values := url.Values{"token": {api.token}, "channel": {channelID}} + response := struct { + Channel *Channel `json:"channel"` + Warning string `json:"warning"` + ResponseMetaData *struct { + Warnings []string `json:"warnings"` + } `json:"response_metadata"` + SlackResponse + }{} + + err := api.postMethod(ctx, "conversations.join", values, &response) + if err != nil { + return nil, "", nil, err + } + if response.Err() != nil { + return nil, "", nil, response.Err() + } + var warnings []string + if response.ResponseMetaData != nil { + warnings = response.ResponseMetaData.Warnings + } + return response.Channel, response.Warning, warnings, nil +} + +type GetConversationHistoryParameters struct { + ChannelID string + Cursor string + Inclusive bool + Latest string + Limit int + Oldest string + IncludeAllMetadata bool +} + +type GetConversationHistoryResponse struct { + SlackResponse + HasMore bool `json:"has_more"` + PinCount int `json:"pin_count"` + Latest string `json:"latest"` + ResponseMetaData struct { + NextCursor string `json:"next_cursor"` + } `json:"response_metadata"` + Messages []Message `json:"messages"` +} + +// GetConversationHistory joins an existing conversation. +// For more details, see GetConversationHistoryContext documentation. +func (api *Client) GetConversationHistory(params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) { + return api.GetConversationHistoryContext(context.Background(), params) +} + +// GetConversationHistoryContext joins an existing conversation with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.history +func (api *Client) GetConversationHistoryContext(ctx context.Context, params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) { + values := url.Values{"token": {api.token}, "channel": {params.ChannelID}} + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + if params.Inclusive { + values.Add("inclusive", "1") + } else { + values.Add("inclusive", "0") + } + if params.Latest != "" { + values.Add("latest", params.Latest) + } + if params.Limit != 0 { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Oldest != "" { + values.Add("oldest", params.Oldest) + } + if params.IncludeAllMetadata { + values.Add("include_all_metadata", "1") + } else { + values.Add("include_all_metadata", "0") + } + + response := GetConversationHistoryResponse{} + + err := api.postMethod(ctx, "conversations.history", values, &response) + if err != nil { + return nil, err + } + + return &response, response.Err() +} + +// MarkConversation sets the read mark of a conversation to a specific point. +// For more details, see MarkConversationContext documentation. +func (api *Client) MarkConversation(channel, ts string) (err error) { + return api.MarkConversationContext(context.Background(), channel, ts) +} + +// MarkConversationContext sets the read mark of a conversation to a specific point with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.mark +func (api *Client) MarkConversationContext(ctx context.Context, channel, ts string) error { + values := url.Values{ + "token": {api.token}, + "channel": {channel}, + "ts": {ts}, + } + + response := &SlackResponse{} + + err := api.postMethod(ctx, "conversations.mark", values, response) + if err != nil { + return err + } + return response.Err() +} + +// CreateChannelCanvas creates a new canvas in a channel. +// For more details, see CreateChannelCanvasContext documentation. +func (api *Client) CreateChannelCanvas(channel string, documentContent DocumentContent) (string, error) { + return api.CreateChannelCanvasContext(context.Background(), channel, documentContent) +} + +// CreateChannelCanvasContext creates a new canvas in a channel with a custom context. +// Slack API docs: https://api.slack.com/methods/conversations.canvases.create +func (api *Client) CreateChannelCanvasContext(ctx context.Context, channel string, documentContent DocumentContent) (string, error) { + values := url.Values{ + "token": {api.token}, + "channel_id": {channel}, + } + if documentContent.Type != "" { + documentContentJSON, err := json.Marshal(documentContent) + if err != nil { + return "", err + } + values.Add("document_content", string(documentContentJSON)) + } + + response := struct { + SlackResponse + CanvasID string `json:"canvas_id"` + }{} + err := api.postMethod(ctx, "conversations.canvases.create", values, &response) + if err != nil { + return "", err + } + + return response.CanvasID, response.Err() +} diff --git a/vendor/github.com/slack-go/slack/dialog.go b/vendor/github.com/slack-go/slack/dialog.go new file mode 100644 index 000000000..f94113f4d --- /dev/null +++ b/vendor/github.com/slack-go/slack/dialog.go @@ -0,0 +1,120 @@ +package slack + +import ( + "context" + "encoding/json" + "strings" +) + +// InputType is the type of the dialog input type +type InputType string + +const ( + // InputTypeText textfield input + InputTypeText InputType = "text" + // InputTypeTextArea textarea input + InputTypeTextArea InputType = "textarea" + // InputTypeSelect select menus input + InputTypeSelect InputType = "select" +) + +// DialogInput for dialogs input type text or menu +type DialogInput struct { + Type InputType `json:"type"` + Label string `json:"label"` + Name string `json:"name"` + Placeholder string `json:"placeholder"` + Optional bool `json:"optional"` + Hint string `json:"hint"` +} + +// DialogTrigger ... +type DialogTrigger struct { + TriggerID string `json:"trigger_id"` //Required. Must respond within 3 seconds. + Dialog Dialog `json:"dialog"` //Required. +} + +// Dialog as in Slack dialogs +// https://api.slack.com/dialogs#option_element_attributes#top-level_dialog_attributes +type Dialog struct { + TriggerID string `json:"trigger_id"` // Required + CallbackID string `json:"callback_id"` // Required + State string `json:"state,omitempty"` // Optional + Title string `json:"title"` + SubmitLabel string `json:"submit_label,omitempty"` + NotifyOnCancel bool `json:"notify_on_cancel"` + Elements []DialogElement `json:"elements"` +} + +// DialogElement abstract type for dialogs. +type DialogElement interface{} + +// DialogCallback DEPRECATED use InteractionCallback +type DialogCallback InteractionCallback + +// DialogSubmissionCallback is sent from Slack when a user submits a form from within a dialog +type DialogSubmissionCallback struct { + // NOTE: State is only used with the dialog_submission type. + // You should use InteractionCallback.BlockActionsState for block_actions type. + State string `json:"-"` + Submission map[string]string `json:"submission"` +} + +// DialogOpenResponse response from `dialog.open` +type DialogOpenResponse struct { + SlackResponse + DialogResponseMetadata DialogResponseMetadata `json:"response_metadata"` +} + +// DialogResponseMetadata lists the error messages +type DialogResponseMetadata struct { + Messages []string `json:"messages"` +} + +// DialogInputValidationError is an error when user inputs incorrect value to form from within a dialog +type DialogInputValidationError struct { + Name string `json:"name"` + Error string `json:"error"` +} + +// DialogInputValidationErrors lists the name of field and that error messages +type DialogInputValidationErrors struct { + Errors []DialogInputValidationError `json:"errors"` +} + +// OpenDialog opens a dialog window where the triggerID originated from. +// EXPERIMENTAL: dialog functionality is currently experimental, api is not considered stable. +func (api *Client) OpenDialog(triggerID string, dialog Dialog) (err error) { + return api.OpenDialogContext(context.Background(), triggerID, dialog) +} + +// OpenDialogContext opens a dialog window where the triggerId originated from with a custom context +// EXPERIMENTAL: dialog functionality is currently experimental, api is not considered stable. +func (api *Client) OpenDialogContext(ctx context.Context, triggerID string, dialog Dialog) (err error) { + if triggerID == "" { + return ErrParametersMissing + } + + req := DialogTrigger{ + TriggerID: triggerID, + Dialog: dialog, + } + + encoded, err := json.Marshal(req) + if err != nil { + return err + } + + response := &DialogOpenResponse{} + endpoint := api.endpoint + "dialog.open" + if err := postJSON(ctx, api.httpclient, endpoint, api.token, encoded, response, api); err != nil { + return err + } + + if len(response.DialogResponseMetadata.Messages) > 0 { + response.Ok = false + response.Error += "\n" + strings.Join(response.DialogResponseMetadata.Messages, "\n") + } + + return response.Err() +} diff --git a/vendor/github.com/slack-go/slack/dialog_select.go b/vendor/github.com/slack-go/slack/dialog_select.go new file mode 100644 index 000000000..3d6be989e --- /dev/null +++ b/vendor/github.com/slack-go/slack/dialog_select.go @@ -0,0 +1,115 @@ +package slack + +// SelectDataSource types of select datasource +type SelectDataSource string + +const ( + // DialogDataSourceStatic menu with static Options/OptionGroups + DialogDataSourceStatic SelectDataSource = "static" + // DialogDataSourceExternal dynamic datasource + DialogDataSourceExternal SelectDataSource = "external" + // DialogDataSourceConversations provides a list of conversations + DialogDataSourceConversations SelectDataSource = "conversations" + // DialogDataSourceChannels provides a list of channels + DialogDataSourceChannels SelectDataSource = "channels" + // DialogDataSourceUsers provides a list of users + DialogDataSourceUsers SelectDataSource = "users" +) + +// DialogInputSelect dialog support for select boxes. +type DialogInputSelect struct { + DialogInput + Value string `json:"value,omitempty"` //Optional. + DataSource SelectDataSource `json:"data_source,omitempty"` //Optional. Allowed values: "users", "channels", "conversations", "external". + SelectedOptions []DialogSelectOption `json:"selected_options,omitempty"` //Optional. May hold at most one element, for use with "external" only. + Options []DialogSelectOption `json:"options,omitempty"` //One of options or option_groups is required. + OptionGroups []DialogOptionGroup `json:"option_groups,omitempty"` //Provide up to 100 options. + MinQueryLength int `json:"min_query_length,omitempty"` //Optional. minimum characters before query is sent. + Hint string `json:"hint,omitempty"` //Optional. Additional hint text. +} + +// DialogSelectOption is an option for the user to select from the menu +type DialogSelectOption struct { + Label string `json:"label"` + Value string `json:"value"` +} + +// DialogOptionGroup is a collection of options for creating a segmented table +type DialogOptionGroup struct { + Label string `json:"label"` + Options []DialogSelectOption `json:"options"` +} + +// NewStaticSelectDialogInput constructor for a `static` datasource menu input +func NewStaticSelectDialogInput(name, label string, options []DialogSelectOption) *DialogInputSelect { + return &DialogInputSelect{ + DialogInput: DialogInput{ + Type: InputTypeSelect, + Name: name, + Label: label, + Optional: true, + }, + DataSource: DialogDataSourceStatic, + Options: options, + } +} + +// NewExternalSelectDialogInput constructor for a `external` datasource menu input +func NewExternalSelectDialogInput(name, label string, options []DialogSelectOption) *DialogInputSelect { + return &DialogInputSelect{ + DialogInput: DialogInput{ + Type: InputTypeSelect, + Name: name, + Label: label, + Optional: true, + }, + DataSource: DialogDataSourceExternal, + Options: options, + } +} + +// NewGroupedSelectDialogInput creates grouped options select input for Dialogs. +func NewGroupedSelectDialogInput(name, label string, options []DialogOptionGroup) *DialogInputSelect { + return &DialogInputSelect{ + DialogInput: DialogInput{ + Type: InputTypeSelect, + Name: name, + Label: label, + }, + DataSource: DialogDataSourceStatic, + OptionGroups: options} +} + +// NewDialogOptionGroup creates a DialogOptionGroup from several select options +func NewDialogOptionGroup(label string, options ...DialogSelectOption) DialogOptionGroup { + return DialogOptionGroup{ + Label: label, + Options: options, + } +} + +// NewConversationsSelect returns a `Conversations` select +func NewConversationsSelect(name, label string) *DialogInputSelect { + return newPresetSelect(name, label, DialogDataSourceConversations) +} + +// NewChannelsSelect returns a `Channels` select +func NewChannelsSelect(name, label string) *DialogInputSelect { + return newPresetSelect(name, label, DialogDataSourceChannels) +} + +// NewUsersSelect returns a `Users` select +func NewUsersSelect(name, label string) *DialogInputSelect { + return newPresetSelect(name, label, DialogDataSourceUsers) +} + +func newPresetSelect(name, label string, dataSourceType SelectDataSource) *DialogInputSelect { + return &DialogInputSelect{ + DialogInput: DialogInput{ + Type: InputTypeSelect, + Label: label, + Name: name, + }, + DataSource: dataSourceType, + } +} diff --git a/vendor/github.com/slack-go/slack/dialog_text.go b/vendor/github.com/slack-go/slack/dialog_text.go new file mode 100644 index 000000000..25fa1b693 --- /dev/null +++ b/vendor/github.com/slack-go/slack/dialog_text.go @@ -0,0 +1,59 @@ +package slack + +// TextInputSubtype Accepts email, number, tel, or url. In some form factors, optimized input is provided for this subtype. +type TextInputSubtype string + +// TextInputOption handle to extra inputs options. +type TextInputOption func(*TextInputElement) + +const ( + // InputSubtypeEmail email keyboard + InputSubtypeEmail TextInputSubtype = "email" + // InputSubtypeNumber numeric keyboard + InputSubtypeNumber TextInputSubtype = "number" + // InputSubtypeTel Phone keyboard + InputSubtypeTel TextInputSubtype = "tel" + // InputSubtypeURL Phone keyboard + InputSubtypeURL TextInputSubtype = "url" +) + +// TextInputElement subtype of DialogInput +// https://api.slack.com/dialogs#option_element_attributes#text_element_attributes +type TextInputElement struct { + DialogInput + MaxLength int `json:"max_length,omitempty"` + MinLength int `json:"min_length,omitempty"` + Hint string `json:"hint,omitempty"` + Subtype TextInputSubtype `json:"subtype"` + Value string `json:"value"` +} + +// NewTextInput constructor for a `text` input +func NewTextInput(name, label, text string, options ...TextInputOption) *TextInputElement { + t := &TextInputElement{ + DialogInput: DialogInput{ + Type: InputTypeText, + Name: name, + Label: label, + }, + Value: text, + } + + for _, opt := range options { + opt(t) + } + + return t +} + +// NewTextAreaInput constructor for a `textarea` input +func NewTextAreaInput(name, label, text string) *TextInputElement { + return &TextInputElement{ + DialogInput: DialogInput{ + Type: InputTypeTextArea, + Name: name, + Label: label, + }, + Value: text, + } +} diff --git a/vendor/github.com/slack-go/slack/dnd.go b/vendor/github.com/slack-go/slack/dnd.go new file mode 100644 index 000000000..81eaf5024 --- /dev/null +++ b/vendor/github.com/slack-go/slack/dnd.go @@ -0,0 +1,160 @@ +package slack + +import ( + "context" + "net/url" + "strconv" + "strings" +) + +type SnoozeDebug struct { + SnoozeEndDate string `json:"snooze_end_date"` +} + +type SnoozeInfo struct { + SnoozeEnabled bool `json:"snooze_enabled,omitempty"` + SnoozeEndTime int `json:"snooze_endtime,omitempty"` + SnoozeRemaining int `json:"snooze_remaining,omitempty"` + SnoozeDebug SnoozeDebug `json:"snooze_debug,omitempty"` +} + +type DNDStatus struct { + Enabled bool `json:"dnd_enabled"` + NextStartTimestamp int `json:"next_dnd_start_ts"` + NextEndTimestamp int `json:"next_dnd_end_ts"` + SnoozeInfo +} + +type dndResponseFull struct { + DNDStatus + SlackResponse +} + +type dndTeamInfoResponse struct { + Users map[string]DNDStatus `json:"users"` + SlackResponse +} + +func (api *Client) dndRequest(ctx context.Context, path string, values url.Values) (*dndResponseFull, error) { + response := &dndResponseFull{} + err := api.postMethod(ctx, path, values, response) + if err != nil { + return nil, err + } + + return response, response.Err() +} + +// EndDND ends the user's scheduled Do Not Disturb session. +// For more information see the EndDNDContext documentation. +func (api *Client) EndDND() error { + return api.EndDNDContext(context.Background()) +} + +// EndDNDContext ends the user's scheduled Do Not Disturb session with a custom context. +// Slack API docs: https://api.slack.com/methods/dnd.endDnd +func (api *Client) EndDNDContext(ctx context.Context) error { + values := url.Values{ + "token": {api.token}, + } + + response := &SlackResponse{} + + if err := api.postMethod(ctx, "dnd.endDnd", values, response); err != nil { + return err + } + + return response.Err() +} + +// EndSnooze ends the current user's snooze mode. +// For more information see the EndSnoozeContext documentation. +func (api *Client) EndSnooze() (*DNDStatus, error) { + return api.EndSnoozeContext(context.Background()) +} + +// EndSnoozeContext ends the current user's snooze mode with a custom context. +// Slack API docs: https://api.slack.com/methods/dnd.endSnooze +func (api *Client) EndSnoozeContext(ctx context.Context) (*DNDStatus, error) { + values := url.Values{ + "token": {api.token}, + } + + response, err := api.dndRequest(ctx, "dnd.endSnooze", values) + if err != nil { + return nil, err + } + return &response.DNDStatus, nil +} + +// GetDNDInfo provides information about a user's current Do Not Disturb settings. +// For more information see the GetDNDInfoContext documentation. +func (api *Client) GetDNDInfo(user *string) (*DNDStatus, error) { + return api.GetDNDInfoContext(context.Background(), user) +} + +// GetDNDInfoContext provides information about a user's current Do Not Disturb settings with a custom context. +// Slack API docs: https://api.slack.com/methods/dnd.info +func (api *Client) GetDNDInfoContext(ctx context.Context, user *string) (*DNDStatus, error) { + values := url.Values{ + "token": {api.token}, + } + if user != nil { + values.Set("user", *user) + } + + response, err := api.dndRequest(ctx, "dnd.info", values) + if err != nil { + return nil, err + } + return &response.DNDStatus, nil +} + +// GetDNDTeamInfo provides information about a user's current Do Not Disturb settings. +// For more information see the GetDNDTeamInfoContext documentation. +func (api *Client) GetDNDTeamInfo(users []string) (map[string]DNDStatus, error) { + return api.GetDNDTeamInfoContext(context.Background(), users) +} + +// GetDNDTeamInfoContext provides information about a user's current Do Not Disturb settings with a custom context. +// Slack API docs: https://api.slack.com/methods/dnd.teamInfo +func (api *Client) GetDNDTeamInfoContext(ctx context.Context, users []string) (map[string]DNDStatus, error) { + values := url.Values{ + "token": {api.token}, + "users": {strings.Join(users, ",")}, + } + response := &dndTeamInfoResponse{} + + if err := api.postMethod(ctx, "dnd.teamInfo", values, response); err != nil { + return nil, err + } + + if response.Err() != nil { + return nil, response.Err() + } + + return response.Users, nil +} + +// SetSnooze adjusts the snooze duration for a user's Do Not Disturb settings. +// For more information see the SetSnoozeContext documentation. +func (api *Client) SetSnooze(minutes int) (*DNDStatus, error) { + return api.SetSnoozeContext(context.Background(), minutes) +} + +// SetSnoozeContext adjusts the snooze duration for a user's Do Not Disturb settings. +// If a snooze session is not already active for the user, invoking this method will +// begin one for the specified duration. +// Slack API docs: https://api.slack.com/methods/dnd.setSnooze +func (api *Client) SetSnoozeContext(ctx context.Context, minutes int) (*DNDStatus, error) { + values := url.Values{ + "token": {api.token}, + "num_minutes": {strconv.Itoa(minutes)}, + } + + response, err := api.dndRequest(ctx, "dnd.setSnooze", values) + if err != nil { + return nil, err + } + return &response.DNDStatus, nil +} diff --git a/vendor/github.com/slack-go/slack/emoji.go b/vendor/github.com/slack-go/slack/emoji.go new file mode 100644 index 000000000..139df0fd2 --- /dev/null +++ b/vendor/github.com/slack-go/slack/emoji.go @@ -0,0 +1,37 @@ +package slack + +import ( + "context" + "net/url" +) + +type emojiResponseFull struct { + Emoji map[string]string `json:"emoji"` + SlackResponse +} + +// GetEmoji retrieves all the emojis. +// For more details see GetEmojiContext documentation. +func (api *Client) GetEmoji() (map[string]string, error) { + return api.GetEmojiContext(context.Background()) +} + +// GetEmojiContext retrieves all the emojis with a custom context. +// Slack API docs: https://api.slack.com/methods/emoji.list +func (api *Client) GetEmojiContext(ctx context.Context) (map[string]string, error) { + values := url.Values{ + "token": {api.token}, + } + response := &emojiResponseFull{} + + err := api.postMethod(ctx, "emoji.list", values, response) + if err != nil { + return nil, err + } + + if response.Err() != nil { + return nil, response.Err() + } + + return response.Emoji, nil +} diff --git a/vendor/github.com/slack-go/slack/errors.go b/vendor/github.com/slack-go/slack/errors.go new file mode 100644 index 000000000..8be22a659 --- /dev/null +++ b/vendor/github.com/slack-go/slack/errors.go @@ -0,0 +1,21 @@ +package slack + +import "github.com/slack-go/slack/internal/errorsx" + +// Errors returned by various methods. +const ( + ErrAlreadyDisconnected = errorsx.String("Invalid call to Disconnect - Slack API is already disconnected") + ErrRTMDisconnected = errorsx.String("disconnect received while trying to connect") + ErrRTMGoodbye = errorsx.String("goodbye detected") + ErrRTMDeadman = errorsx.String("deadman switch triggered") + ErrParametersMissing = errorsx.String("received empty parameters") + ErrBlockIDNotUnique = errorsx.String("Block ID needs to be unique") + ErrInvalidConfiguration = errorsx.String("invalid configuration") + ErrMissingHeaders = errorsx.String("missing headers") + ErrExpiredTimestamp = errorsx.String("timestamp is too old") +) + +// internal errors +const ( + errPaginationComplete = errorsx.String("pagination complete") +) diff --git a/vendor/github.com/slack-go/slack/files.go b/vendor/github.com/slack-go/slack/files.go new file mode 100644 index 000000000..810c476b7 --- /dev/null +++ b/vendor/github.com/slack-go/slack/files.go @@ -0,0 +1,671 @@ +package slack + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/url" + "strconv" + "strings" +) + +const ( + // Add here the defaults in the site + DEFAULT_FILES_USER = "" + DEFAULT_FILES_CHANNEL = "" + DEFAULT_FILES_TS_FROM = 0 + DEFAULT_FILES_TS_TO = -1 + DEFAULT_FILES_TYPES = "all" + DEFAULT_FILES_COUNT = 100 + DEFAULT_FILES_PAGE = 1 + DEFAULT_FILES_SHOW_HIDDEN = false +) + +// File contains all the information for a file +type File struct { + ID string `json:"id"` + Created JSONTime `json:"created"` + Timestamp JSONTime `json:"timestamp"` + + Name string `json:"name"` + Title string `json:"title"` + Mimetype string `json:"mimetype"` + ImageExifRotation int `json:"image_exif_rotation"` + Filetype string `json:"filetype"` + PrettyType string `json:"pretty_type"` + User string `json:"user"` + + Mode string `json:"mode"` + Editable bool `json:"editable"` + IsExternal bool `json:"is_external"` + ExternalType string `json:"external_type"` + + Size int `json:"size"` + + URL string `json:"url"` // Deprecated - never set + URLDownload string `json:"url_download"` // Deprecated - never set + URLPrivate string `json:"url_private"` + URLPrivateDownload string `json:"url_private_download"` + + OriginalH int `json:"original_h"` + OriginalW int `json:"original_w"` + Thumb64 string `json:"thumb_64"` + Thumb80 string `json:"thumb_80"` + Thumb160 string `json:"thumb_160"` + Thumb360 string `json:"thumb_360"` + Thumb360Gif string `json:"thumb_360_gif"` + Thumb360W int `json:"thumb_360_w"` + Thumb360H int `json:"thumb_360_h"` + Thumb480 string `json:"thumb_480"` + Thumb480W int `json:"thumb_480_w"` + Thumb480H int `json:"thumb_480_h"` + Thumb720 string `json:"thumb_720"` + Thumb720W int `json:"thumb_720_w"` + Thumb720H int `json:"thumb_720_h"` + Thumb960 string `json:"thumb_960"` + Thumb960W int `json:"thumb_960_w"` + Thumb960H int `json:"thumb_960_h"` + Thumb1024 string `json:"thumb_1024"` + Thumb1024W int `json:"thumb_1024_w"` + Thumb1024H int `json:"thumb_1024_h"` + + Permalink string `json:"permalink"` + PermalinkPublic string `json:"permalink_public"` + + EditLink string `json:"edit_link"` + Preview string `json:"preview"` + PreviewHighlight string `json:"preview_highlight"` + Lines int `json:"lines"` + LinesMore int `json:"lines_more"` + + IsPublic bool `json:"is_public"` + PublicURLShared bool `json:"public_url_shared"` + Channels []string `json:"channels"` + Groups []string `json:"groups"` + IMs []string `json:"ims"` + InitialComment Comment `json:"initial_comment"` + CommentsCount int `json:"comments_count"` + NumStars int `json:"num_stars"` + IsStarred bool `json:"is_starred"` + Shares Share `json:"shares"` + + Subject string `json:"subject"` + To []EmailFileUserInfo `json:"to"` + From []EmailFileUserInfo `json:"from"` + Cc []EmailFileUserInfo `json:"cc"` + Headers EmailHeaders `json:"headers"` +} + +type EmailFileUserInfo struct { + Address string `json:"address"` + Name string `json:"name"` + Original string `json:"original"` +} + +type EmailHeaders struct { + Date string `json:"date"` + InReplyTo string `json:"in_reply_to"` + ReplyTo string `json:"reply_to"` + MessageID string `json:"message_id"` +} + +type Share struct { + Public map[string][]ShareFileInfo `json:"public"` + Private map[string][]ShareFileInfo `json:"private"` +} + +type ShareFileInfo struct { + ReplyUsers []string `json:"reply_users"` + ReplyUsersCount int `json:"reply_users_count"` + ReplyCount int `json:"reply_count"` + Ts string `json:"ts"` + ThreadTs string `json:"thread_ts"` + LatestReply string `json:"latest_reply"` + ChannelName string `json:"channel_name"` + TeamID string `json:"team_id"` +} + +// FileUploadParameters contains all the parameters necessary (including the optional ones) for an UploadFile() request. +// +// There are three ways to upload a file. You can either set Content if file is small, set Reader if file is large, +// or provide a local file path in File to upload it from your filesystem. +// +// Note that when using the Reader option, you *must* specify the Filename, otherwise the Slack API isn't happy. +type FileUploadParameters struct { + File string + Content string + Reader io.Reader + Filetype string + Filename string + Title string + InitialComment string + Channels []string + ThreadTimestamp string +} + +// GetFilesParameters contains all the parameters necessary (including the optional ones) for a GetFiles() request +type GetFilesParameters struct { + User string + Channel string + TeamID string + TimestampFrom JSONTime + TimestampTo JSONTime + Types string + Count int + Page int + ShowHidden bool +} + +// ListFilesParameters contains all the parameters necessary (including the optional ones) for a ListFiles() request +type ListFilesParameters struct { + Limit int + User string + Channel string + TeamID string + Types string + Cursor string +} + +type UploadFileV2Parameters struct { + File string + FileSize int + Content string + Reader io.Reader + Filename string + Title string + InitialComment string + Blocks Blocks + Channel string + ThreadTimestamp string + AltTxt string + SnippetType string +} + +type GetUploadURLExternalParameters struct { + AltTxt string + FileSize int + FileName string + SnippetType string +} + +type GetUploadURLExternalResponse struct { + UploadURL string `json:"upload_url"` + FileID string `json:"file_id"` + SlackResponse +} + +type UploadToURLParameters struct { + UploadURL string + Reader io.Reader + File string + Content string + Filename string +} + +type FileSummary struct { + ID string `json:"id"` + Title string `json:"title"` +} + +type CompleteUploadExternalParameters struct { + Files []FileSummary + Blocks Blocks + Channel string + InitialComment string + ThreadTimestamp string +} + +type CompleteUploadExternalResponse struct { + SlackResponse + Files []FileSummary `json:"files"` +} + +type fileResponseFull struct { + File `json:"file"` + Paging `json:"paging"` + Comments []Comment `json:"comments"` + Files []File `json:"files"` + Metadata ResponseMetadata `json:"response_metadata"` + + SlackResponse +} + +// NewGetFilesParameters provides an instance of GetFilesParameters with all the sane default values set +func NewGetFilesParameters() GetFilesParameters { + return GetFilesParameters{ + User: DEFAULT_FILES_USER, + Channel: DEFAULT_FILES_CHANNEL, + TimestampFrom: DEFAULT_FILES_TS_FROM, + TimestampTo: DEFAULT_FILES_TS_TO, + Types: DEFAULT_FILES_TYPES, + Count: DEFAULT_FILES_COUNT, + Page: DEFAULT_FILES_PAGE, + ShowHidden: DEFAULT_FILES_SHOW_HIDDEN, + } +} + +func (api *Client) fileRequest(ctx context.Context, path string, values url.Values) (*fileResponseFull, error) { + response := &fileResponseFull{} + err := api.postMethod(ctx, path, values, response) + if err != nil { + return nil, err + } + + return response, response.Err() +} + +// GetFileInfo retrieves a file and related comments. +// For more details, see GetFileInfoContext documentation. +func (api *Client) GetFileInfo(fileID string, count, page int) (*File, []Comment, *Paging, error) { + return api.GetFileInfoContext(context.Background(), fileID, count, page) +} + +// GetFileInfoContext retrieves a file and related comments with a custom context. +// Slack API docs: https://api.slack.com/methods/files.info +func (api *Client) GetFileInfoContext(ctx context.Context, fileID string, count, page int) (*File, []Comment, *Paging, error) { + values := url.Values{ + "token": {api.token}, + "file": {fileID}, + "count": {strconv.Itoa(count)}, + "page": {strconv.Itoa(page)}, + } + + response, err := api.fileRequest(ctx, "files.info", values) + if err != nil { + return nil, nil, nil, err + } + return &response.File, response.Comments, &response.Paging, nil +} + +// GetFile retrieves a given file from its private download URL. +func (api *Client) GetFile(downloadURL string, writer io.Writer) error { + return api.GetFileContext(context.Background(), downloadURL, writer) +} + +// GetFileContext retrieves a given file from its private download URL with a custom context. +// For more details, see GetFile documentation. +func (api *Client) GetFileContext(ctx context.Context, downloadURL string, writer io.Writer) error { + return downloadFile(ctx, api.httpclient, api.token, downloadURL, writer, api) +} + +// GetFiles retrieves all files according to the parameters given. +// For more details, see GetFilesContext documentation. +func (api *Client) GetFiles(params GetFilesParameters) ([]File, *Paging, error) { + return api.GetFilesContext(context.Background(), params) +} + +// GetFilesContext retrieves all files according to the parameters given with a custom context. +// Slack API docs: https://api.slack.com/methods/files.list +func (api *Client) GetFilesContext(ctx context.Context, params GetFilesParameters) ([]File, *Paging, error) { + values := url.Values{ + "token": {api.token}, + } + if params.User != DEFAULT_FILES_USER { + values.Add("user", params.User) + } + if params.Channel != DEFAULT_FILES_CHANNEL { + values.Add("channel", params.Channel) + } + if params.TeamID != "" { + values.Add("team_id", params.TeamID) + } + if params.TimestampFrom != DEFAULT_FILES_TS_FROM { + values.Add("ts_from", strconv.FormatInt(int64(params.TimestampFrom), 10)) + } + if params.TimestampTo != DEFAULT_FILES_TS_TO { + values.Add("ts_to", strconv.FormatInt(int64(params.TimestampTo), 10)) + } + if params.Types != DEFAULT_FILES_TYPES { + values.Add("types", params.Types) + } + if params.Count != DEFAULT_FILES_COUNT { + values.Add("count", strconv.Itoa(params.Count)) + } + if params.Page != DEFAULT_FILES_PAGE { + values.Add("page", strconv.Itoa(params.Page)) + } + if params.ShowHidden != DEFAULT_FILES_SHOW_HIDDEN { + values.Add("show_files_hidden_by_limit", strconv.FormatBool(params.ShowHidden)) + } + + response, err := api.fileRequest(ctx, "files.list", values) + if err != nil { + return nil, nil, err + } + return response.Files, &response.Paging, nil +} + +// ListFiles retrieves all files according to the parameters given. Uses cursor based pagination. +// For more details, see ListFilesContext documentation. +func (api *Client) ListFiles(params ListFilesParameters) ([]File, *ListFilesParameters, error) { + return api.ListFilesContext(context.Background(), params) +} + +// ListFilesContext retrieves all files according to the parameters given with a custom context. +// Slack API docs: https://api.slack.com/methods/files.list +func (api *Client) ListFilesContext(ctx context.Context, params ListFilesParameters) ([]File, *ListFilesParameters, error) { + values := url.Values{ + "token": {api.token}, + } + + if params.User != DEFAULT_FILES_USER { + values.Add("user", params.User) + } + if params.Channel != DEFAULT_FILES_CHANNEL { + values.Add("channel", params.Channel) + } + if params.TeamID != "" { + values.Add("team_id", params.TeamID) + } + if params.Limit != DEFAULT_FILES_COUNT { + values.Add("limit", strconv.Itoa(params.Limit)) + } + if params.Cursor != "" { + values.Add("cursor", params.Cursor) + } + + response, err := api.fileRequest(ctx, "files.list", values) + if err != nil { + return nil, nil, err + } + + params.Cursor = response.Metadata.Cursor + + return response.Files, ¶ms, nil +} + +// UploadFile uploads a file. +// +// Deprecated: Use [Client.UploadFileV2] instead. +// +// Per Slack Changelog, specifically [https://api.slack.com/changelog#entry-march_2025_1](this entry), +// this will stop functioning on November 12, 2025. +// +// For more details, see: https://api.slack.com/methods/files.upload#markdown +func (api *Client) UploadFile(params FileUploadParameters) (file *File, err error) { + return api.UploadFileContext(context.Background(), params) +} + +// UploadFileContext uploads a file and setting a custom context. +// +// Deprecated: Use [Client.UploadFileV2Context] instead. +// +// Per Slack Changelog, specifically [https://api.slack.com/changelog#entry-march_2025_1](this entry), +// this will stop functioning on November 12, 2025. +// +// For more details, see: https://api.slack.com/methods/files.upload#markdown +func (api *Client) UploadFileContext(ctx context.Context, params FileUploadParameters) (file *File, err error) { + // Test if user token is valid. This helps because client.Do doesn't like this for some reason. XXX: More + // investigation needed, but for now this will do. + _, err = api.AuthTestContext(ctx) + if err != nil { + return nil, err + } + response := &fileResponseFull{} + values := url.Values{} + if params.Filetype != "" { + values.Add("filetype", params.Filetype) + } + if params.Filename != "" { + values.Add("filename", params.Filename) + } + if params.Title != "" { + values.Add("title", params.Title) + } + if params.InitialComment != "" { + values.Add("initial_comment", params.InitialComment) + } + if params.ThreadTimestamp != "" { + values.Add("thread_ts", params.ThreadTimestamp) + } + if len(params.Channels) != 0 { + values.Add("channels", strings.Join(params.Channels, ",")) + } + if params.Content != "" { + values.Add("content", params.Content) + values.Add("token", api.token) + err = api.postMethod(ctx, "files.upload", values, response) + } else if params.File != "" { + err = postLocalWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.File, "file", api.token, values, response, api) + } else if params.Reader != nil { + if params.Filename == "" { + return nil, fmt.Errorf("files.upload: FileUploadParameters.Filename is mandatory when using FileUploadParameters.Reader") + } + err = postWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.Filename, "file", api.token, values, params.Reader, response, api) + } + + if err != nil { + return nil, err + } + + return &response.File, response.Err() +} + +// DeleteFileComment deletes a file's comment. +// For more details, see DeleteFileCommentContext documentation. +func (api *Client) DeleteFileComment(commentID, fileID string) error { + return api.DeleteFileCommentContext(context.Background(), fileID, commentID) +} + +// DeleteFileCommentContext deletes a file's comment with a custom context. +// Slack API docs: https://api.slack.com/methods/files.comments.delete +func (api *Client) DeleteFileCommentContext(ctx context.Context, fileID, commentID string) (err error) { + if fileID == "" || commentID == "" { + return ErrParametersMissing + } + + values := url.Values{ + "token": {api.token}, + "file": {fileID}, + "id": {commentID}, + } + _, err = api.fileRequest(ctx, "files.comments.delete", values) + return err +} + +// DeleteFile deletes a file. +// For more details, see DeleteFileContext documentation. +func (api *Client) DeleteFile(fileID string) error { + return api.DeleteFileContext(context.Background(), fileID) +} + +// DeleteFileContext deletes a file with a custom context. +// Slack API docs: https://api.slack.com/methods/files.delete +func (api *Client) DeleteFileContext(ctx context.Context, fileID string) (err error) { + values := url.Values{ + "token": {api.token}, + "file": {fileID}, + } + + _, err = api.fileRequest(ctx, "files.delete", values) + return err +} + +// RevokeFilePublicURL disables public/external sharing for a file. +// For more details, see RevokeFilePublicURLContext documentation. +func (api *Client) RevokeFilePublicURL(fileID string) (*File, error) { + return api.RevokeFilePublicURLContext(context.Background(), fileID) +} + +// RevokeFilePublicURLContext disables public/external sharing for a file with a custom context. +// Slack API docs: https://api.slack.com/methods/files.revokePublicURL +func (api *Client) RevokeFilePublicURLContext(ctx context.Context, fileID string) (*File, error) { + values := url.Values{ + "token": {api.token}, + "file": {fileID}, + } + + response, err := api.fileRequest(ctx, "files.revokePublicURL", values) + if err != nil { + return nil, err + } + return &response.File, nil +} + +// ShareFilePublicURL enabled public/external sharing for a file. +// For more details, see ShareFilePublicURLContext documentation. +func (api *Client) ShareFilePublicURL(fileID string) (*File, []Comment, *Paging, error) { + return api.ShareFilePublicURLContext(context.Background(), fileID) +} + +// ShareFilePublicURLContext enabled public/external sharing for a file with a custom context. +// Slack API docs: https://api.slack.com/methods/files.sharedPublicURL +func (api *Client) ShareFilePublicURLContext(ctx context.Context, fileID string) (*File, []Comment, *Paging, error) { + values := url.Values{ + "token": {api.token}, + "file": {fileID}, + } + + response, err := api.fileRequest(ctx, "files.sharedPublicURL", values) + if err != nil { + return nil, nil, nil, err + } + return &response.File, response.Comments, &response.Paging, nil +} + +// GetUploadURLExternalContext gets a URL and fileID from slack which can later be used to upload a file. +// Slack API docs: https://api.slack.com/methods/files.getUploadURLExternal +func (api *Client) GetUploadURLExternalContext(ctx context.Context, params GetUploadURLExternalParameters) (*GetUploadURLExternalResponse, error) { + if params.FileName == "" { + return nil, fmt.Errorf("FileName cannot be empty") + } + if params.FileSize == 0 { + return nil, fmt.Errorf("FileSize cannot be 0") + } + + values := url.Values{ + "token": {api.token}, + "filename": {params.FileName}, + "length": {strconv.Itoa(params.FileSize)}, + } + if params.AltTxt != "" { + values.Add("alt_txt", params.AltTxt) + } + if params.SnippetType != "" { + values.Add("snippet_type", params.SnippetType) + } + response := &GetUploadURLExternalResponse{} + err := api.postMethod(ctx, "files.getUploadURLExternal", values, response) + if err != nil { + return nil, err + } + + return response, response.Err() +} + +// UploadToURL uploads the file to the provided URL using post method +// This is not a Slack API method, but a helper function to upload files to the URL +func (api *Client) UploadToURL(ctx context.Context, params UploadToURLParameters) (err error) { + values := url.Values{} + if params.Content != "" { + contentReader := strings.NewReader(params.Content) + err = postWithMultipartResponse(ctx, api.httpclient, params.UploadURL, params.Filename, "file", api.token, values, contentReader, nil, api) + } else if params.File != "" { + err = postLocalWithMultipartResponse(ctx, api.httpclient, params.UploadURL, params.File, "file", api.token, values, nil, api) + } else if params.Reader != nil { + err = postWithMultipartResponse(ctx, api.httpclient, params.UploadURL, params.Filename, "file", api.token, values, params.Reader, nil, api) + } + return err +} + +// CompleteUploadExternalContext once files are uploaded, this completes the upload and shares it to the specified channel +// Slack API docs: https://api.slack.com/methods/files.completeUploadExternal +func (api *Client) CompleteUploadExternalContext(ctx context.Context, params CompleteUploadExternalParameters) (file *CompleteUploadExternalResponse, err error) { + filesBytes, err := json.Marshal(params.Files) + if err != nil { + return nil, err + } + + values := url.Values{ + "token": {api.token}, + "files": {string(filesBytes)}, + } + + if params.Channel != "" { + values.Add("channel_id", params.Channel) + } + if params.InitialComment != "" { + values.Add("initial_comment", params.InitialComment) + } + if params.Blocks.BlockSet != nil && params.InitialComment == "" { + blocksBytes, err := json.Marshal(params.Blocks) + if err != nil { + return nil, err + } + values.Add("blocks", string(blocksBytes)) + } + if params.ThreadTimestamp != "" { + values.Add("thread_ts", params.ThreadTimestamp) + } + response := &CompleteUploadExternalResponse{} + err = api.postMethod(ctx, "files.completeUploadExternal", values, response) + if err != nil { + return nil, err + } + if response.Err() != nil { + return nil, response.Err() + } + return response, nil +} + +// UploadFileV2 uploads file to a given slack channel using 3 steps. +// For more details, see UploadFileV2Context documentation. +func (api *Client) UploadFileV2(params UploadFileV2Parameters) (*FileSummary, error) { + return api.UploadFileV2Context(context.Background(), params) +} + +// UploadFileV2Context uploads file to a given slack channel using 3 steps - +// 1. Get an upload URL using files.getUploadURLExternal API +// 2. Send the file as a post to the URL provided by slack +// 3. Complete the upload and share it to the specified channel using files.completeUploadExternal +// +// Slack Docs: https://api.slack.com/messaging/files#uploading_files +func (api *Client) UploadFileV2Context(ctx context.Context, params UploadFileV2Parameters) (file *FileSummary, err error) { + if params.Filename == "" { + return nil, fmt.Errorf("file.upload.v2: filename cannot be empty") + } + if params.FileSize == 0 { + return nil, fmt.Errorf("file.upload.v2: file size cannot be 0") + } + + u, err := api.GetUploadURLExternalContext(ctx, GetUploadURLExternalParameters{ + AltTxt: params.AltTxt, + FileName: params.Filename, + FileSize: params.FileSize, + SnippetType: params.SnippetType, + }) + if err != nil { + return nil, err + } + + err = api.UploadToURL(ctx, UploadToURLParameters{ + UploadURL: u.UploadURL, + Reader: params.Reader, + File: params.File, + Content: params.Content, + Filename: params.Filename, + }) + if err != nil { + return nil, err + } + + c, err := api.CompleteUploadExternalContext(ctx, CompleteUploadExternalParameters{ + Files: []FileSummary{{ + ID: u.FileID, + Title: params.Title, + }}, + Channel: params.Channel, + InitialComment: params.InitialComment, + ThreadTimestamp: params.ThreadTimestamp, + Blocks: params.Blocks, + }) + if err != nil { + return nil, err + } + if len(c.Files) != 1 { + return nil, fmt.Errorf("file.upload.v2: something went wrong; received %d files instead of 1", len(c.Files)) + } + + return &c.Files[0], nil +} diff --git a/vendor/github.com/slack-go/slack/function_execute.go b/vendor/github.com/slack-go/slack/function_execute.go new file mode 100644 index 000000000..4ec8f9f4c --- /dev/null +++ b/vendor/github.com/slack-go/slack/function_execute.go @@ -0,0 +1,93 @@ +package slack + +import ( + "context" + "encoding/json" +) + +type ( + FunctionCompleteSuccessRequest struct { + FunctionExecutionID string `json:"function_execution_id"` + Outputs map[string]string `json:"outputs"` + } + + FunctionCompleteErrorRequest struct { + FunctionExecutionID string `json:"function_execution_id"` + Error string `json:"error"` + } +) + +type FunctionCompleteSuccessRequestOption func(opt *FunctionCompleteSuccessRequest) error + +func FunctionCompleteSuccessRequestOptionOutput(outputs map[string]string) FunctionCompleteSuccessRequestOption { + return func(opt *FunctionCompleteSuccessRequest) error { + if len(outputs) > 0 { + opt.Outputs = outputs + } + return nil + } +} + +// FunctionCompleteSuccess indicates function is completed +func (api *Client) FunctionCompleteSuccess(functionExecutionId string, options ...FunctionCompleteSuccessRequestOption) error { + return api.FunctionCompleteSuccessContext(context.Background(), functionExecutionId, options...) +} + +// FunctionCompleteSuccess indicates function is completed +func (api *Client) FunctionCompleteSuccessContext(ctx context.Context, functionExecutionId string, options ...FunctionCompleteSuccessRequestOption) error { + // More information: https://api.slack.com/methods/functions.completeSuccess + r := &FunctionCompleteSuccessRequest{ + FunctionExecutionID: functionExecutionId, + } + for _, option := range options { + option(r) + } + + endpoint := api.endpoint + "functions.completeSuccess" + jsonData, err := json.Marshal(r) + if err != nil { + return err + } + + response := &SlackResponse{} + if err := postJSON(ctx, api.httpclient, endpoint, api.token, jsonData, response, api); err != nil { + return err + } + + if !response.Ok { + return response.Err() + } + + return nil +} + +// FunctionCompleteError indicates function is completed with error +func (api *Client) FunctionCompleteError(functionExecutionID string, errorMessage string) error { + return api.FunctionCompleteErrorContext(context.Background(), functionExecutionID, errorMessage) +} + +// FunctionCompleteErrorContext indicates function is completed with error +func (api *Client) FunctionCompleteErrorContext(ctx context.Context, functionExecutionID string, errorMessage string) error { + // More information: https://api.slack.com/methods/functions.completeError + r := FunctionCompleteErrorRequest{ + FunctionExecutionID: functionExecutionID, + } + r.Error = errorMessage + + endpoint := api.endpoint + "functions.completeError" + jsonData, err := json.Marshal(r) + if err != nil { + return err + } + + response := &SlackResponse{} + if err := postJSON(ctx, api.httpclient, endpoint, api.token, jsonData, response, api); err != nil { + return err + } + + if !response.Ok { + return response.Err() + } + + return nil +} diff --git a/vendor/github.com/slack-go/slack/groups.go b/vendor/github.com/slack-go/slack/groups.go new file mode 100644 index 000000000..b77f909db --- /dev/null +++ b/vendor/github.com/slack-go/slack/groups.go @@ -0,0 +1,7 @@ +package slack + +// Group contains all the information for a group +type Group struct { + GroupConversation + IsGroup bool `json:"is_group"` +} diff --git a/vendor/github.com/slack-go/slack/history.go b/vendor/github.com/slack-go/slack/history.go new file mode 100644 index 000000000..49dfe3540 --- /dev/null +++ b/vendor/github.com/slack-go/slack/history.go @@ -0,0 +1,37 @@ +package slack + +const ( + DEFAULT_HISTORY_LATEST = "" + DEFAULT_HISTORY_OLDEST = "0" + DEFAULT_HISTORY_COUNT = 100 + DEFAULT_HISTORY_INCLUSIVE = false + DEFAULT_HISTORY_UNREADS = false +) + +// HistoryParameters contains all the necessary information to help in the retrieval of history for Channels/Groups/DMs +type HistoryParameters struct { + Latest string + Oldest string + Count int + Inclusive bool + Unreads bool +} + +// History contains message history information needed to navigate a Channel / Group / DM history +type History struct { + Latest string `json:"latest"` + Messages []Message `json:"messages"` + HasMore bool `json:"has_more"` + Unread int `json:"unread_count_display"` +} + +// NewHistoryParameters provides an instance of HistoryParameters with all the sane default values set +func NewHistoryParameters() HistoryParameters { + return HistoryParameters{ + Latest: DEFAULT_HISTORY_LATEST, + Oldest: DEFAULT_HISTORY_OLDEST, + Count: DEFAULT_HISTORY_COUNT, + Inclusive: DEFAULT_HISTORY_INCLUSIVE, + Unreads: DEFAULT_HISTORY_UNREADS, + } +} diff --git a/vendor/github.com/slack-go/slack/im.go b/vendor/github.com/slack-go/slack/im.go new file mode 100644 index 000000000..7c4bc2572 --- /dev/null +++ b/vendor/github.com/slack-go/slack/im.go @@ -0,0 +1,21 @@ +package slack + +type imChannel struct { + ID string `json:"id"` +} + +type imResponseFull struct { + NoOp bool `json:"no_op"` + AlreadyClosed bool `json:"already_closed"` + AlreadyOpen bool `json:"already_open"` + Channel imChannel `json:"channel"` + IMs []IM `json:"ims"` + History + SlackResponse +} + +// IM contains information related to the Direct Message channel +type IM struct { + Conversation + IsUserDeleted bool `json:"is_user_deleted"` +} diff --git a/vendor/github.com/slack-go/slack/info.go b/vendor/github.com/slack-go/slack/info.go new file mode 100644 index 000000000..a026ab494 --- /dev/null +++ b/vendor/github.com/slack-go/slack/info.go @@ -0,0 +1,479 @@ +package slack + +import ( + "bytes" + "context" + "fmt" + "net/url" + "strconv" + "strings" + "time" +) + +type UserPrefsCarrier struct { + SlackResponse + UserPrefs *UserPrefs `json:"prefs"` +} + +// UserPrefs carries a bunch of user settings including some unknown types +type UserPrefs struct { + UserColors string `json:"user_colors,omitempty"` + ColorNamesInList bool `json:"color_names_in_list,omitempty"` + // Keyboard UnknownType `json:"keyboard"` + EmailAlerts string `json:"email_alerts,omitempty"` + EmailAlertsSleepUntil int `json:"email_alerts_sleep_until,omitempty"` + EmailTips bool `json:"email_tips,omitempty"` + EmailWeekly bool `json:"email_weekly,omitempty"` + EmailOffers bool `json:"email_offers,omitempty"` + EmailResearch bool `json:"email_research,omitempty"` + EmailDeveloper bool `json:"email_developer,omitempty"` + WelcomeMessageHidden bool `json:"welcome_message_hidden,omitempty"` + SearchSort string `json:"search_sort,omitempty"` + SearchFileSort string `json:"search_file_sort,omitempty"` + SearchChannelSort string `json:"search_channel_sort,omitempty"` + SearchPeopleSort string `json:"search_people_sort,omitempty"` + ExpandInlineImages bool `json:"expand_inline_images,omitempty"` + ExpandInternalInlineImages bool `json:"expand_internal_inline_images,omitempty"` + ExpandSnippets bool `json:"expand_snippets,omitempty"` + PostsFormattingGuide bool `json:"posts_formatting_guide,omitempty"` + SeenWelcome2 bool `json:"seen_welcome_2,omitempty"` + SeenSSBPrompt bool `json:"seen_ssb_prompt,omitempty"` + SpacesNewXpBannerDismissed bool `json:"spaces_new_xp_banner_dismissed,omitempty"` + SearchOnlyMyChannels bool `json:"search_only_my_channels,omitempty"` + SearchOnlyCurrentTeam bool `json:"search_only_current_team,omitempty"` + SearchHideMyChannels bool `json:"search_hide_my_channels,omitempty"` + SearchOnlyShowOnline bool `json:"search_only_show_online,omitempty"` + SearchHideDeactivatedUsers bool `json:"search_hide_deactivated_users,omitempty"` + EmojiMode string `json:"emoji_mode,omitempty"` + EmojiUse string `json:"emoji_use,omitempty"` + HasInvited bool `json:"has_invited,omitempty"` + HasUploaded bool `json:"has_uploaded,omitempty"` + HasCreatedChannel bool `json:"has_created_channel,omitempty"` + HasSearched bool `json:"has_searched,omitempty"` + SearchExcludeChannels string `json:"search_exclude_channels,omitempty"` + MessagesTheme string `json:"messages_theme,omitempty"` + WebappSpellcheck bool `json:"webapp_spellcheck,omitempty"` + NoJoinedOverlays bool `json:"no_joined_overlays,omitempty"` + NoCreatedOverlays bool `json:"no_created_overlays,omitempty"` + DropboxEnabled bool `json:"dropbox_enabled,omitempty"` + SeenDomainInviteReminder bool `json:"seen_domain_invite_reminder,omitempty"` + SeenMemberInviteReminder bool `json:"seen_member_invite_reminder,omitempty"` + MuteSounds bool `json:"mute_sounds,omitempty"` + ArrowHistory bool `json:"arrow_history,omitempty"` + TabUIReturnSelects bool `json:"tab_ui_return_selects,omitempty"` + ObeyInlineImgLimit bool `json:"obey_inline_img_limit,omitempty"` + RequireAt bool `json:"require_at,omitempty"` + SsbSpaceWindow string `json:"ssb_space_window,omitempty"` + MacSsbBounce string `json:"mac_ssb_bounce,omitempty"` + MacSsbBullet bool `json:"mac_ssb_bullet,omitempty"` + ExpandNonMediaAttachments bool `json:"expand_non_media_attachments,omitempty"` + ShowTyping bool `json:"show_typing,omitempty"` + PagekeysHandled bool `json:"pagekeys_handled,omitempty"` + LastSnippetType string `json:"last_snippet_type,omitempty"` + DisplayRealNamesOverride int `json:"display_real_names_override,omitempty"` + DisplayDisplayNames bool `json:"display_display_names,omitempty"` + Time24 bool `json:"time24,omitempty"` + EnterIsSpecialInTbt bool `json:"enter_is_special_in_tbt,omitempty"` + MsgInputSendBtn bool `json:"msg_input_send_btn,omitempty"` + MsgInputSendBtnAutoSet bool `json:"msg_input_send_btn_auto_set,omitempty"` + MsgInputStickyComposer bool `json:"msg_input_sticky_composer,omitempty"` + GraphicEmoticons bool `json:"graphic_emoticons,omitempty"` + ConvertEmoticons bool `json:"convert_emoticons,omitempty"` + SsEmojis bool `json:"ss_emojis,omitempty"` + SeenOnboardingStart bool `json:"seen_onboarding_start,omitempty"` + OnboardingCancelled bool `json:"onboarding_cancelled,omitempty"` + SeenOnboardingSlackbotConversation bool `json:"seen_onboarding_slackbot_conversation,omitempty"` + SeenOnboardingChannels bool `json:"seen_onboarding_channels,omitempty"` + SeenOnboardingDirectMessages bool `json:"seen_onboarding_direct_messages,omitempty"` + SeenOnboardingInvites bool `json:"seen_onboarding_invites,omitempty"` + SeenOnboardingSearch bool `json:"seen_onboarding_search,omitempty"` + SeenOnboardingRecentMentions bool `json:"seen_onboarding_recent_mentions,omitempty"` + SeenOnboardingStarredItems bool `json:"seen_onboarding_starred_items,omitempty"` + SeenOnboardingPrivateGroups bool `json:"seen_onboarding_private_groups,omitempty"` + SeenOnboardingBanner bool `json:"seen_onboarding_banner,omitempty"` + OnboardingSlackbotConversationStep int `json:"onboarding_slackbot_conversation_step,omitempty"` + SetTzAutomatically bool `json:"set_tz_automatically,omitempty"` + SuppressLinkWarning bool `json:"suppress_link_warning,omitempty"` + DndEnabled bool `json:"dnd_enabled,omitempty"` + DndStartHour string `json:"dnd_start_hour,omitempty"` + DndEndHour string `json:"dnd_end_hour,omitempty"` + DndBeforeMonday string `json:"dnd_before_monday,omitempty"` + DndAfterMonday string `json:"dnd_after_monday,omitempty"` + DndEnabledMonday string `json:"dnd_enabled_monday,omitempty"` + DndBeforeTuesday string `json:"dnd_before_tuesday,omitempty"` + DndAfterTuesday string `json:"dnd_after_tuesday,omitempty"` + DndEnabledTuesday string `json:"dnd_enabled_tuesday,omitempty"` + DndBeforeWednesday string `json:"dnd_before_wednesday,omitempty"` + DndAfterWednesday string `json:"dnd_after_wednesday,omitempty"` + DndEnabledWednesday string `json:"dnd_enabled_wednesday,omitempty"` + DndBeforeThursday string `json:"dnd_before_thursday,omitempty"` + DndAfterThursday string `json:"dnd_after_thursday,omitempty"` + DndEnabledThursday string `json:"dnd_enabled_thursday,omitempty"` + DndBeforeFriday string `json:"dnd_before_friday,omitempty"` + DndAfterFriday string `json:"dnd_after_friday,omitempty"` + DndEnabledFriday string `json:"dnd_enabled_friday,omitempty"` + DndBeforeSaturday string `json:"dnd_before_saturday,omitempty"` + DndAfterSaturday string `json:"dnd_after_saturday,omitempty"` + DndEnabledSaturday string `json:"dnd_enabled_saturday,omitempty"` + DndBeforeSunday string `json:"dnd_before_sunday,omitempty"` + DndAfterSunday string `json:"dnd_after_sunday,omitempty"` + DndEnabledSunday string `json:"dnd_enabled_sunday,omitempty"` + DndDays string `json:"dnd_days,omitempty"` + DndCustomNewBadgeSeen bool `json:"dnd_custom_new_badge_seen,omitempty"` + DndNotificationScheduleNewBadgeSeen bool `json:"dnd_notification_schedule_new_badge_seen,omitempty"` + // UnreadCollapsedChannels unknownType `json:"unread_collapsed_channels,omitempty"` + SidebarBehavior string `json:"sidebar_behavior,omitempty"` + ChannelSort string `json:"channel_sort,omitempty"` + SeparatePrivateChannels bool `json:"separate_private_channels,omitempty"` + SeparateSharedChannels bool `json:"separate_shared_channels,omitempty"` + SidebarTheme string `json:"sidebar_theme,omitempty"` + SidebarThemeCustomValues string `json:"sidebar_theme_custom_values,omitempty"` + NoInvitesWidgetInSidebar bool `json:"no_invites_widget_in_sidebar,omitempty"` + NoOmniboxInChannels bool `json:"no_omnibox_in_channels,omitempty"` + + KKeyOmniboxAutoHideCount int `json:"k_key_omnibox_auto_hide_count,omitempty"` + ShowSidebarQuickswitcherButton bool `json:"show_sidebar_quickswitcher_button,omitempty"` + EntOrgWideChannelsSidebar bool `json:"ent_org_wide_channels_sidebar,omitempty"` + MarkMsgsReadImmediately bool `json:"mark_msgs_read_immediately,omitempty"` + StartScrollAtOldest bool `json:"start_scroll_at_oldest,omitempty"` + SnippetEditorWrapLongLines bool `json:"snippet_editor_wrap_long_lines,omitempty"` + LsDisabled bool `json:"ls_disabled,omitempty"` + FKeySearch bool `json:"f_key_search,omitempty"` + KKeyOmnibox bool `json:"k_key_omnibox,omitempty"` + PromptedForEmailDisabling bool `json:"prompted_for_email_disabling,omitempty"` + NoMacelectronBanner bool `json:"no_macelectron_banner,omitempty"` + NoMacssb1Banner bool `json:"no_macssb1_banner,omitempty"` + NoMacssb2Banner bool `json:"no_macssb2_banner,omitempty"` + NoWinssb1Banner bool `json:"no_winssb1_banner,omitempty"` + HideUserGroupInfoPane bool `json:"hide_user_group_info_pane,omitempty"` + MentionsExcludeAtUserGroups bool `json:"mentions_exclude_at_user_groups,omitempty"` + MentionsExcludeReactions bool `json:"mentions_exclude_reactions,omitempty"` + PrivacyPolicySeen bool `json:"privacy_policy_seen,omitempty"` + EnterpriseMigrationSeen bool `json:"enterprise_migration_seen,omitempty"` + LastTosAcknowledged string `json:"last_tos_acknowledged,omitempty"` + SearchExcludeBots bool `json:"search_exclude_bots,omitempty"` + LoadLato2 bool `json:"load_lato_2,omitempty"` + FullerTimestamps bool `json:"fuller_timestamps,omitempty"` + LastSeenAtChannelWarning int `json:"last_seen_at_channel_warning,omitempty"` + EmojiAutocompleteBig bool `json:"emoji_autocomplete_big,omitempty"` + TwoFactorAuthEnabled bool `json:"two_factor_auth_enabled,omitempty"` + // TwoFactorType unknownType `json:"two_factor_type,omitempty"` + // TwoFactorBackupType unknownType `json:"two_factor_backup_type,omitempty"` + HideHexSwatch bool `json:"hide_hex_swatch,omitempty"` + ShowJumperScores bool `json:"show_jumper_scores,omitempty"` + EnterpriseMdmCustomMsg string `json:"enterprise_mdm_custom_msg,omitempty"` + // EnterpriseExcludedAppTeams unknownType `json:"enterprise_excluded_app_teams,omitempty"` + ClientLogsPri string `json:"client_logs_pri,omitempty"` + FlannelServerPool string `json:"flannel_server_pool,omitempty"` + MentionsExcludeAtChannels bool `json:"mentions_exclude_at_channels,omitempty"` + ConfirmClearAllUnreads bool `json:"confirm_clear_all_unreads,omitempty"` + ConfirmUserMarkedAway bool `json:"confirm_user_marked_away,omitempty"` + BoxEnabled bool `json:"box_enabled,omitempty"` + SeenSingleEmojiMsg bool `json:"seen_single_emoji_msg,omitempty"` + ConfirmShCallStart bool `json:"confirm_sh_call_start,omitempty"` + PreferredSkinTone string `json:"preferred_skin_tone,omitempty"` + ShowAllSkinTones bool `json:"show_all_skin_tones,omitempty"` + WhatsNewRead int `json:"whats_new_read,omitempty"` + // FrecencyJumper unknownType `json:"frecency_jumper,omitempty"` + FrecencyEntJumper string `json:"frecency_ent_jumper,omitempty"` + FrecencyEntJumperBackup string `json:"frecency_ent_jumper_backup,omitempty"` + Jumbomoji bool `json:"jumbomoji,omitempty"` + NewxpSeenLastMessage int `json:"newxp_seen_last_message,omitempty"` + ShowMemoryInstrument bool `json:"show_memory_instrument,omitempty"` + EnableUnreadView bool `json:"enable_unread_view,omitempty"` + SeenUnreadViewCoachmark bool `json:"seen_unread_view_coachmark,omitempty"` + EnableReactEmojiPicker bool `json:"enable_react_emoji_picker,omitempty"` + SeenCustomStatusBadge bool `json:"seen_custom_status_badge,omitempty"` + SeenCustomStatusCallout bool `json:"seen_custom_status_callout,omitempty"` + SeenCustomStatusExpirationBadge bool `json:"seen_custom_status_expiration_badge,omitempty"` + UsedCustomStatusKbShortcut bool `json:"used_custom_status_kb_shortcut,omitempty"` + SeenGuestAdminSlackbotAnnouncement bool `json:"seen_guest_admin_slackbot_announcement,omitempty"` + SeenThreadsNotificationBanner bool `json:"seen_threads_notification_banner,omitempty"` + SeenNameTaggingCoachmark bool `json:"seen_name_tagging_coachmark,omitempty"` + AllUnreadsSortOrder string `json:"all_unreads_sort_order,omitempty"` + Locale string `json:"locale,omitempty"` + SeenIntlChannelNamesCoachmark bool `json:"seen_intl_channel_names_coachmark,omitempty"` + SeenP2LocaleChangeMessage int `json:"seen_p2_locale_change_message,omitempty"` + SeenLocaleChangeMessage int `json:"seen_locale_change_message,omitempty"` + SeenJapaneseLocaleChangeMessage bool `json:"seen_japanese_locale_change_message,omitempty"` + SeenSharedChannelsCoachmark bool `json:"seen_shared_channels_coachmark,omitempty"` + SeenSharedChannelsOptInChangeMessage bool `json:"seen_shared_channels_opt_in_change_message,omitempty"` + HasRecentlySharedaChannel bool `json:"has_recently_shared_a_channel,omitempty"` + SeenChannelBrowserAdminCoachmark bool `json:"seen_channel_browser_admin_coachmark,omitempty"` + SeenAdministrationMenu bool `json:"seen_administration_menu,omitempty"` + SeenDraftsSectionCoachmark bool `json:"seen_drafts_section_coachmark,omitempty"` + SeenEmojiUpdateOverlayCoachmark bool `json:"seen_emoji_update_overlay_coachmark,omitempty"` + SeenSonicDeluxeToast int `json:"seen_sonic_deluxe_toast,omitempty"` + SeenWysiwygDeluxeToast bool `json:"seen_wysiwyg_deluxe_toast,omitempty"` + SeenMarkdownPasteToast int `json:"seen_markdown_paste_toast,omitempty"` + SeenMarkdownPasteShortcut int `json:"seen_markdown_paste_shortcut,omitempty"` + SeenIaEducation bool `json:"seen_ia_education,omitempty"` + PlainTextMode bool `json:"plain_text_mode,omitempty"` + ShowSharedChannelsEducationBanner bool `json:"show_shared_channels_education_banner,omitempty"` + AllowCallsToSetCurrentStatus bool `json:"allow_calls_to_set_current_status,omitempty"` + InInteractiveMasMigrationFlow bool `json:"in_interactive_mas_migration_flow,omitempty"` + SunsetInteractiveMessageViews int `json:"sunset_interactive_message_views,omitempty"` + ShdepPromoCodeSubmitted bool `json:"shdep_promo_code_submitted,omitempty"` + SeenShdepSlackbotMessage bool `json:"seen_shdep_slackbot_message,omitempty"` + SeenCallsInteractiveCoachmark bool `json:"seen_calls_interactive_coachmark,omitempty"` + AllowCmdTabIss bool `json:"allow_cmd_tab_iss,omitempty"` + SeenWorkflowBuilderDeluxeToast bool `json:"seen_workflow_builder_deluxe_toast,omitempty"` + WorkflowBuilderIntroModalClickedThrough bool `json:"workflow_builder_intro_modal_clicked_through,omitempty"` + // WorkflowBuilderCoachmarks unknownType `json:"workflow_builder_coachmarks,omitempty"` + SeenGdriveCoachmark bool `json:"seen_gdrive_coachmark,omitempty"` + OverloadedMessageEnabled bool `json:"overloaded_message_enabled,omitempty"` + SeenHighlightsCoachmark bool `json:"seen_highlights_coachmark,omitempty"` + SeenHighlightsArrowsCoachmark bool `json:"seen_highlights_arrows_coachmark,omitempty"` + SeenHighlightsWarmWelcome bool `json:"seen_highlights_warm_welcome,omitempty"` + SeenNewSearchUi bool `json:"seen_new_search_ui,omitempty"` + SeenChannelSearch bool `json:"seen_channel_search,omitempty"` + SeenPeopleSearch bool `json:"seen_people_search,omitempty"` + SeenPeopleSearchCount int `json:"seen_people_search_count,omitempty"` + DismissedScrollSearchTooltipCount int `json:"dismissed_scroll_search_tooltip_count,omitempty"` + LastDismissedScrollSearchTooltipTimestamp int `json:"last_dismissed_scroll_search_tooltip_timestamp,omitempty"` + HasUsedQuickswitcherShortcut bool `json:"has_used_quickswitcher_shortcut,omitempty"` + SeenQuickswitcherShortcutTipCount int `json:"seen_quickswitcher_shortcut_tip_count,omitempty"` + BrowsersDismissedChannelsLowResultsEducation bool `json:"browsers_dismissed_channels_low_results_education,omitempty"` + BrowsersSeenInitialChannelsEducation bool `json:"browsers_seen_initial_channels_education,omitempty"` + BrowsersDismissedPeopleLowResultsEducation bool `json:"browsers_dismissed_people_low_results_education,omitempty"` + BrowsersSeenInitialPeopleEducation bool `json:"browsers_seen_initial_people_education,omitempty"` + BrowsersDismissedUserGroupsLowResultsEducation bool `json:"browsers_dismissed_user_groups_low_results_education,omitempty"` + BrowsersSeenInitialUserGroupsEducation bool `json:"browsers_seen_initial_user_groups_education,omitempty"` + BrowsersDismissedFilesLowResultsEducation bool `json:"browsers_dismissed_files_low_results_education,omitempty"` + BrowsersSeenInitialFilesEducation bool `json:"browsers_seen_initial_files_education,omitempty"` + A11yAnimations bool `json:"a11y_animations,omitempty"` + SeenKeyboardShortcutsCoachmark bool `json:"seen_keyboard_shortcuts_coachmark,omitempty"` + NeedsInitialPasswordSet bool `json:"needs_initial_password_set,omitempty"` + LessonsEnabled bool `json:"lessons_enabled,omitempty"` + TractorEnabled bool `json:"tractor_enabled,omitempty"` + TractorExperimentGroup string `json:"tractor_experiment_group,omitempty"` + OpenedSlackbotDm bool `json:"opened_slackbot_dm,omitempty"` + NewxpSuggestedChannels string `json:"newxp_suggested_channels,omitempty"` + OnboardingComplete bool `json:"onboarding_complete,omitempty"` + WelcomePlaceState string `json:"welcome_place_state,omitempty"` + // OnboardingRoleApps unknownType `json:"onboarding_role_apps,omitempty"` + HasReceivedThreadedMessage bool `json:"has_received_threaded_message,omitempty"` + SendYourFirstMessageBannerEnabled bool `json:"send_your_first_message_banner_enabled,omitempty"` + WhocanseethisDmMpdmBadge bool `json:"whocanseethis_dm_mpdm_badge,omitempty"` + HighlightWords string `json:"highlight_words,omitempty"` + ThreadsEverything bool `json:"threads_everything,omitempty"` + NoTextInNotifications bool `json:"no_text_in_notifications,omitempty"` + PushShowPreview bool `json:"push_show_preview,omitempty"` + GrowlsEnabled bool `json:"growls_enabled,omitempty"` + AllChannelsLoud bool `json:"all_channels_loud,omitempty"` + PushDmAlert bool `json:"push_dm_alert,omitempty"` + PushMentionAlert bool `json:"push_mention_alert,omitempty"` + PushEverything bool `json:"push_everything,omitempty"` + PushIdleWait int `json:"push_idle_wait,omitempty"` + PushSound string `json:"push_sound,omitempty"` + NewMsgSnd string `json:"new_msg_snd,omitempty"` + PushLoudChannels string `json:"push_loud_channels,omitempty"` + PushMentionChannels string `json:"push_mention_channels,omitempty"` + PushLoudChannelsSet string `json:"push_loud_channels_set,omitempty"` + LoudChannels string `json:"loud_channels,omitempty"` + NeverChannels string `json:"never_channels,omitempty"` + LoudChannelsSet string `json:"loud_channels_set,omitempty"` + AtChannelSuppressedChannels string `json:"at_channel_suppressed_channels,omitempty"` + PushAtChannelSuppressedChannels string `json:"push_at_channel_suppressed_channels,omitempty"` + MutedChannels string `json:"muted_channels,omitempty"` + // AllNotificationsPrefs unknownType `json:"all_notifications_prefs,omitempty"` + GrowthMsgLimitApproachingCtaCount int `json:"growth_msg_limit_approaching_cta_count,omitempty"` + GrowthMsgLimitApproachingCtaTs int `json:"growth_msg_limit_approaching_cta_ts,omitempty"` + GrowthMsgLimitReachedCtaCount int `json:"growth_msg_limit_reached_cta_count,omitempty"` + GrowthMsgLimitReachedCtaLastTs int `json:"growth_msg_limit_reached_cta_last_ts,omitempty"` + GrowthMsgLimitLongReachedCtaCount int `json:"growth_msg_limit_long_reached_cta_count,omitempty"` + GrowthMsgLimitLongReachedCtaLastTs int `json:"growth_msg_limit_long_reached_cta_last_ts,omitempty"` + GrowthMsgLimitSixtyDayBannerCtaCount int `json:"growth_msg_limit_sixty_day_banner_cta_count,omitempty"` + GrowthMsgLimitSixtyDayBannerCtaLastTs int `json:"growth_msg_limit_sixty_day_banner_cta_last_ts,omitempty"` + // GrowthAllBannersPrefs unknownType `json:"growth_all_banners_prefs,omitempty"` + AnalyticsUpsellCoachmarkSeen bool `json:"analytics_upsell_coachmark_seen,omitempty"` + SeenAppSpaceCoachmark bool `json:"seen_app_space_coachmark,omitempty"` + SeenAppSpaceTutorial bool `json:"seen_app_space_tutorial,omitempty"` + DismissedAppLauncherWelcome bool `json:"dismissed_app_launcher_welcome,omitempty"` + DismissedAppLauncherLimit bool `json:"dismissed_app_launcher_limit,omitempty"` + Purchaser bool `json:"purchaser,omitempty"` + ShowEntOnboarding bool `json:"show_ent_onboarding,omitempty"` + FoldersEnabled bool `json:"folders_enabled,omitempty"` + // FolderData unknownType `json:"folder_data,omitempty"` + SeenCorporateExportAlert bool `json:"seen_corporate_export_alert,omitempty"` + ShowAutocompleteHelp int `json:"show_autocomplete_help,omitempty"` + DeprecationToastLastSeen int `json:"deprecation_toast_last_seen,omitempty"` + DeprecationModalLastSeen int `json:"deprecation_modal_last_seen,omitempty"` + Iap1Lab int `json:"iap1_lab,omitempty"` + IaTopNavTheme string `json:"ia_top_nav_theme,omitempty"` + IaPlatformActionsLab int `json:"ia_platform_actions_lab,omitempty"` + ActivityView string `json:"activity_view,omitempty"` + FailoverProxyCheckCompleted int `json:"failover_proxy_check_completed,omitempty"` + EdgeUploadProxyCheckCompleted int `json:"edge_upload_proxy_check_completed,omitempty"` + AppSubdomainCheckCompleted int `json:"app_subdomain_check_completed,omitempty"` + AddAppsPromptDismissed bool `json:"add_apps_prompt_dismissed,omitempty"` + AddChannelPromptDismissed bool `json:"add_channel_prompt_dismissed,omitempty"` + ChannelSidebarHideInvite bool `json:"channel_sidebar_hide_invite,omitempty"` + InProdSurveysEnabled bool `json:"in_prod_surveys_enabled,omitempty"` + DismissedInstalledAppDmSuggestions string `json:"dismissed_installed_app_dm_suggestions,omitempty"` + SeenContextualMessageShortcutsModal bool `json:"seen_contextual_message_shortcuts_modal,omitempty"` + SeenMessageNavigationEducationalToast bool `json:"seen_message_navigation_educational_toast,omitempty"` + ContextualMessageShortcutsModalWasSeen bool `json:"contextual_message_shortcuts_modal_was_seen,omitempty"` + MessageNavigationToastWasSeen bool `json:"message_navigation_toast_was_seen,omitempty"` + UpToBrowseKbShortcut bool `json:"up_to_browse_kb_shortcut,omitempty"` + ChannelSections string `json:"channel_sections,omitempty"` + TZ string `json:"tz,omitempty"` +} + +func (api *Client) GetUserPrefs() (*UserPrefsCarrier, error) { + return api.GetUserPrefsContext(context.Background()) +} + +func (api *Client) GetUserPrefsContext(ctx context.Context) (*UserPrefsCarrier, error) { + response := UserPrefsCarrier{} + + err := api.getMethod(ctx, "users.prefs.get", api.token, url.Values{}, &response) + if err != nil { + return nil, err + } + + return &response, response.Err() +} + +func (api *Client) MuteChat(channelID string) (*UserPrefsCarrier, error) { + prefs, err := api.GetUserPrefs() + if err != nil { + return nil, err + } + chnls := strings.Split(prefs.UserPrefs.MutedChannels, ",") + for _, chn := range chnls { + if chn == channelID { + return nil, nil // noop + } + } + newChnls := prefs.UserPrefs.MutedChannels + "," + channelID + values := url.Values{"token": {api.token}, "muted_channels": {newChnls}, "reason": {"update-muted-channels"}} + response := UserPrefsCarrier{} + + err = api.postMethod(context.Background(), "users.prefs.set", values, &response) + if err != nil { + return nil, err + } + + return &response, response.Err() +} + +func (api *Client) UnMuteChat(channelID string) (*UserPrefsCarrier, error) { + prefs, err := api.GetUserPrefs() + if err != nil { + return nil, err + } + chnls := strings.Split(prefs.UserPrefs.MutedChannels, ",") + newChnls := make([]string, len(chnls)-1) + for i, chn := range chnls { + if chn == channelID { + return nil, nil // noop + } + newChnls[i] = chn + } + values := url.Values{"token": {api.token}, "muted_channels": {strings.Join(newChnls, ",")}, "reason": {"update-muted-channels"}} + response := UserPrefsCarrier{} + + err = api.postMethod(context.Background(), "users.prefs.set", values, &response) + if err != nil { + return nil, err + } + + return &response, response.Err() +} + +// UserDetails contains user details coming in the initial response from StartRTM +type UserDetails struct { + ID string `json:"id"` + Name string `json:"name"` + Created JSONTime `json:"created"` + ManualPresence string `json:"manual_presence"` + Prefs UserPrefs `json:"prefs"` +} + +// JSONTime exists so that we can have a String method converting the date +type JSONTime int64 + +// String converts the unix timestamp into a string +func (t JSONTime) String() string { + tm := t.Time() + return fmt.Sprintf("\"%s\"", tm.Format("Mon Jan _2")) +} + +// Time returns a `time.Time` representation of this value. +func (t JSONTime) Time() time.Time { + return time.Unix(int64(t), 0) +} + +// UnmarshalJSON will unmarshal both string and int JSON values +func (t *JSONTime) UnmarshalJSON(buf []byte) error { + s := bytes.Trim(buf, `"`) + + if bytes.EqualFold(s, []byte("null")) { + *t = JSONTime(0) + return nil + } + + v, err := strconv.Atoi(string(s)) + if err != nil { + return err + } + + *t = JSONTime(int64(v)) + return nil +} + +// Team contains details about a team +type Team struct { + ID string `json:"id"` + Name string `json:"name"` + Domain string `json:"domain"` + Icons *Icons `json:"icon,omitempty"` +} + +// Icons XXX: needs further investigation +type Icons struct { + Image36 string `json:"image_36,omitempty"` + Image48 string `json:"image_48,omitempty"` + Image72 string `json:"image_72,omitempty"` + Image132 string `json:"image_132,omitempty"` + Image230 string `json:"image_230,omitempty"` +} + +// Info contains various details about the authenticated user and team. +// It is returned by StartRTM or included in the "ConnectedEvent" RTM event. +type Info struct { + URL string `json:"url,omitempty"` + User *UserDetails `json:"self,omitempty"` + Team *Team `json:"team,omitempty"` +} + +type infoResponseFull struct { + Info + SlackResponse +} + +// GetBotByID is deprecated and returns nil +func (info Info) GetBotByID(botID string) *Bot { + return nil +} + +// GetUserByID is deprecated and returns nil +func (info Info) GetUserByID(userID string) *User { + return nil +} + +// GetChannelByID is deprecated and returns nil +func (info Info) GetChannelByID(channelID string) *Channel { + return nil +} + +// GetGroupByID is deprecated and returns nil +func (info Info) GetGroupByID(groupID string) *Group { + return nil +} + +// GetIMByID is deprecated and returns nil +func (info Info) GetIMByID(imID string) *IM { + return nil +} diff --git a/vendor/github.com/slack-go/slack/interactions.go b/vendor/github.com/slack-go/slack/interactions.go new file mode 100644 index 000000000..f658a72c2 --- /dev/null +++ b/vendor/github.com/slack-go/slack/interactions.go @@ -0,0 +1,250 @@ +package slack + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" +) + +// InteractionType type of interactions +type InteractionType string + +// ActionType type represents the type of action (attachment, block, etc.) +type ActionType string + +// action is an interface that should be implemented by all callback action types +type action interface { + actionType() ActionType +} + +// Types of interactions that can be received. +const ( + InteractionTypeDialogCancellation = InteractionType("dialog_cancellation") + InteractionTypeDialogSubmission = InteractionType("dialog_submission") + InteractionTypeDialogSuggestion = InteractionType("dialog_suggestion") + InteractionTypeInteractionMessage = InteractionType("interactive_message") + InteractionTypeMessageAction = InteractionType("message_action") + InteractionTypeBlockActions = InteractionType("block_actions") + InteractionTypeBlockSuggestion = InteractionType("block_suggestion") + InteractionTypeViewSubmission = InteractionType("view_submission") + InteractionTypeViewClosed = InteractionType("view_closed") + InteractionTypeShortcut = InteractionType("shortcut") + InteractionTypeWorkflowStepEdit = InteractionType("workflow_step_edit") +) + +// InteractionCallback is sent from slack when a user interactions with a button or dialog. +type InteractionCallback struct { + Type InteractionType `json:"type"` + Token string `json:"token"` + CallbackID string `json:"callback_id"` + ResponseURL string `json:"response_url"` + TriggerID string `json:"trigger_id"` + ActionTs string `json:"action_ts"` + Team Team `json:"team"` + Channel Channel `json:"channel"` + User User `json:"user"` + OriginalMessage Message `json:"original_message"` + Message Message `json:"message"` + Name string `json:"name"` + Value string `json:"value"` + MessageTs string `json:"message_ts"` + AttachmentID string `json:"attachment_id"` + ActionCallback ActionCallbacks `json:"actions"` + View View `json:"view"` + ActionID string `json:"action_id"` + APIAppID string `json:"api_app_id"` + BlockID string `json:"block_id"` + Container Container `json:"container"` + Enterprise Enterprise `json:"enterprise"` + IsEnterpriseInstall bool `json:"is_enterprise_install"` + DialogSubmissionCallback + ViewSubmissionCallback + ViewClosedCallback + + // FIXME(kanata2): just workaround for backward-compatibility. + // See also https://github.com/slack-go/slack/issues/816 + RawState json.RawMessage `json:"state,omitempty"` + + // BlockActionState stands for the `state` field in block_actions type. + // NOTE: InteractionCallback.State has a role for the state of dialog_submission type, + // so we cannot use this field for backward-compatibility for now. + BlockActionState *BlockActionStates `json:"-"` +} + +type BlockActionStates struct { + Values map[string]map[string]BlockAction `json:"values"` +} + +// InteractionCallbackParse parses the HTTP form value "payload" from r, unmarshals +// it as JSON into an InteractionCallback, and returns the result. +// It returns an error if the payload is missing or cannot be decoded. +// +// See https://github.com/slack-go/slack/issues/660 for context. +func InteractionCallbackParse(r *http.Request) (InteractionCallback, error) { + payload := r.FormValue("payload") + if len(payload) == 0 { + return InteractionCallback{}, errors.New("payload is empty") + } + + var ic InteractionCallback + if err := json.Unmarshal([]byte(payload), &ic); err != nil { + return InteractionCallback{}, err + } + return ic, nil +} + +func (ic *InteractionCallback) MarshalJSON() ([]byte, error) { + type alias InteractionCallback + tmp := alias(*ic) + if tmp.Type == InteractionTypeBlockActions { + if tmp.BlockActionState == nil { + tmp.RawState = []byte(`{}`) + } else { + state, err := json.Marshal(tmp.BlockActionState.Values) + if err != nil { + return nil, err + } + tmp.RawState = []byte(`{"values":` + string(state) + `}`) + } + } else if ic.Type == InteractionTypeDialogSubmission { + tmp.RawState = []byte(tmp.State) + } + // Use pointer for go1.7 + return json.Marshal(&tmp) +} + +func (ic *InteractionCallback) UnmarshalJSON(b []byte) error { + type alias InteractionCallback + tmp := struct { + Type InteractionType `json:"type"` + *alias + }{ + alias: (*alias)(ic), + } + if err := json.Unmarshal(b, &tmp); err != nil { + return err + } + *ic = InteractionCallback(*tmp.alias) + ic.Type = tmp.Type + if ic.Type == InteractionTypeBlockActions { + if len(ic.RawState) > 0 { + err := json.Unmarshal(ic.RawState, &ic.BlockActionState) + if err != nil { + return err + } + } + } else if ic.Type == InteractionTypeDialogSubmission { + ic.State = string(ic.RawState) + } + return nil +} + +type Container struct { + Type string `json:"type"` + ViewID string `json:"view_id"` + MessageTs string `json:"message_ts"` + ThreadTs string `json:"thread_ts,omitempty"` + AttachmentID json.Number `json:"attachment_id"` + ChannelID string `json:"channel_id"` + IsEphemeral bool `json:"is_ephemeral"` + IsAppUnfurl bool `json:"is_app_unfurl"` +} + +type Enterprise struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// ActionCallback is a convenience struct defined to allow dynamic unmarshalling of +// the "actions" value in Slack's JSON response, which varies depending on block type +type ActionCallbacks struct { + AttachmentActions []*AttachmentAction + BlockActions []*BlockAction +} + +// MarshalJSON implements the Marshaller interface in order to combine both +// action callback types back into a single array, like how the api responds. +// This makes Marshaling and Unmarshaling an InteractionCallback symmetrical +func (a ActionCallbacks) MarshalJSON() ([]byte, error) { + count := 0 + length := len(a.AttachmentActions) + len(a.BlockActions) + buffer := bytes.NewBufferString("[") + + f := func(obj interface{}) error { + js, err := json.Marshal(obj) + if err != nil { + return err + } + _, err = buffer.Write(js) + if err != nil { + return err + } + + count++ + if count < length { + _, err = buffer.WriteString(",") + return err + } + return nil + } + + for _, act := range a.AttachmentActions { + err := f(act) + if err != nil { + return nil, err + } + } + for _, blk := range a.BlockActions { + err := f(blk) + if err != nil { + return nil, err + } + } + buffer.WriteString("]") + return buffer.Bytes(), nil +} + +// UnmarshalJSON implements the Marshaller interface in order to delegate +// marshalling and allow for proper type assertion when decoding the response +func (a *ActionCallbacks) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + err := json.Unmarshal(data, &raw) + if err != nil { + return err + } + + for _, r := range raw { + var obj map[string]interface{} + err := json.Unmarshal(r, &obj) + if err != nil { + return err + } + + if _, ok := obj["block_id"].(string); ok { + action, err := unmarshalAction(r, &BlockAction{}) + if err != nil { + return err + } + + a.BlockActions = append(a.BlockActions, action.(*BlockAction)) + continue + } + + action, err := unmarshalAction(r, &AttachmentAction{}) + if err != nil { + return err + } + a.AttachmentActions = append(a.AttachmentActions, action.(*AttachmentAction)) + } + + return nil +} + +func unmarshalAction(r json.RawMessage, callbackAction action) (action, error) { + err := json.Unmarshal(r, callbackAction) + if err != nil { + return nil, err + } + return callbackAction, nil +} diff --git a/vendor/github.com/slack-go/slack/internal/backoff/backoff.go b/vendor/github.com/slack-go/slack/internal/backoff/backoff.go new file mode 100644 index 000000000..833e9f2b6 --- /dev/null +++ b/vendor/github.com/slack-go/slack/internal/backoff/backoff.go @@ -0,0 +1,62 @@ +package backoff + +import ( + "math/rand" + "time" +) + +// This one was ripped from https://github.com/jpillora/backoff/blob/master/backoff.go + +// Backoff is a time.Duration counter. It starts at Min. After every +// call to Duration() it is multiplied by Factor. It is capped at +// Max. It returns to Min on every call to Reset(). Used in +// conjunction with the time package. +type Backoff struct { + attempts int + // Initial value to scale out + Initial time.Duration + // Jitter value randomizes an additional delay between 0 and Jitter + Jitter time.Duration + // Max maximum values of the backoff + Max time.Duration +} + +// Returns the current value of the counter and then multiplies it +// Factor +func (b *Backoff) Duration() (dur time.Duration) { + // Zero-values are nonsensical, so we use + // them to apply defaults + if b.Max == 0 { + b.Max = 10 * time.Second + } + + if b.Initial == 0 { + b.Initial = 100 * time.Millisecond + } + + // calculate this duration + if dur = time.Duration(1 << uint(b.attempts)); dur > 0 { + dur = dur * b.Initial + } else { + dur = b.Max + } + + if b.Jitter > 0 { + dur = dur + time.Duration(rand.Intn(int(b.Jitter))) + } + + // bump attempts count + b.attempts++ + + return dur +} + +// Resets the current value of the counter back to Min +func (b *Backoff) Reset() { + b.attempts = 0 +} + +// Attempts returns the number of attempts that we had done so far +func (b *Backoff) Attempts() int { + return b.attempts +} diff --git a/vendor/github.com/slack-go/slack/internal/errorsx/errorsx.go b/vendor/github.com/slack-go/slack/internal/errorsx/errorsx.go new file mode 100644 index 000000000..0182ec68c --- /dev/null +++ b/vendor/github.com/slack-go/slack/internal/errorsx/errorsx.go @@ -0,0 +1,17 @@ +package errorsx + +// String representing an error, useful for declaring string constants as errors. +type String string + +func (t String) Error() string { + return string(t) +} + +// Is reports whether String matches with the target error +func (t String) Is(target error) bool { + if target == nil { + return false + } + + return t.Error() == target.Error() +} diff --git a/vendor/github.com/slack-go/slack/internal/timex/timex.go b/vendor/github.com/slack-go/slack/internal/timex/timex.go new file mode 100644 index 000000000..40063f738 --- /dev/null +++ b/vendor/github.com/slack-go/slack/internal/timex/timex.go @@ -0,0 +1,18 @@ +package timex + +import "time" + +// Max returns the maximum duration +func Max(values ...time.Duration) time.Duration { + var ( + max time.Duration + ) + + for _, v := range values { + if v > max { + max = v + } + } + + return max +} diff --git a/vendor/github.com/slack-go/slack/item.go b/vendor/github.com/slack-go/slack/item.go new file mode 100644 index 000000000..89af4eb15 --- /dev/null +++ b/vendor/github.com/slack-go/slack/item.go @@ -0,0 +1,75 @@ +package slack + +const ( + TYPE_MESSAGE = "message" + TYPE_FILE = "file" + TYPE_FILE_COMMENT = "file_comment" + TYPE_CHANNEL = "channel" + TYPE_IM = "im" + TYPE_GROUP = "group" +) + +// Item is any type of slack message - message, file, or file comment. +type Item struct { + Type string `json:"type"` + Channel string `json:"channel,omitempty"` + Message *Message `json:"message,omitempty"` + File *File `json:"file,omitempty"` + Comment *Comment `json:"comment,omitempty"` + Timestamp string `json:"ts,omitempty"` +} + +// NewMessageItem turns a message on a channel into a typed message struct. +func NewMessageItem(ch string, m *Message) Item { + return Item{Type: TYPE_MESSAGE, Channel: ch, Message: m} +} + +// NewFileItem turns a file into a typed file struct. +func NewFileItem(f *File) Item { + return Item{Type: TYPE_FILE, File: f} +} + +// NewFileCommentItem turns a file and comment into a typed file_comment struct. +func NewFileCommentItem(f *File, c *Comment) Item { + return Item{Type: TYPE_FILE_COMMENT, File: f, Comment: c} +} + +// NewChannelItem turns a channel id into a typed channel struct. +func NewChannelItem(ch string) Item { + return Item{Type: TYPE_CHANNEL, Channel: ch} +} + +// NewIMItem turns a channel id into a typed im struct. +func NewIMItem(ch string) Item { + return Item{Type: TYPE_IM, Channel: ch} +} + +// NewGroupItem turns a channel id into a typed group struct. +func NewGroupItem(ch string) Item { + return Item{Type: TYPE_GROUP, Channel: ch} +} + +// ItemRef is a reference to a message of any type. One of FileID, +// CommentId, or the combination of ChannelId and Timestamp must be +// specified. +type ItemRef struct { + Channel string `json:"channel"` + Timestamp string `json:"timestamp"` + File string `json:"file"` + Comment string `json:"file_comment"` +} + +// NewRefToMessage initializes a reference to to a message. +func NewRefToMessage(channel, timestamp string) ItemRef { + return ItemRef{Channel: channel, Timestamp: timestamp} +} + +// NewRefToFile initializes a reference to a file. +func NewRefToFile(file string) ItemRef { + return ItemRef{File: file} +} + +// NewRefToComment initializes a reference to a file comment. +func NewRefToComment(comment string) ItemRef { + return ItemRef{Comment: comment} +} diff --git a/vendor/github.com/slack-go/slack/logger.go b/vendor/github.com/slack-go/slack/logger.go new file mode 100644 index 000000000..90cb3caab --- /dev/null +++ b/vendor/github.com/slack-go/slack/logger.go @@ -0,0 +1,60 @@ +package slack + +import ( + "fmt" +) + +// logger is a logger interface compatible with both stdlib and some +// 3rd party loggers. +type logger interface { + Output(int, string) error +} + +// ilogger represents the internal logging api we use. +type ilogger interface { + logger + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) +} + +type Debug interface { + Debug() bool + + // Debugf print a formatted debug line. + Debugf(format string, v ...interface{}) + // Debugln print a debug line. + Debugln(v ...interface{}) +} + +// internalLog implements the additional methods used by our internal logging. +type internalLog struct { + logger +} + +// Println replicates the behaviour of the standard logger. +func (t internalLog) Println(v ...interface{}) { + t.Output(2, fmt.Sprintln(v...)) +} + +// Printf replicates the behaviour of the standard logger. +func (t internalLog) Printf(format string, v ...interface{}) { + t.Output(2, fmt.Sprintf(format, v...)) +} + +// Print replicates the behaviour of the standard logger. +func (t internalLog) Print(v ...interface{}) { + t.Output(2, fmt.Sprint(v...)) +} + +type discard struct{} + +func (t discard) Debug() bool { + return false +} + +// Debugf print a formatted debug line. +func (t discard) Debugf(format string, v ...interface{}) {} + +// Debugln print a debug line. +func (t discard) Debugln(v ...interface{}) {} diff --git a/vendor/github.com/slack-go/slack/logo.png b/vendor/github.com/slack-go/slack/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..9bd143459bfe55bb6e01e721623c51a367be7190 GIT binary patch literal 52440 zcma%i1yEewwr1n*8l1-6-8Hy2t_?KqPH=a3cWYb&gx~~12yVfGBtY=s8ixPB_uYHn z%&VEH>Z(3_?QeZc_FB76opW}qhT2;UR1#DG0Dz&WAgcucz`S0`dYytox z9`8Wm8YL8gbLzoXAJ=Ot`-*BWswO@Ilg!he1xAGb{8zVJlSG< zF)4pr!L4Nw*z*CDnP%bYlNK_F4zF+h(*Gi|XZG@t9ZxNbr(N6q)A636b0uIOYf=2= z_;LQ5Z*bp>TT?M*6RDAD@YNH=otUUg!qda*w%7F8$@Rli&+6sFQI&OH-_|CPJLPRh z<7M^L{+UO=DP?g}{&i1ElLY&Z;_qSp8-8NJW=&`aFTJNbN79eaHKEzTer4BOpT zMGiu*=OuH-zu6M8h^g8$2)Nfm27BR3E zH@&~UX7Fd&=KH+uhaE+j_bmSS)61s*a`!sVtm(sEpV>j9Ntee$@5%Smr+1*EwK436 zN5t*R%V#m()2H8`e1l7QU-C`9-P}JsI$1vM7mgiaLN0ouQi`M|Z>`pDo@#qppCRH^ z-O~d4&5!bz5~jg{gNMH*7>wvkgbr^6;yc4aU9v=e_TAvECGKB8T}n^eUJ3;djU>X| zo7Mybogbn7yuVzIoNC;^?s*B=7`=@g8Y6$YX@>{IP`ER885Wp1!|8dcRMkh2HBtjrC=78l#aZ;A7ExO%p>;>d8@J%Vki3 zcXmI97lEmIzrOcIujb1`SaH$vrCAe_KDa&j4JV=jS^Uig!PDccuh^eI?;f0gYi5kW z<3MdX`dRr-?*<}2=>7@%C~=l$ynZ|V!AB4}IU2Z+RMGi4a_T)tZ`4v(XnenMjmYNR zc_H`2yQ1;T{z5-af}=;gj~|1#w12H(ufySjBggQ9gfCBTjwYU%6$hbja==j+tQOfp z)_*)MYVa+9Kj6P+*-|(8kG_BO?=4O?l-AS=+%!H#mX4rTD;0=c%!JhU5{AY9+0G1R z4;ZHRoL&>0H>p;B_HDTF&`C5+4oBuI?B(dE%LvMX73&`v)lzT6~+{QN=fVX ziMv6W`XioS6dF@Ccyaqq#uvMBqnb4@P6X3rbF&zW;O2PVh;JsFY=Fst)7d7vQ{pqXv0m9Zl-;~VQbae(h7bd2R!%`yX+y(B~6G5nG{rh zdtXQI3zwcQu!duN2JT1iUcP?+>VtSOD*H)*G})|vDfr_J8))R2-tZ5kZ9BfXAN}GI zt+vhiKfqFBJ}YU+6?UL3{W4=?PD=&JSutk2 z1$qpoW8en5gYV5TZ&iXiNFUET%vO%GX`f5)rzx-gun?IC%|Gee2j&h`Urd?xzg+kD zB|cszx(wbu7NV42e-Z5exY;IA%zmK?E^a#%dVFJo#A-O%B=zkqYivKtdUCx9!qQU2 z)jo0d5Xrhby`g3vM4gD(PtUx-lR75%-q>gCR$9ZKGcF!BXF@L|?J)&@$>=gN7W;?3+ZirrQ z$>_xLd_B&_O%?|h^#`}mK)Y{~D_H;}R5-a2n_nLWHr`CMfbG&DW+XOAAxQZs(LWAJ-D* zCQ_UM6;l)_srN6#lcJ3LA<#xH}xyQcl`<06CP@8|iOcc$nER~PC zZ^zSlp!-IT_30q~WSWQ&#j0XN8$L@BH9a3HZ5lNfkAuuq4<(x6ygD14(vBrX9dB_? zKhM|t4s4(6al66LD!Jpwg*BK%X>r3xQy&i46uA`TKttZ@HNP%$20WgRXJ03Ehse5b ze(E2u^I-%Hws>qrd$D*Y&Yk2|X7AvxcR7k(vDdYU2e^#(Df56ANW3HK-KZVuFev32 z*pDaPWfNxS=hzy4Eci7>tb;eh_Fb_0xVB%XXr|r|DpIQ($UlNg9?pV`utfbdonB?R z#kZRmnOTf&lGVX>s^Kl%>u#Rtk;4g7xC)p2CM*4!ZIhj+K-}7uhQD|XMISQ@&~4K< z4Z^it!f5fF)Ly*HIi58nvuzH?H|@swLOMn-X7gPX@+BO}PHajBo|$JeB4sWkux$>W zXxfu_OxPR?CfqtSr@V~IJTBDEw6>MCb(gRD%#JQ%swM#LzIt%mt?$!RHF{J(12Ui` zuX!<1k2acOH&%C;_gJVl>i3T>?4cK7$`lQ~F+6JdL6C$X7hxd-P;>#43v z?h7}6Yyo>C?jfV=`X-{-$p#1E(cD^~YHxX6aL0N{Y2#-?s%slUTI2T6o4|r7-^04c zRur?bo6a_&no@GL$kTI;5{V^#y@3|Yw7Ff*Clq`oyP^&l3ek));qmvbGn#Ds2v63- zg>ywM_`X`-EE6&6sj{K&Qh>ux(#kF@+h2oVjqCAQU_!1juTJqrrlzcnEYJq>mE#&A zF(@8@u(vUM=xn;iI2Xl_`Zixje052+efMl|G%9uVwg-OzTg=7Twu>a$eb;hcxHLM0 zV1n-ik?}6A7FcgE#Rz!M23FmRkXggjBos6oU0@#D;MzzuuVB6u4tzJXbX;iP<(6gn zl*|fGFQ93~y#Il1z9W`w@!ByirDTC_GmeWz9oGCS>eg>X30E{EWCr8b?H`ZmDzl^D z(2dYYRST;V2uVQ4;7oGim&90(?K(--Y%74^hO^rc=@77n#TE4Uc(zx(d3SQ_29Vq; zs7d2b@(>Lbuns68Oi$0puw`(B5tYoJNwqb{n(A<4+-r=61~!CmM9Z(h9pVN!vy9^& z3mgg)i&qdR*W)(9rR0`g2<+WhSO5I%#as&KUZI+B!l%Obn6psGj&IBV~zYRsp#<0wS?~=WkOK+e)J17d57-h@cSo4uFB>FAK z&K}*Cptn_6GC}(EsvsjgVN@3~9QI=2Q;eXEzzn*Saq|GKwH{10iW$rs{hs;3q6D`c zTm4}598N(o*yc!bk-gutDzF0F#Bmaw3A-r`E!+EEjiF%N#&~9 zx;POXac5OgrZ;Qta2}{@KX->t?JOP02{R87dAkrVyKq5{0%e6n*7efOVG8F&?_<8X z7KF#^uSho5f3xc4;X=r<25=gQE84Nq!==REY$8jeg^y0Qpk;CJXzIiqILjX?l_fB# zJ0i+ON)?K#jmnCqZ@`#W>}qzhyn|E;m^11QtBQe;%$3)ESdtRYuga&WWuH$?+Uq2+ z?`Gc#`f9|;iz&|iWTv#HGyZ5bDOWalerIU4S8AL%26vc3OS1&KgqtKECa1H77X*hC zMambZ%7IZmmHS18xYGvO^2dta{J?#{kC+(ny}4-Sgz$EUzOgtei*AZ3civkkuW18= z@NI!|yt?}bJk=vulz|kK!FSwHT;P#@8`V34obL2dRI%;tG?|+3KNTj)CYa&-P(1i7 z1^b3X1 z6;VTMUN-5-JW<;tO!D`}B6oc>f9saGgk)KJnVhXo<{=ls*JP-kv!4Voa0@<+wq{Z-ZN2-PtMsS6Zn1=9u#o*)` z{j$(I9eQL@H95RhN5J0QhKxz|#b)5X@)i*C1w0BNN)TF>Bbzn1Kp%xa3C~W5qwm~q ztsV~aDZ&9b#qD|APag2Peu5pt8j6&xU|02qd6H!6jorzaAzQ$2_OY68Gg>EfsO6M> z8v+iaglVmMsggZC3n93Si-@VyixSK@G+)|AA~j8TW*^kFeuI~7BcACRZJB_AiHP83 zOVC@bOy3n1F~epQ6G4IwYoW9iAIFp^8Fj&|1?P(vGsYADPIAe}%8n>GtctcvIyCDW z1T&>_+KwQ=O}d>@0qMuE#TFSwVyY;RYiGDr@R%LJf*HMpDmw7zS|XD^Uu_5RRuQI$P~l{t}5Yd}lDB(^cqhy_%&dE)U=bK{1_x;hnl}H0sSi%2 z{F39axG8GfeCT*X$eSv|y~Ci#jj{++vs>APo?&E6$>f5J_emjnjtIn%uiq9n*%2y{>V3Gr-KVPy&os!;C z+$wIhS;RF@y-HbB%29emEM!?Au-SE_SfJj-do*vy69@~7=t$JH|A~Q*Qw@%~qliES zlMImLlyl73BJXR)1%=}q-9dmR(XhdK51WCpRRoVmFNannDH4!iJ@PU|D4pnFzmK`1{lw}r>*eU* z4Bpf^-#+=;cCJy688luT`<_S^bCM*?ho5=WanD;A7*j)Jrs8ME5pzIcz+`~0f({J( z4a0Y*Z^hg^5viZx9!E@le-JaJwz;67cn)e6%T7~?`fYy@{8FXorN zKAW%e=y^xt79yA(BD0iAI{4LG5SXce($~@4-U-CTIRoQI0^kXNRz|t<+DUocqAa^* ztQ3T=w<;XGh3=Xqj2RwrecZ_i&LIrcsCYa{p5M?LI%&HUG*PX)1i2)wl5bU{6KXz( zd^7)m_B7kKG+5>neu82OJt>)hUB=-PU6ucZA%~$q54>tfdDpn4sKPOXtJ#Zf2aR6l zELI_21&q?gPG7cCL5KlXu@|vfa48`?j_^IvH5QY)OGR7>pWi3lFcA2LQf)1T(%Q;p zWiaMpxWhcB#}2jerM9(10}_vL@I#lr#5yj*4pf>OM%y+yQf3L|_$IVkTyX~9aXi6a z$`}uz-1+zc1t?(_C?NO`-&0#yH1#t};1uQg_!K{NfiuD1(m1zHX`4s-ngbVbYPfzI zNYY}{m1b1NdeBthJT#NAlJ+29*O7Bm{%(%c+Ak+&$Utb&XolkROy1u`{iY(Inb0y= zW<~;>NIiw551_%k80;CwAVttu5IxWOe~RPIAP8+v|1fznAu&m&VgV7Rc0XzR(K!71 z5xoaJ+5ET9ytPe?2BNP^q(!UofG#!fIYBHEqZiE_ec7j(s5fDo^0k2yB|-H<@?WmP ze%;|wvzHd|AR@#w!cC&Wqc2Q=`CH~H$=JEy3Z>MdYNd{gCTOL}IY)Yr8TOE(A%!Em zl9!d3_i`kVbi-)woPDFplbQRY;- zot?gP9ue-T$wO!Ngfj-+XjvP0w`3?0^0kt_vD;FWfe@F1vIJ6pIdDX_XeK&o-v>36 z=uu}cYoMS;{1nalV2z~77x;emV}t7i;q zGQS&vogZz|png|o@fM4(SjHt%x*l9ne)&*U8{lLYKkq5zV^N>@@^oZ@k9*BE)? zMR3xZB=x0^&eV{azG;})90naC_oggopCuZltbJHAkd?CrQ!gya(dGsqgk!3Jo@14E zu*1$!%BpV&sc|EJ!l@l^L&tc}WP(yWA_->2fJoVLC+TI7DZfp}ycxxCp-4jsDgX@B zLKB&WiyGzKlMk*t7^Psma3^kU2lO;VaTcp@lrs2g&v6w-RdGCN$+i-u;argUY7hkJ zi@s{XkA8umSt@@nvE!|bUECcSkPj7O+5li9&Q{hOyMtD`a!_DF1}S$mvJ`nh3}_eP zhZ7WW!u?}%-d2HB2RUUoUfmL4z0ZdbWip)m=%_&mo;4ulcYRD&O{@JhoE;WlS>;wG zd@)-qfSUek5gdp;7(>k((?9q^TV=K>^X?@zdc>NQ-seT?pVp)kqEiLo|kI;}B> zmmg7Qad}<9+vHft_Cy4JU?b>o8#^>qf3OR?uPwsKFz2 z=OsYgqQlpA8rO8EL&zkjFNzWkh9g4JW7JTUB<^CxROz&><$FGFLR%z2s4rv`AJU_+<{MA1|=AKZ$du@9c>fHWEaBy7(t@Z*ULo5{gpT2 z;E}u(+c?7C24`Oj8RZ$T)0aj}Y)%RZt+7Sc>de@#``TJyPHc=oEzY@>$iKr~bEA)e z%_Ym;n&#a~X6%IxldKhVZmn1v3ydz`@jVbzPCiQC=PjYQlkxR%lpz84g# z=;f{d2CbH@I!#QASNV6HE))}D3Wi-N&;`tmY2o^2ZUJ(*luP`V*8LCz5SYe#7AqKB z_RemvK#~WvtX@_ropXq-2qMAtD$AoYtrtxJ1lC4=fbdA%cu65v2upN=f~?9}AS*0~ zZ%l6Qe@d}@-meVAE2<=R5RVsLYoCkjV|*ZyLvH&RuqFhSMv=y<`j1Z zhTGTP@1^s;adUZEpY*$MP!W6WO3~_Z@8N03c`^_}!$9Xe2uQ{Q&0B912y$n95bvqW z#+}2Ernuu2nMtHr8+$%3MyW-=F9n-}d_QQ7n;1>kVxM*~s(GxAv=cs{Fvlu0Z)?Up zD~K%N(jpQwBu|;OH3?itd^eXX1&m;`_rjL}vRe>PC&;pSVdmtq2QCx1xid=u>|K@c zo|b#zxYv`w0?Hox&pjnr1L#-DbubuGBD_k@zM2o=@njgCkTf5G(RfJo=v3I{hzx9YNkik!m>u7 zS(}86`1FQ;mFoNsH6$%N^! z=$e^&lTm`Z_Y+K2R)I7HmS5Zaii&fmfm=EORMghollV#viBoJZj&djn1zAK1TJGEH zj>Lh&vfQ1u3@4Ay-aUC{n zz<#AZDU6~|_lYb#c0)*U=~awUN$DuD)tEsXKCK~FC;%;x6A>R*?htqt&zSoKis`+X z^N1{S91$BsrLroSDkF?+Nxk5iE`m1EgOd#EY&bQE)a8$r94#%F^Bduf$4Uio^qhtsjJCY%yGo)z*o_0R0hE1`9nugf9e$6ZiE&WogK=jBx#vZj{Xf4#ww;^A74l`A8%pd;%Es2-)wO zL*yo^#WXXLkFr=Af97&$Oe+nLxnyxNY?B7KBPtZ}u(_zoB20!!=&E-@f%Xx&iEpg5 zDf+0@BeI+KHDw=kJO<|Q0=vbj1!_Fe>4Bt1RZ59M)vles3T2a;81$Mm+~gB9Y->5T z71cBRNQ>o;0OnXgas z*w|$=_O_|ZRS^(Wft^)UiM_GqvU>U*H&!X>xo@l`arIJ=bOKsQ#A>UUF;tZ(7Bjq0 zL;=&&pQdK~N#QL<-Xc(RagGQy#l)$J59#F_>UDfc+E(6Ug4mQOVdGb}#t=3qq>p_~ z2{Uw%slmaoHKTy%2+iWgg09&=dEs0&hRtS9%GCccX4!-LhSWPc&`#czxM3oE<|xiP z6CiW{=w7D_z>7iJmUxr8R?p0;sT7=z2VHM3JO*iGWn7H4xETe&B^UWwxYlF1EtjM0 zBl6W{nN?g%qolR1ry1sG=!Oz$c;kl2Egf;$8HbVE8Je8yvL}_XW~VAk;Dq(4H$0N#G}SreZs%d^j`hPs-3h^B zT|{kZucsKwYfc>q_C}I|T{K<;#)99_LcifY>r@31!2oy~0Ew>uY_4g|OBj?o%dO4eTf zfHev+t~Z4`Zrblz!w#vlCv~O+GAwnRwSFd7#f&4dNb^u=Ye$>cSgccVaBMXiPT3xH zeHyIDV$g=&9&A02r$K3PCmY`vbsMj+AC&~uL2Vn9jXeFBZoh%{gk?~aM?)qO&PA{q zWWDtB96e{P9I+Eyk#m|IevY)>$dDa<8JjSE`;FJyS2)w@IP?r^B{on)WwfF-NuLRO zG-7B@s*k*ijrk^1ICN-Z!4U6R!(DSU-;a;7>gLzr>q}ALMd|5-cJ&YK9$eVEa9_;% zoDUhH&6~9X8Kh85yp)ZfjPcFS@L^dY9$choq8)?gn3BxJ?P~dw(E88_-=9W?%{5V+ zFwNmOpHKMY0!SMx3%UsmStCfx&& z4ihaGHChlmgF&S#V`$-OhAZ~sB*p*&VPYNFeT*w1K%3SNXrQzQrY{9r);7OEz6=cs z1IYixw&+od?alvefTz0{_qIHfa8WdhsFXVQS(H6dQ$?7u&_h6g{g9H!Wpc%|H?)Sd zH||*flBRZnE@{iNxe#Te!`Asz2A$%Ks!8qf+j!A1JE)wMy&)njH7~-{9Js{DxLnHZ z5w|~^sYH;NfI0*c#)4p$>fyVi9mHRj9PCuI&=}`jg8qfYnQO5SGPT8dNJd6`P}@i* zh9%iD$waQ5u^YBMTnQU8kXa$z?3@{zEKX+&DAS*HUFC67I({t25EU#}!Uy3tSdpuv zVk(SNnP*Ps`aIY#$sewe4i;E?Hi|&zbQ|Y%29DEH^4fPPv0q{MDjPnt^9^qKb)_C3bXaKTFavRxein98 zR@FOG*jmcz3A&gQDEx{$yqz)`Bxvu)Q|nKI!w%6_JITGu-69_r(zgS^1CEp6n0fKf z=sL!czPrYp28T?%D^t?dFZcBM89}iM9pzkjAL7+rGvSqG@ELmyiRO$#)3m5N#s`5X zDpIRELzCqT*K!xo3^K~vBh_)8B0-F355)#6jw|IL7t6#lUR9$E zZ+U_8Ws;AdueOYq)P~>iTh-u}{h-j$D)o!eHF|%cg4`cYvt#we-Z0+XDU)DOX#u`2 z0MJQGVYk1Lsu;b!^J|2gHtVL!avOCE=LSQmaNEhs=nL+s#McDmYAUTDGsOH-T9FJ1OhO|i0vh|;e$@94ra3#qbv!l}vpAK|mK zIFy|jMiDZ9Ir5r?>Osq{t5n*_)y&1GHq@~0$dipisL?TM6a&9#Sf@aofzJqFebSNs943d*pKb2t+xs#`azU~x`Z8a(6VPq>mZ-79%Iv9ba zT$;xTe9kEjV;>kAQCQYV^Hv2NbzivNSq$jLn6HKjHx^w>NzfD&amc$2MZOxjtb$J* z#k)X0W56!ZU97A(u9XJdGNrbrBtFjS{Ml`;q0KNdtp5 z^bI56Q5qTdZRbT4o%|vyN4LC=l&;nUW37EyNiQyrUI@beD%2U)SA}|sX1_!gv!2eE zhN7K~6LPCTwz%gS?Av^k*5eJAmx@BWcKt zt{F+eq}>8qT0-2kf`OWB(vu*JFbG9?B6h#U3Zd5r6r2z{{pS3*-=(xAku!4Fl?i)i zZj6LrkEbxWb>5mAdN)hU>_e5@!un_Js}fW^{3n}U6WSIYzA@{iviZ$6zAjc%@%4{P%3=R8n>YLGQug^+eZ7xjOLG8|jGknR*J1{uFlley55 zff(QQK)Z9)RC;T`$jtxqmN#QJof0wy?=*O4Q=huUHVTzZe)Fxr zp~*K`yMJrQUkY2~XY@=Z&g^LYMx#cqz|Q$BT`8_C&b;~}c^&PpRrRy_VhiM?HxYV@ z;uzuvnS97mTP+!muNm?xeTWm&dAylvEM$o27^~9qI^W&<0pV<4es~V1+_rk zZ1N@!Oqy$ zJg#^(lgy$rUix-Qj6d3rC}C1-mXSC@w(zV3eS)8mw-!T3p~ujS7e7$K65B}fPtM{a zuFf8zqHX#PK!HTmfh;I}WYJ`~bON?7+>~KmfM<~6;H{)_=)lUMyxw=KtV#05nxK@j zW4<^6<~IgJ{Vq;zW2G|Odrmyus}VDZ?KdUNT76N%cZ}9Oquj8l6yJ#o#F=fWpnaej z*DhMOA}UKz1jZ%O5X$JpBaUvf1#zF==rqm;z*0H0(AIX2G)QbzlOk6KUZuk2NfN>l zKn>Lc#i<#$NJAvkswiryh9vBD3Z>XpPrSdO>~x^)L-}PtLMh@k`LHZy#XseTjeN|4 zV!qciH)2ro+zgZWjv{56nR!_wcdJ{8$K@dQQ>}A=pj9U2ZSx5FdxUlMz3NQBXkC1X znyTYDZ+Cf@h^`F0dKxK;d1$jsp#^uF_86UuOC}kQFv0au)xvFJ#m{>mq{*QT?jWVf zx`&0{9uq2u4Z+Mk^wf8J=QRfG8_&@V{M1|J?8hWE5>RAsX!pS~*P7ulQ5DI@+CYJ8 z=^ECz{wHFV>@XodAq_@W%wxN761q6%bbGbQayx+w3vzxf-RL+6N*G&0}M(^oQwU0@JvCvLBVK~>ej zT>3wZH5Tmkylb@Rd-Kb~4eM70Xs=3S(fI9k=C`&9!l^M%YdSw$6rx%$BDKM%!K)N{ z`#HlX@^eT8Pas^e+hg6-57Ea&942zbWA&Vi7;*N`BFuD)ro01v^=y}O1KnCJ4wvJz ziHAS>^F4oKQT`ALtb-0a*@sg6SQvtoJj!Ke;*@AlZ)=*p9~U<+Hn2Mk_tSDdT*kspsm*b{OmAkgNIk0& z;f4FN2I)4))$6d@`lQPCd6pwLC)z&pE2oqhc|a*|EsSJX;ppzSnPVy2IU6~GOQ5(4 zEAh!v7Pq5;j{Sk!=`0yG5i$R&45WLQFQHxvEDV>6dvYap^GT zplk;mFX()3uSg3|_Ri4|@0T-kxW#5RT@Wvy6|TlPkia2Bu(UDoq@0ASN;3NC?gK$W zD*b7J5=ocmrPVS$8SR!V6Waiaa-K^`B z;OvvIF(ypv^yG6}P>M>>!0!HG^Ru>YfDWd4O_T(Fp*^ir?Lx|fe%5REPZ|lv6PbP* zU0%^~OG_*)rk)XLOhzJ(2KmE2X4(2k1dr8AZkZX_i75!LkGk}9zoIj!e@%@j_l|Ot z8$sBmP*{Ln^JE-pEGXPaJA99usZbf@KZ|a92Blp?lB>Qd^}cGqhflkfJb^BRHAZQ#4X7|k~0(dr?xnf$e|4Q2vyuu)uu>Ie4{J6x*qp^P5t1?(@g z?$AjmP3BkU(?Nr~o}8VPhB{AFn`L^zMqSBohc+8}aLnY+Ny$%%nA>Wy;pMR@+iA^z z#x!#gBN0|^s-AgiNjGfY1W04g2R@X}BSyU|YKD42>e8IanWlf@cnB8&wuvNv@syd zCajUE0lZf*OmH@|ZjhmDv7PJO>b*mwN|RLHN9Ox^W68RAMkpN-Ek;qDaZ^@drPh27 zIt%cFQXPYLUNGM~FlsQhZO+FlVGEI+8U!jsS0oO?O2awZhgFOnmRIta(=R~W-M_Fc zt;gvzhik`2Yj%mLK_xS)NH8jk1l6$jLlh=7oUy;Dx|SLcV5q1g4?oTQIgen4lA3Se ziuILNATj^w@Oj$bST@qEE!3-EdBOfQ`L^cE%G=w+lFOMy6atGls#B`xf;TWFq!-F-wooOZy}}hBiW82el&3~MU6K~I`M|&WN4p!I5WP|} zkz~aG)@UHItS^9Fp-NU$S|l1@-%Dpdw&usCU3of3F09^McMx)V$)}?dOQVJFWfvlg zBnL4u`~xvb#q|0(myP4T>Rr^F0(InHZNo?qyq2Orke}j>v#gp3YkFlU!V*s}#Bx)y(R~{qcnA!XX`8gmHtak6J7Y5j1s5 zdJMVi+U_GsHVwN6d_{6!)y&th+?i*#y3ouYdJ&I3G z9W=uXGlll*%*^YzXXrg@S9j@B!7oXWaQ0O~c;1T>ycN~QT^`mu$=TnE!k9Gv)qlo- zCIdMxTydRs=_EnaW{sp?*+UNWuBd#ZGMSdEF_Nt{l*-rP1|L1yfAyxrpGAFW%^87_ zh`YGeIl12CjWyC?70Gm0uVm4wUQi244tKtYHx8_CTD*acV9ld*o@B~l{p~^A7&Br~ zExEbjtP6otnpa2NHn%o;ov$+wvb zCpGHHpWt@I}uN97JJUmwiF=e7@pvkT>HsYDudA_>u+m#8feUO(?EgEQc)zbTF#C^OH2yG7`(sEO)I zG9q9LBOY%SHK_T4yp4z~RpXy|GN=g)167|DF+XF(qlXdl`X${CToJwo4JRvk%Az`r zpqZ4y17y|+j>1XgKPjwW&+ka=FtU(<98u)P4;g=2E3s9=SZbeCz1#AlO1tSODEllX z*v;ozh@d~yTZWWUjQZ}_)<{?Aqgo9U6=icFoxQKGo0%6UPB*7>7W!x8n@wT1fFNHx ze%r{`_Z5iB9ckO0-62hLBZ%U59Cl+E8(Q=5Z2%)en~a=e(b-1mTq-qUp?+9-EdV9G zN$sB2Q4CvdQ)ET%Cp6(lOt#D|^vKpsg?nYA{l3a^5O)LPo#7BtDn9b3#lbaaPBCN5 z#K1=p06Ae;a}FqYvYgCS`r2ZS5Xv^or8bVbP@#2`#A+{CJ2$pmkI9TKUzEC^@Cv zi#dD@Wsx*Of{MXKt7+kI54xM>b+*0}JEWUAWDbd?8fj?}y6!=xcg?f*)XMTkFTA-w zR8e1EX;EMNKKGfG*~Sw?n^q}$dDce|6VsbTna>dlUNPlK#KRS% z5IL$YyyIv{66ZV5L;ltE1k4P*qedqfmMQ8QXE3KpNr(M6o|wJZGG<3{u_XVD@?MxY z;apR|)Vj6p4rQmjE8_1ee#!;x^!M}I4lS`{MnTYN)sttjT6?LnP~Y5i>oOs@IgD!B zs~81TI_VjD=m9$OuDh^zFM1t*X_^*LVWt7ZW3Bh>G@4H!A7=bE%SjJpwe_C=U~wx| z_EH$FGW|^UtxjgOH)|ok>pbiOB?-896=t@3*{fETqwW|LSyYjsS5*g7h$Zlya@^LP z5*4m(d<7R!=)W7e@+-PbR^kEi=yAI(~H}+ojGz;+rXj_vznF`Q7uMG zh|b#pxherYliPZk9z>T{r(bet%l^#aO_Dw%x6>8RY#gqY!iD2=kDrX<>ZfCN{k3AM zgkla7L2AOTAJ%G0S4jOl@0yHE5%$$Sab`Q^NEiD+Bhep(_u7Rs)U4k$q2O;Us{rbT zT@LC_CS1`16Z;*95Wz4kD0h1QDxfg#hZ;ln4?-A_6Vhl~SyV1!o2PkC|L14pp0vh* zHbOdWP;$Pf%7mIQPoi71@#0{Az9cmh%AurIIeR43d%3<of(Xg-oaezE9E=1^5|-$uehMvYU+b8usWOG31UfsrVqBV| zbEDJGE;xVmsutFZQBx4GJTZ)w;BEpnqYilgSKleE&k~up|ZcuT3^6)pBAytkfIC7;@gcdI+JZ^+(HHo6KOiTie5> z697$(XpaVVyzLfhFSjoaW!b59s1eTl0PY~x(J7BsDo9Mq)QDY~{ROW-X0RF_!nHkk zxT_c6foZugYj#flxxzpGk}S@?j`{0a`n9&plHgCFlaghdV27gtV_DV3!(RtTtWJi# zPQNC(3jaX=6u%2cAcF}vj$nfbIg8sA1@rWNC^Y@#v6CY#es@j)W;W&0_M$L(tcC$N z3$0JF6Urhv;1`xxrI-wYgE1+5%Vi5RR4MD zO()Ug{dNOiu*9|adWRL`H>v(ZN&wK?K^cme_rlL~X~?D! zkO5vuLAkjqP#v4ZdHt_&1P$9q4!ie46yb!hPS#sCKSv>*DC(8d3 zhEcn2IQ)^1kgJvE$_}S}lO#76q(GQei^;{p)HpNO$&ZfhGxojew0t*oF^r(ySQ&C9 z+}JHb9y08~>}8hOYHvEI#)q%7#&Bs{=DCtG6d z{W}r!VT8a7rK9oQnIs)D8#(qUcvdv*e+whsHUVn0!PVgVqQJ0Y!QRh|Xo?d7ptK;)$f;%Ei8t_FS{C!t z+K}_h^7&r8*o3cwcqh9fR7Fbo8}avKRi(!!17=%m1$Hr>I?EP-+LagVL z&8e!>c+s(=T0~z=CMTklL{-T&L5UZU1z%A2*{19}rdDr%aG(>kXQD6LB?3d~Xj8+G z-*|yEA|n}3NSNs7JSlF^lLi0acU!sZ42-vgkbo4DD4(!`rk7YhRjpTOkR1fJoFsEm zHKVnYbUp_k=b`mgRfH{FoY=uuE*21WUnkes^U?r-sD!U8*wO*wNo4`Cv2zv!o_**CQrTIF z0rmJ)IaOU{Ahvc2@7y8U@6%YVtK&rnXo(^I_eN_!A85eg56)!t4J13i*ubnqHP#l#?)ZNNjSW8y^pA@enF`%ud zr>igrhmVgByAKb$i@Oa6mynPU2PZcNH#gfWg3ZIv*%R!`=IlZ97sWp~WFa1w?sl%8 zb}r6Te{q5>T)aHRfWX&zs(+Hd&RWX(z6$?o;IHxD^d6p89Ez_4-q(0u0UX?%oPune z+-%%J9RI2RI;*PsFKuU!e`fJDpB%nmR}LTOo8)Ie30da&ly*lFY%FOlO@Sb+o|6ZW~7SCTZ|A!;5=KjV1 z-_ZY+ufKiyJFmjBE|y+@8C8@O1ODZ&u$7CYot5z4mpnXR9zL*zH52Z2oB~{eY`kDz zOEw`0Cxng5!U|%=$z^2$;j{b?3Uzn8*G>RC{-;-eQCYoG2|;+Q1^9R^*f_0(_}O?Z zc?8%j1UQA*xCOz25GydhfS{H2-&B9CgRqo_q8N~yo%7!k4M(u2wTrvcYkS!_Te*C}5|Ht!h=)YK`+&z6< z+#S^2)h+BHmY)B2p8pB_FD9+m-Oj_)-B0oV5!C;N6a7cQD!l5txcmKweQk)_KSux9 zk{s>+P8Ai^-`jvN*zzCg_W*lCto~kt*F64X%F-6>Yy)}SZ~xhB|0TEk9}1ZtYz>C+ zT3N91a|v;>@e1+rvRMdP@UU5Na|^sy3z(Oa^B;x$FLnYQ`ytGegEAGLPXu3fX%%f%*v+9&i;vw z^Aj7#hku`Ka)FQk?6Cj&wgUg`LGtpS{;NC${@J5GN&lmWUtJv?ZLQ3{{m*jxPrdoy zwEHjj|A&tLf8G9HoBjLUVh)a;z$&(MQFOQeKX(7WX!!3>kh3x|vv+p*KMnoAHu-n4 z{1-z6jQQVx0}LEsFF*dj2J=6(wD13755S}U)yaQLzW)-}zr^+5lE8nf z@xQd|U*h_2N#MWL_+Q%f|C_iF|A)(MW)I*#cfg@u%QD^roN-uVSt;>E~@IWe3I$zp=x$F zB-|_~o35&T&{+~1{(*r(xt2VyDx72?^uR&F{j{xw@s7nt!lhCZz3_m++P1u;L=&RW z{l||R(`Dvv;j;w(_*B!l(Sps4{o#0e_x0y>uZ?RTMd6q{>_R#TdKu+#m4yH8SIdu- z6s}0i!Nkt889iSNK`}74FzQgpx&snjvm`Rgh@d-#!E=Ncq!h>k2|iQ28f*{LhgCJ* zg5opna1~IEJL|gv*y5GnSKx;00(8+--tt9u?H6_-h`e7;3%sJHyK_o)%?!KuW6eZ# z(j{GNK|&hSn-tn$RQ3@v?pgqu5aKJnLf!OAY7_AfJB4|#!O>7~gf zhCj4Iv5n(ziW=Hx2-kw{dH0e`+rlH>mJoZKK%Ee@hH&3rO%@;%MFfKfx~2gM^s}AN zL+rs_+#YODT|-$~rFwiv6D_OkZFBt@UL`9+dO>%QJgXu;QIXRZ!E&;SG+=8 zqSXqtwZtU~sQNI!K#^=e12bTe^}JN|H*euD?*jRzqj2CE95M{z-wbQP8VF687w8vw z?_CC#vQXY3DG>~CQtHp*h0VSEZ;$p&ezu4mYW}Z!0}|auNjBkk3?Ro*<|Q;u=o^$3 zl$m;^tM>dN{(MF4OQV$+qJSZshZ1Cb;vfPu;l6A{Ip`Avm)7ab0@3r>BjI}~M0y39ga0fTT&w(f!I{-|&8!ps%bz4)WnKBvn z)P(Cz?~P$|CuNgHnk$XD^0Vwn440H-k-03E>(U4E97=d~bkl2v$SO)phJcB{11Cz4 zBbeGQ+^KCyc{}U^@3p5K^F8q7%L>!{g7FHr%eNK?3kxUzB06da&cT-t7oTGuVIUl~ zK(iIA=Fx>aZW8PDSez)`RF_(+<_*QIi6@ZlNoV5qOB`b=QeXMm0>CWc2X!!Gu||Zd zVlM45M`bZ(BN(f&5}& z8tNb*)V`6&PzauM>KlUT*ZcugAd9iST=%G^`cmYEf2NENEIv4kdT*CW$5yC;meO-Lp;fG5?~VVg44^mui}pS7 zY`8{(58bXS+Dc;Glc!c5?e}8N1@7bR)mDp5)nbnAN^RJAyw@1m*?jQun|?jXrG;sE zoiLy-&>+6?8L7ADTDnWTw3=7V*`nb|0>mvvGvhi-=co0m4Pv$pwFu3x2w<~kSZH@a zV;|-KOx63fp50PH2zr^cm}S&`Zy3r+*k9Y9s}|RIKPR5|w)yykKEhx)O!#}W-yY76 zqU9_RAJkF1RC>LIjv{t&<3MKQnW}ifKz5>L5Exo2c5hkU1rK~Yh7!03>@Y0S%v0E> zb_}4N4Sy4`t_#ZXJeS84s#x=4uiG2zUi0$B4FRE>T*Q}!To<^CH;6ZWw72Gh!wu8j zzNz@lP%NVd|Cr3|8lqesTi~|7COZ;iyTV6CgMMd1=#OyjzxKVs4 zSMAhi!3Ts*%r+RuWg==y?&m%CTRPc?*&h%8TD*O!nP)vhr~(Q70?Lz4twgD<0k}M0LB~yz^Zqcb@(>iFB6Cwy zOK_LT5b9R*hHrhx-Lj3RtE=nO`OL;y+1_kKy(5*RAi8xq#``n-@^f|mdsE&L4UBM( z5Xd`Adzt>|;-5Z|{4L;3r&6WkE^bIjHAH`=+*~hQR9g}9^8{-lNAvBaFyk3`JIO06 zPfZ2{K+-pD=F~gyE2vlL4s%QhY^MwR`925?Wmh>5kU;8rHF-y+!EX4WMz4a1G=hE1 z+zSq$Bk}du+TG8uvIM=(<~e`X)v-U{Z}??5yPYmqDW9dIdPB<%l^6h)*HssE5!e%p z|BJh#$%gxV|Wde_{bWh#Ep)$QmkW2V*IoQ!tY`4$BHV-tXo^ zI?&3c^w>484W_V}XbWn{&v@)-y7TU5IG2=P>zqHM-hbPVP=7+PBE5dMA@uI#e3*(? z6dFD(&Q=f=6|LXfaclRHO=el+bKV=R>VCPB6){i&&w!~*3$yYpXJd&E2PkyFC0_0K zHjiJjnclS9&cj~=%bqsg29K+|v(We8&?RD}<7sNWAHPZdyfPUrQd6(uC1`SpbclH( zZ1Iwec~lgBb+Oz1lPH%h)VVZ@X4t&KT%7Su=6pivdDQLob^%T($)CrcQAJizV(QBg zd^}+K4pBSsCoK{KNCVPRXX<`6Ih4t?KP5ouM@zx8zOT7&$g8WX_wMT{DfNWWX8m^G z@EJ;C*6C40N}umB!pdQ54;q3&(?=rfgy^v<&QyPXxt>`0es{9;HF z?gMNf99f_jP=z$}BettJ!se&QqmF~P$hd{i_h}QdTa*ibZhgyNON+DqWV)|QOG-*k z)2x?keB2vLmx}T1X7=aFvVM_z_rZC4#sm$K^5i}}?q^T@9vzii%rMp3o0k2!JAh}v zDZH=2wi*V&x1m@NfX>>CRpIL(OJD?zaiQ$uy1cW~-d9avfV)h81;DtRuL~Y7#3UvT z0F&u)*18{w=KDZK%!YB5hYg|CjabD;0{#^US1ybD(QRjMkH%XefV>8fBj{quB73X5 z8|p>mADsox==#=Eqc4joqp*6=RV{8Wu&uRGR*GQ8Atj04FZ+_gjML}LW~$yDqVk~$!_Ifu3Y0FFsNHB znKbwQSiKh}nBwYc9BG%2iNJw9r$iNwgsM#T|^HHAjjbfX1BhMTJuXfjem^ovQsrjUsYvsfdxKMV;kXFNiDzd87I zb2uZW=c6Gde(m#WbYbS?q|MOLyDj1cRgHgKYO@OaOssJ=Hi%PVAFgowhRH=1$>ep!?a=$)iFI?orVrI7 zJDol}!)cI!qV(uK`?JCPLhrF6B&+G{udc1WkmjY1y83#078cYFd8j*wAD7fJ<_dkk z89i|G)pVSx25dLEH#KC;qoiv!5kbab@7!{N=d<&si>Ir^x;Z?nj!?t1<&?w6w|{Sg z%Usb&1$g_JWc7cDI7JJ#8&05t#@jZlxwzAr>940;Gl7k)-h7M@kach#{wcD&8_0MW zLdN_KA_+MQ!;!^1%&={5Tj(`BYX+L5;Iw8*Z3${ zI=iLn_~q%ide!@SjM(>K>z|LV-|Owm!*(<_HuhvSpkPZ`BuY&)!b54B=U%r*sn~r> z^OZWSZ%@YrypH5z!N|E9)%tR&>_O*U&r!X-tSf&o*n(ToczbU2x!Af^LrJ9jFX$wy zXpt@$s5!_AOwH}X*FKRpTDWhT1pMu$gwnGfQ2o5-A9r+(#`+FyFyjqYGbN=6Y`1_d z839)8kn@D#P-(p4Zf*!EXV+pQN!xAk^3i7P;UNKn#v70AV$U#b_Gp<}d9RQ`jUfaQ zE|cMKT#ehV0Q7<*?OJRPYp{@P{O z#N;S1KUDW_MfF~C-TGQ194n(KZQa3K;8p2ax|rQPlQmMND$3~4njlk%F|VT!(diqU@t-e`f6&=2V!=KCf=% zC^4%*ZEYl`2lITC3&_ag@Y2>Ms@NjBT$yxGv6~(PLZm2w0 zn$?%=Sr^r>)zlHzHZsW9v~VRj@4P2Hp06}ntT95!ZXk!xa31G-dER)BI)@v|z>tBj zTi(oI+`KdX^R_s=+-O7TbIn`?pds_Iv;he`J?wNW64bTbZwS7fFMg*+PgZ-u96}}Y zW-BoAQLkS$d_T>9(*SuOf%8MB6sM{q&Lc32C)c`hkysO*p1ppUZW^J(*(a=s+>=z-h3mPM`I3b*-q z#!^iDVD$cWv@mML>`A zAmMFV7C1?f>q0H#y!gL0DG-K+GB6i5{WPtg*eKIdjsf%Cd+J8J9~|}}*}#`C+xLkc zz(@KQ*8ozC$J6)7W%&I9f|G<^y(NH_ki6Kg(5f#0P#n9_cW~d<<{*)S>EqSzDzNng z^Ir`TY1J5t7W~{?k_>jDc5<%iAMxO;FJ5|WX9bltT4ktC_f}o*WGu}HLH}VzELabU zg#t>hX?qSswT?$(y^Zu(a5#8VOT46@z;|(=&oXsI)aLz0a3Tvri0#}X2ELEf4qcDt z_<=NWRMLNcQ%3Jx^r7w74v~s2xK2+`w`>L=xnUjndiS7 zcd0+5FvD1TiwEcL5qwB`Ns~+;(j-17i*rW6`?9Sc=+KfMe6su$ry-%lDIOh=W8Ic> zWQ2vOiZWbjSf~8koU5mz65xk0L6{QU{MZ`}KlwkNA~`i9RrVIlu2;0Lty4;^0le+ z4o{q_bVXHFO`8J>$0Kx)B^pN_*#FjUXG4w z-M;#5?_L%yO`zQAfogICcK~15lNOKOzz7YRA`9U||588P(r&IK$QoVd?>Xx} z+>>r(LsCx*RxOAAtaS7w00V-Bv9X9)hu)XLz6*p~hwsYdus}`Lb0b)3c5sNwB20Gm z9SFzKLFGHb?{ryE5KAQV`;HMMhy?!F_0a1(DGEmqET+1l3{&in z^x?fBWWK-Yi!%aBnOaa+kp(tH=XIPrNPqRi4wLA~RDArMQ>Dnw_3B(om=eM$OfpB) z{I2$-x~PUQvXIB}Bw6WweeF7TEu^L6^vw9!)9o+I_IYbXP@tvrY`$o6?8^F}Ei^`? zfYgUmpaZ>%pU9g<-|Lji_vw)KwQ)fo>u$~6;D>tF$f=tb>D&GGu|wNgnvz;H1zbr6k=Y=>#@3e zwf4_X9ty9fFxZK_xBF*)HxH$)?JQ1jLBP z_Ua<(WyEB|@DYgi8GJ6uLw##TTz}HGurV_k{pOdHTjColBWB2II3Yhc(rz3#JJe_E9x%iafknm^U|!NIEhe%8ijGy) z)a#7;V6%MgmNY#xlJ1|>Q-|xket$y(GVMN z+7_~AGd9l!v5tR!O?ER@E`vJ|nY8u$Ru$Qm8j_G32=jT*iv4gw=-^Bd4G_S_w527c zXSCXCqVQzF>Gaia4Mq~w@0XQVJ#B|lMjdPbj+qowX--{ToP0X>p#iXKRE3acX4c*{ z&uy`^4-Y7LW9`uN^nLw`K<&`iyU#UWVHx)Q4n}f%cp5je+jP%~`OVH-ReY)7 z9Q%(v;>h7o);rtZt|x@wU-P4d{^)jjKlacy74!S2dIR0*XN-vx5l{-g@@JcL=zDS z2?N^y>gpS}!+HgiPE*Aj;47k3|1piZZYZ&+EM_ud~+TzknePuh8>jl*CNvYKH3Bc!9-0FZ{GH2^F6`*lGvWam&=f z-M(wGa|@QW56)KzuApH(&WCXvnZ1}`X~AXbqTsgVtT}rWQOo%jJ<@bW>$RDB=*m_6 z-JyNQ=kIm-5E4j=MhiJpa;n1OFEm)KhZW@BjI8T|w`Oi&3bEh=G=U4SV=n^jWQO$wqec~z z;PoiSu3EWzD&EZ39y2d~5OVKq`S^?D1v}c~~Z?$&YGU6JOiQbg}ukQb2J$(nNClPxrjRfx6 zz3;b141_i8PTnFj3czZ?UWd zLM_n`@j?ZE1QWHJZ%%f^vOwbk`0jC+?uT;u`UZAfsv1AYk{4juosma;J0w3eBbD9t z+-FN!__7wDYX~B*k$wByOkx=&#{nW1-_Q3rB{YGw`HBaFonA-*wSG%e!HHOfN-B^- zEt}L33K4=#&qiz08-zsp9?9G)&__#$9f_Cr&gkD`vOGjFII3N7&sMn!4 zMHmA4H-OG)OUnMlD?Vj!kX&cxhAKE?p@6&r#9(|HKuww6`w z3PP^LslsHna+K_&k+MbVun-K1KHt#_^Tdn9Oi_OYHVY|&aK%E6XaV+V6dIwY$t_)< zam$HD_b%PH;RPGy*l+Wku@scKem6}I_xZ?;dGln_UP@bpVUT>WLxwU}^= z6th{95}5s2q2_^&G_VMt({4S*=2bK zI{0|7*Hd9$Cmslh``WPL$R>=q9p$xGnS9*68OY4vLC^@?*!N!;o8cXW79`pFl% zZ`XNB%6={CXZNCY+ZQ~v@%3(W9>x=9()HSBT;Je1K_*4Z8PFn>M}q_V zW+HS8ASBE<^%H$}%7PM

G+=^K z=Y27tSqe^XI{G4xrczF1YFbc>JS|HN4Mo%@#xOVws_x>Pd z#B(PX)3052t2W&f{87Uey-T;2LT-UXz=Ks$@D@8?DjFA{n1{F)bg@ntUbgVcA1@;2 zwoLRLD=|v(u|T~AmgOe)(p}{(B^B`?k+1q-A9>vpn>s40aENqSE-o&VPV%Dbp&9?O zuC6Szk)%t&ZK(mmF#rKROc6rd3ovKleOs0%tJ%f{&Ty9Z`beOtR%$WUwhH__N69-k z&PJsQo)q!*PL#1&|Fo>R%cOep-h>gew!0rv_F%!S!I5LOG)agGG(3XVeCSP+@bMdW85 z0J8k?ZpC4##t2HGI3C~v*vv;$3@H{gfrx}B0F=b`o1R4%2)-G616(w*=T0o!&|;k# z(t?4X&#Zafezu>`KV(f%(3FXH5|fsSbrxz-Mrx-rq(_1X8lQ66J?`B{@r7DD?Vp=m zOs4@0cAW1Ap;R(TE)0?M?3m!JRvZ58Eo=D&XL*HR5@ z7re;JaIj}Hrb#(0!{#8+mjd>T$Smu<%m#WQ5x@AiYOWgPfnjiCW23;!Mc-cdZ_!V8 zizc2ATOobSuNV!!uTR#HqOz~o9kug=s=M%v1=+9mn zd_SZvD=+uF9Kaj?V_j3_6D|DK(mHaPEd8Bj@XBs~?VUH0g=H|&{oDizx*doNO1SRj z@3~1h?age_3nD$C1o@!Rvl7J{D{B&5Oi2;$_HN5z%m>vBsW1LIkMzWID5KI;T9{!n z7DK8DgGgr4E0e5;0*qzn{W?+NBg8*ky#oI!CjbtKoiWclt^sN}-9$3@Pw=k!=d_B4 ziHYULsR*Wznlr%)gh3Y?Fm3!bA}(HOvQB%l z=6VY{i)0SXLge8tgmGdrZA05(-$TpFws!w8H|=Fo3aoMEU$17+K;#&Ffr%lU=lebO zLw~#nm8nvzz6j!r_x+mts*}`qX3Ii_7FKQgh47Q5?I_u`qPo8y6Wo2a}fqs_5Pl1%klf|T%6;Dr-VrZ%DEHHLh0NRYS zK?Q-y4GOz^$-Bd#4`0=wgDoh6mj-^?09522?|AWsl5)}K@7Ek z#r%7El@J^2f8q}Kvg&2=w2EhvztxT)&!pQB$}{`lq5Nz8?`3?Wxl=6!rbw&O`v6aFU{=7y*nqY=Zp~ zYbV{q-6+Szs9xuHSET}*KfMk#^$^v7hc~0ZFMsvD6BY_}G$ha%T084|Xy%m9@vj3B zE`UJ-!U}i|rx_l9!<;hxdVe7B5~Et%*rWnh_w`RAY3wrr46_MRR+A0~!#LI_rA22O@rYxGcKAXG^~}T4Y@&4~+cw zhl;i=)cYx}t|aXy2ufYdDrP00F=cDA=C~xs7iKb4#6T5#Fl6fin+!$$wE6J*e2><) z1q`EgCrpNPxiEdu_0!heRDM7;53->xX6s>9NKQ)n_BV|73J67PUO)2QuR5m- z_?es2SY$ZC3co#2V$mwh;xcPvqx*Apy9iXva}T&JzGgm@LqO5B>aA3;m>l<=k>_D^`YWy=c&qvk(3}+P-n9zqsCo(eVhL^fJ$UH@VMLIl zrqL6$NisLSCO(gS#uG4vk`NL%d_ga65^})ba5t`Bdbk`SOXakRyW2~5AdGcC#BF&O z$kz}tNk~R;&$4Mjc(q=8xZF-CzV2J78provtSg|_)v&c%bxta&j{Ck=`N72&Eg)2(pMqJq+%xc5}i(js2eF+3p z-RJXgq*}-!+2qYBKjTbVW>yS42eh3JDROWVinIgbfiYwt`8d0RGx^#Co zXEOl&S574z?#Zm7?@3K58M!&H<6t&hqU;R_IhSwE74>9=wyT`}H@nDYOw8Io0Km;x zTbx#%hDfwc?yp<-v$g>?jooht#vX#yTGre)S|n%ltlE4pw4n|*M^z_mXCf z$t55oZU&~b4tvUOM@REd)ApetRjtP1Xb_|MufqXJ=eX%i$?NIfuFxQ#sq6OUjFlU1 zoRt;p88$rG3yS_J$qI6$Ga<#ztY+_*hB3$*h8C; z>nSNR6tePUEOWUZK50t|T@hIJd{{yTW~yFyJT#?MRZ(8fI8Xc4^E?TeXxDEEgqz!0NU{@9NS8V(V$ zM-pQ=QRlVy!{>lbdW9u>0SR+WMb6V4UOl{eM?t}9?XoPbfw_RFRgDG|NV2lIB1U<9 z=?G#>j?qIm#|CzrOVqjzYt0%hm}q1U=i#cI_7(OEj_*Qz(TDG=CCVU?ifYlaa!IE> zYSM(|1$cPL&y!DsAQ8Ou(zG;!i;=lcvVLF#H%?z>0^F2u_>n}YLGrvRswmhv72mc! z3AIppeX)soFx}J%2gI%QD8l4Hh#8a2M7ds7F|9?acYeuG$P|-EP9I^xeSxFrzeSR@ z9eU=OxC6Id&HBaN1=A>ns5CM?e;2~4L{t%yw}Qy&grE)RywxIlR|ConSL$FnaY~CI z-QO|fFU>4U@~oqdqZ9Y6*`z_tP;arUHCkT*fp$!Xy+)-RrAC90erd1ww)BbAl(1teRG6$OM zV`xM~z2}N6#2N1`Q|t#ZzU_RTE}!zBig`luBV~OOdv>3l|1D9|vg^y3vHa@MpHWGc zl`V@LZRl*CqqAj4Db(F`%O>tG608H2Hp;GEf=uFkNk6F|D=_IHRB13kki;LjJPG%Pklj`lVuK#lNdh{dxmk!U=syey0LRTxo))|ttrXRkv=vD~4Mxv`XpR_{sI_--Jy<`0Z;N7SFbWMs6?h+3*ke9M zbsVD};@JBA>e$*L@OTwsyI7aL9Zfu3xKARc9voPK4A+Tt&3813amP=pS7UXDMD640 z03*j=rNs?~f9}^u0ez;Lp~3E`Z#Sf0GdihD3wPa@6zGKIYT!F0Oj=usxqrbJe7Ph< z)oC1*V-cRxvnYYi3*A&yU_XEB3OH~Tf>!&<33;Z#N<<}b$JQC8hFdX8m5CsIC_9U9 z_W%WqFe}x3DoMb-vSp)2Nn|n?4t21Yu4PpyLu;#vQ42HGW7PlZ1W#tO*=}qV{m0_V zl;o`MVGn}7bsJSs*sHNT^?c`ce%3E%|hYCb@!dTCAtIbg`-G zSDO!1Q=>4!;0U-QV?mIc+$vm4YTjQkQw}n;ajz*DN{`4rWZ87{;5J$DTY4&4PjN}d z%{(45zB|{waI0o%6$%>f^V$CGpsCbtalNvR3`qa80yBjC&kEa_?-Cr%j6mw3O5-mq z6?qsHc?naLPSzFw=7k(dwV?ihgvhuVoYqwkd2LnORt9@LQKJETSIvn;HbC%2E7XjS zt^yQ*!Y1NDZ=9l7eM7G5N%eEHkq&T1@iFvK>`~jebG2WuFd64^&)V~i*VXa4cj3!* z_)LE;lvikabMooqzL*1nzCWATClXLYA#}|M8l7T; z=QS-IFbFWEEJ2o5TFR$TGRavU-%+hq1uYPtzw&7 zDjviE{ril^p>+@Ke=R9>y__8(^L&5Y)VVpB3IteeT>v?idClC(v_1sy_xHVjgWK1C zRLv?ng49p|i;f{tVX1a9&sIlKK(vHM2mlTtk$MSz$3r$YX67i7Y2#VPhUm6qNn8Zoel7iDx?NndvtfzjogLtSszBk%|KtCzY z2o3SUJIW37_DT>ApLGZOnc!Am@LH~5SlZlJ#GY_03%$yMuB@ZEC@BMhU?HpdD8A>( zV(k^co3G9kE8f2VQ8xw2J5}Ce$JD8@^J(1Ny%H}j(8FOdIjH6Mi~a})1a&cpntubn zTg_XtKW8q>aoc31h!)5a1}@I`;w_AbOc>DUY)ZQsjw2#i_xyTVoR&g#CUy-mTrcXT zl+qKMoks)mQ)6en@?V76rD7g|Zx8}4n$JEaR_NY9ZrNbhGohd?5S0ZmexqWxQ0BsM-lbCLlg#RzQf;-{NSVye+<%~)7o^zb zEXbJ^Ko1lynKIk3AQGUhe4?om@d|_Zc zKRF4Gia1+qC)(Vx^Smg?`SIx7{6YXSbP}1x!2YPBheB_?2X*}e=B@JdM>07N1qE!s ziL8kmNO>ma2*oQ@bze-iH~O|HgcD_WSImv8Z_l*8C#F|Snxp9Gn(M_*PcIX5(KHWL z`Sh3iuDwe%mSDJ6Hsi`ML=TX-kMltDV8|f*m3Xa!qz|r)u$03cc6wXO88H48zjo#u zIC~q?sDi^@<9LWcKqQuH%-Hz1Ijo$_2jWRZaPV9p#6QuuzM%NE$tbgOm)NGpxCT45 zMMh(uN1XQ`n4q4ozr1wSNa?4GN~YF?<>V`515n7du&Xi9bEx1!b6Juc4V+S;znE`P z&~Ev}XrNn*Qit^eKqevZATsX@h_>N)Rek+4&x70$WGID=V2YQft4U|f{Cmq0eX(t`jY?m*ZhD&$lVwi>&Kw{LrDZVkvLyXTdr z^HrC!E6Kuh_RYGMvaPKp8=+RJ*UScO=UQ{661fN-*{{;=n)T{g*nl|9M>hfI)BNS( za#~}g>(6eE5bLca#Wbv8DHoo1ETIQkg_^QjtQs&Y2Y!eEz3xrE$USs5lvLB7fj!`% zS;d-vh?gnt0i+?#-s`ZLC{SOhZFY9{;(YbgIAJdvUQE7|l3!#YJ0!G?ov~6Cj_C7+RCO!?GA9sZzPfz!v?SWF<%a1U}Dw8PM>c9Mp{!L&F>9T@p@SCpRI zS(f^Cja}&^3Dymwvk;-gr#;2>Rnl{i>8(8KLd;H$CA2Eod)+==#w&9X&_@(rM)EU+ zaI}@8xl4_^HKZ?9i$7h5Bmv|5VNRV(JMjx5-g~nNV)`j`!ptaFGgv7pKSf;~&sq6l zn#tozjK5ZOpW4}nkFVSIRn*Gv@0*nZx=#Tg3(V=b`A+y(vYs^WV&jBK{t5D# zL~S!>UI#t}c|%KCs5C49V$3we!27Sg&bz%NycsSI|sN^&@h-)U;#GN^hf5&B#8S{3H&EqUG89;p02;RJ6OoLQ_ilhFh?}uaCbuog~}dP0FtM%xNBJP z9|G-YI|NrQS9;Z*u#wgA%mf41!B-455N|SW2sOJr1+aPS zB-5$0Q8~WKS<<}APdg*#e0Lcpwfj#vpO_cHeaGy{pdZMZO| zb5}K)sv`(0rVc5_-7ZX6RdWU%+aYJU2HoZa-FeydzUP%V7~cUq7diYc?XVtP@)16` zQskn1F)!4;;H zk_aiYnT$7$BY{{~y6aO?g$=>hu8k;Mf=G=U@ZuVFJL7gIS#ijDp>}H%wa7M~8}t@# zmIoNP`4FjAwKpT!Ha`@>cwaf-k=Z{L&VI{Ft!8=YiOhmGINE8BtG z&$oZlL%V$Q$yGX|N9A#5@4hwJE!FH*7?jKTh)Pc4r!@LT2a`f~+4YcQ4w7S;-3x$1atD?LTYSEki=S>* zjcYB;lesD-iF%aCmYE;C`rV)H_fN{LRYI~4~La#lLWIRAbH z5$Snx&iI4uwQ#4XpHDHaH3{v&HEGK(R7~O!j5Ej3EC81SgKklJ|94T1C<$w`7>>bw zw6!T;nw}W~R0_q~nd*Hh12Q+sV+kcWmZs{~&wUJNZw`bu6!NoqB2Ym7Yu7fnJ=U~x z(r(jdd?67XVCT-v-7O|L+>l$OrDV%qCNEhZ8fL{`MD+Mxw-Tbe-=}gasnlReH2eOK zkZh$IlpCNypHwvI+sNnPEgvUy?A&N`+^#J&xUOtRz@*Z=7T|4P=q~#KUXy^}pG@gv znWsJRW<%CJf?WEG;x?j|Hu*k^8IS^v zkdxXTesB#qHHJmmdA{15viYWa8~(}C3QS;BU9qVOTu;Mq=8E-DuK}3gZmJX(#Flyz z;QDP3WAhWPbsmd}knmRdkrO&QY1Wokbc*!!_b3^C(twl+$68Nvk>WB}hiZNCJ>uF0 zjjk090tLZokIOLT+B&+8zsKje8gr}qPw+UL>V8$0^F%$;;`qy$;_pS4>NY9{^{jKa zN_qW{jBcq<0WM|FyLsk6mWuB|(!(Ku*^)^@(THYBxNwd-K47<$W!`$H*g^R1Fo85_ z7qv-(mmXS#bln&s4No3B=If(K3_@RqclFZNS*w%qMK8uce~5`o-3AAVRO4n9M>(3T zY2bIg%qyi_)|7q`p&kpsW|+FIBwMTlzlmt%ph-gN;JtrpdZZ?E)*V5ACu@`FPqyMv zg_9O()KRj_+yq}V&cl*kDY-)&z zaoSEq!MGLc>i`v^%*lvRW~|A0QxxF$p$@hl=)`6?xS7A9D=msGl(#rOYL`tG9fVJQ z!Ej+uCEV1BXb2}d3-wn+{ICKZbkSc2VJZJIU{r%d+_ z+Nh{ks4uV_O(J}?IFDToc^ye=st6*T`5Zq<)R$qopd|L}^$^M0VOb|liY(h9fGQ9w z$xxK1(rTc>ra(>r0~W|a)gh>sE(_U4ms@BCOV)^Ao{>@%Bnwja+VQbG`6z^q2Mtt^ zZq|NV8fR^!Y;knAlW+;LwFO+?ogI}QmPo9zwW-V#espPSvQrh$Y-#PJZ~{LtVCkO1kp`yQq^oe; zD!_m$kwQq)TSLsahMrIa)>e)`%#Paje+s-T{G*Z(K$?4{Z=NZTLkbU>HkOsqy5q+6 zM11fGsE>6WA@tVs%GY5EJ^Q{R=m%Yn4^g7!$yN^AC?bq1{tTmT)aVDtA6=UoCN0RE zR%nb3enbbyrN(VI7C{LCgVRCu#%_VHK?s-JOOiQ4%q*D?mekV;vJuRUoErnyKOHlO zL=i|Pkp*A>qB}Ws`()hPh+Rc9Yt%A&uL5EfG2|Gr9yEH0@{%CXxc?}w_~W;ps7IU( zC(Z{Yot_N)3La=Mak<&T{PrZ5mJ$wAdsA>3)ZwSR1(JDh@#e)QiqMJF@xz~DqZ(|G zmJRTM8jBWbb5Z7s@8t(&naGkqK`VoaY&##VBH}jef~{g_F-fV5O&WeySCx-iNcaMXwm#bjCAjgX1OssqT!eR(mMX5#BTe*Zdc-#ADP}bUq7O9ct&Ov zVM#9tl>rBzr$gc6j^e79AK1j)aXA!CvIP3lJ1}m>1!=;uLftXO*1W^E`5q9Nk`%_G zgK=CQrUH8c`%f{tbVdY>2MTXxY@ZO+xEl`MDV4-n5s>*k!hK}(pSb{MG^^-q34+ER zz>vJsKGj&)(iuayO5?jSPeW`~Fyje6{iKnHCvJ9VD@oe5kSQnOc99lQAdt`Vo>S<|ld0QfJ16LGEsa>r-TT!YfmiuryDVMonVa4p8JpHI|pu|5MX7 zhS&9c-5aw>8#`&^q_OR!v28TA&BnGG+g5`cG`6kAw)LLh|9Rf?>3+EP%-oqhd-m+T z)*2m#^6UY;MJith%*#%mAUjN28pwj53_AqLQEu-tA&p#L4;-!5)3mu`;B=zfttmA- z);3&lm#_br=v=FJGfhZp`2f@^mR0vCMj3=Y>8k+!q#15ak?4D)cb%xhEWIqN{cq*A z)`tlS^2{AG+*rOf#N%*mosZp#6E#{xS1yHxjN}DL1zDTM*dIUkgS#MP9ONv0TvWa` zttn%`fb`%dWY)t6B&Qon)o(73*sYEDQ0m4|d2NK1vl1Jzl|XU%qAVXKD{Y$n8@`cD zQ3)tuU9#~HZZ%|C6FD(|SBN0sYicl>;bjN$-_UQ6x^2pM;#C|WgZ#4vA->8BeveT7 zS57M)E&9JVO*7#TMPj(1{Aq218uHrF)zo0@3HbuCfYkT7)VOi(-No@p>0-k^TJ`sL z<6nCy{iR!pAzv69VMx7QIupsq+0fqT`jxXHLR9InLb)j|=;*n>or=jYKu{X}3MZ1i z?M=k&9_%Jfluq@Xmc#{rCLP`v#2E!#&6)>2)WM z1VTchfbZ64)Y3bfjmqgldfnWeDazzQ*x?D_c{9>?N>hQ^fUb6_H?blGF`|%iGl^wI zRy)eg5WOj{fUvM+4xzsHUq-SU__ouR%BhmbMn*VMLX2W#$>1y?qhbq;79mJ9s=Oi9$k}H& z+GXoO3v<&8(1D-h<_yqzf_!#>_t>58_?81XwN6^U@TKyng9e;uZHu9$f4nH-`8lxA zbmxs6!inL>S>qI74l!H^W&)PO4Z7|NjTv9(BN@FP+s2=+ypo*QH)nHD-7}h0W;?VH zz9jTrqSU`cb{Dd9uTM~QqgR;;+Ce!gi}#?2Uhq&_=)0(a>>=e13Xf12{ichgu>pkN z1VE2Y7x3c;ur!`Q#BSpgJxB001%8C!EA02d5sIk%4A7sPi#_`X193Rv`xSO>b&X8h z12UUWmyZaKEEPTVBaChH}VzfijUQ+^6ufGxk04DbW}>k zMMVy0O^c4tMxk>}!25{p%Aj8$kM2<0SLYMnIZ-0JXI@TqNBx2=f2goo92&Tg<6>?HP1~ z?{Y;1X&NVmdtuJH$|c#(tQgd^*GCwoD8=1+1HN0(9sxN2KO@OI6b}H13l6Kff=s55{lR6ae{FLU^jAf{@gCY52P|i znW-B+F7JFr6@Trq0mf@V6x5yCy#yVZS%ecHZ_2$ooUmvl^)0eL+*d>yjIrqgp8=(_ z|GUs4>l0{($uj*6|Iq;8X+;t7aUb`PlamuTjWIcVdIefn(9uEmUp?CgU~m5bzypde z*ngTpq-D#irf?^ro9?8QjIgCpnf7>2+SAEW+ph0&THvI`a4lAmr-r-{jnmNaXr_t+ z^f<>LM1}@p7c<;-%KDzZSjt_mAv1V6r6W0lKBcFEw082la6SGoV0GlvV_N!?z}xL? z8lX9Ga&<9Xj%TFZzCPiys2h5CWxsRQ0(FV%y9EWLrUlX_$`LhG?LC8G3I4^qSkiI3 z)XQZRD$^ac{w;Mn3ZJGpvCLOVlwE{I?D!^^=g!cIiv^ z3*befvUUEjD#+7JkCQ=zqe&AoSRr5D#!vxo{}H{N#R*klDwwj__2m!|W4s&F<3{K2 zqKM$tCRFmJ-e>xc9HOf>OK!U@CpYv1M1qoMa$Y(|F3_Fgz^BGYmK*{5>LHIWKeO3b z$Lj1~CW|E6Q0Wb1t=`_w5I~_IWhlFB-)D<~XsZqzPeVh)wIEaiob0}Dqs;2-?xgyi zH$;)@-lL`%LP&7MTOX0hYw!eEMD;kn@{WKb@ z-&>LeV}Zq@tNObm?C&7tD+Gn^Q0{2fcMs-%SU)`}SAuR()b$!j$DtonmRZ1m+;pdT z)wTfOltcsS)P1NDKYjh*P`DmHR(UQSIm@kL{VuHI)hhm2rg&Yj53moY7%R(!*SQx8 z3Wp&;_6C6h{7GQozxorQLP8ULg(pxJh6^GTG$4S2weDVO-Pzb}u79p>v^jq~1Q zKDp1ym3dm>5OVn~&(D zF#c=H-bg;=9M=C@DYLF)E=5t#l7(Ee#!R8Z1|)?03b6jdEgu$V0nE;zRZZsr;8Om> zd-CVR0*VJL7Bggyj@%RSxLo`uX&=8}Pg?^A1o;Sy)7v#iBY*t~{%K-je>2W;6GZ&# z5AY=t0SZOUx|gb&+Vyw_TcvhO%+t*Q+Cuh3+3bGutq>Sv@#Y|m(BmAc3&d@0& zClO~K1B{$lMPLQU(xc2KN1xBTw6N0CDgiTA7Qw)1t1nk5=nvr5=SKhvO55x8XxqOC z+B7aFQx!ncqE4fAZ;=B!_F-lv?znsOtP;Wa{Xb+Lpnc#3fEg1L5@x>MKving1^(w3 z0piEi2yM+JP)cI-xZd5`tl8DZn)xHrLerbZ?+bjUT>%K5nk38CnZ{=Y$xsvgopd~yB z5XlBeLC;coMA|0y#qHjl6nDHE3TSdQ;ndx_3 zyfi^f%_*svKRA?ffQ5;91(eH}+%LBb?3Ji9aphpmrbA&9BN%Q`I=T@*4n*7LjeK(8 zEaD3jY*eX7t`cnS;tj718Gm^5_r${%*sY&qw5-xXo)3eQQdc(Us4Mh{AvC_5lTSYv z1jm;gTjQy*=5!*_&3RJR))ZDgPbq>lx$O}$6kVybu(L6{rOAKJ!zF^IB7YE@t`$Zi zX%6udkv6usVE&%NoiF++1Nkd35g8V$WwW}e0Tr5ZUNee5YXe-rq^Fo@fIwnO4hH@@ z`cys)#E_&qm#sbelV*G;iKbdj9@U_YW<9%zjVn?=7|V{1p=o`u1zQG+;%R=Ump-Zl zK?AiCnjbPHB}sKr;;KCdGWPKd)AO0h-p-@!jA&~+q26+`uA3M^8qU_z^4Jw*|MGMU zl1=)2{CPvqex}y2uN8n5a(7Gu6y!8ULt&F7HoUg00sJdKSdM_n;jQi;J|tIP??f#P{}a-h}fS?r~c8HD`pzi_%s zw`C9XViTCi9AHqDzA<)D0sTkqzzKMQN`mDDd8_DIHjqQ)`jiW)3mO4r$MtJ}fJNLh z>GRrSZ+GbWPRjuP4UoaUiki4^eoka`+#O=SP*hM5)YQZU9-HjMjEs?-_uG=KD|AQH z7rqz}HzCCSpdzdMuTLatl#Cs*+Dv%)Ucd4QIAF=GdGo6RGNP2Ul#9m36^?RFj0Lk( z13dJe51xm{73$K8-nHVp&%L*P8b|=0b^|*7eSMP{WQ)2Xzjcyx!pG`RJIY@;<+W7$ z3pY*G|Bv*Mi5h`7+^%-2DL+8yC(L1au1fO`nIW_Dzc~V0|`1lWGf`?x6nr z2;lZg<1n~1=U(f;VJg6A>n?tnQ<)YNl1TTbY?ITDhqBE}L`WJjm)dMQ$9b1`?_jdB z*nV)mv(<2O^N(yM#wC(b$nQ zKnaV5j*XnYM(iRpLC4|sROzK$Gpe&6rE7tXC3du>IvjW)mL}cudbEP^R9$kYHM_@Y zN>d#`b#&ZF@(j5{7}Ql2JFP2mE>HUU&dHj z@74x{ff*R?Blyj|AX!e`xKp!fTs$$|W%~Q)osmKy*IVEOThZG)sJr)dSs*Q)-~OBn zmJVq?dUrx#Qv`T)h%J}ve~x8xFt~fu8V_}ciT<0yUGfsPSHcIyQ3V;8M%6r!Xss~u zW2$+Z^_SeACIpIc*-m873EGAnt7CT?95$khlR@ON-Izh{!G295{u!cUZrAZdQB+jK zN#H5+ht7 z)|DrNj$NS-dAXY?|Ie|l71-aYX=oyrKLLPhWBT^f`rKcNGW1|$f?{_2>asF~$o`pi z&}Ye`)2h5~5H<{UD#Q$(4ND@8;f3LFvy?`=?)9*i#)_~AK@!}7d}!hTLdb0ZQxJ49 zXQftw5Hran=6oCegGQn4;-^XYeeNogbI*5aMaOku_gR3 z#022;0|tlBrgKY6L;uOvV5;kUc|9kn_ed%;F_>}42$&t-LiZc)^znLN&d&nnxX1Hz zA}kSFBpyXamH`_*o0g!x1XA{noYnw zPcIBv1une+97XJBjqg|)K87=^CBHH%?xoNiApK9KXdn`c5%2zz7Bg1s$0>bh#mO4og;`(q$P;!r8uD5i%V+WZIgi-Vg0eEz7-x` zsNpCsYE6~)jAx$i?Yo{*8cW3N{#KS3ap9a_@p(x;;D2cycZwbCCB~UVMqHVDf}n9= zPKga1^twMa1Ux)K<|W6bw{qv>zep&kwe!>@6C@Bkr1|foo$pv#U!eBE@a`=3ygxNq zL|%R!u)LWy6+TwmC-#Xf!tZB)8=8zc=byi;eMB0r$$r$4OENkbb+t_qb#X6Mtcz{b+Cb5> zeglmj;%f7Bw#3l3Cy8sy=>0;}gPXVl-iYUJJ)=%uObzXNnTNUT!wvi@7Puy(CH7Sc zK`s>*`omlP`nbfuRsH-DnXl_WJVe^8%lT9LaFd&s}} zv5kz#6(p=eW~*}AdU+K1Z-yy8xJ>tp0A7X^z4}b5*^+$0V&B=K?&RyDz7wB4ui$-1wVwAnwO_Oa&=iKMV~9E}TXst1KMmGx~;jAAky#{trm zD1IF}c^i4axNX_@eb6PnPO=52ppdKfCfZeezci!OVMjX8E)lKrgdVaEM3O^8K7r%l zrO+%xsABO?_2)wHw&T-+Jgm{zfL%@&LQrC2^k;=lBzjGikP_Yhi19o(p}Tnue6lWq zkcTU!Y)x0d+QKJRv0s(t=%?efII6H4x|!hDX2`dOUOBl*DGel%h;#=Fo%lux1x&y7 zxqZ-ikw0{N=Jvf*4-EXh^ogH`(D&o!b4W56b<^6WbE|9Rd)sPGjoYzC>p{c>3piUG z6@%BK!N90gV-7~pK?!DxiY>nW)RsVI$C&6Rhn-@-to5$#Lenagphy`jR%m(3&4XFa z-r}O(XaE$P5qH;5>D24K96cJ|cY?Y2-kC79w0yos$t3*RQ6C5(bW1;!@{c|~pqMAH zz4LR?JS2R*54C>{TdE1^@qtFwNB?s^V`oA;{jqT%yvb+ZM8a`$c)?Ryv-Mulmwiz4 zm$SaU1yWG>Z?38LY5%bFpMOL>{gUMJwZW6MPX5i(@mb;!HH_r$ydO^oZI`b|kH-}? zy%{mC!Fc%i=^t|fX&(FObB_%YvFgliq-HD3-{3x+;Rt1o<&2919U}L$bFTgxGug!X=AMGMeD;G5vSWA%NiunOFiSF3NOw?g9znG@nOmufGB1dbD)mwmsPU1) zr@SPJ#%Wum2$K;t707vlO7epO& zR95#8n^y)N+$4+bST~*C-Ea}=vC&>YO5?Ckb&NdYHHtp9&8%qc8l2U zO@uLq6Zv>;*0ujqBv|%z^FWYby$na}OXsoEaOrgXx{wStUpooL<2VnB2P;r#qm;;_ zMG=9-+TwCZhYm&gHB_^(#5AswcR#TD#q+s~LAgtM4km{0rv}X`-)DO8FCBBh786#J z$;{qA+*40Jxb5&7%w+yf?+&E=>^DcYseNioPttM4vRF{52EV{y)dn%g#JcAYjOh$B znkp`t+Rqe=z%AVxzJ&Cq^hhefG(fwV(~G--Kwa5?41hIC8gLY_vn^H~X1BB^r!nwS zvGu0P9Oi-!*TY3=ZYgYtqM;=0pIaV4Mi_l0@R*^N_qXbl!M7onI`B8<5c!nx+1$4M zH7AZjt_O7#>{$+IP48?Y)QUW(hSFT#JP0_bcfM{w`se7pXQ8wR8C?+(BDyOE1@m4z zk}lTP78e=GTD2q3Mqb5g!(td| z8`r5rbsN6A{NrP)Wi~PV_q|?2m~iuKX)-)f3n+QH``~<%%Dj71&AO)i;cc&!K~ow@ z1e(i!e19YK^TYBE-~z=0E>dcA%lxBN~F5vqfqZcT)F=B$q353uIA2q0^B3lm&8G`||^aTV;b-caFBcU?nl-B4MaeI#}$pHsfey1a9 zSl-*O1A|BNBWkGm%@D!w7hGxM18QU7-LquS+7QWiUHir3pu|7I`}Vq}@@_av#sFU* zLN~)rKeI$uNPv=$4B_L1wDrbus8LvpMh1^Qjg`RHp}Kn+S=A+>uW4#)?)Kr>Q+5$f z7GrX9q1T~dwkHL`Lld&I_TVm>nCAurA`buWj)0za?mA!p>bV_{*{!?1%Ofot&Ye*6 zT!(23$Q;z;EQN!(Id;o)5s3yTkC~^weDV#u@1x`cF}AY8H%LhQ2Uxt_1%QXeUh#KD;r+ zYCjAvN-w_fC_cfakher0aN`Rum$C3vLS#a zEl0#qTlm*ikcffz+0#6F{SHYeLXMuxLgxn>wf=W5hbWSHf=n;<`JO6ysV}UmJ^25* zQ%rb_%J_Z8zj7JlJ!AUmy^xLdD{9b~k=QqYR4wWi;AP{0ZR{f^#_N)gfIOVrcIFv@y zXo?~JSfMH3g6Xh->J${r=j7=4xIF1QFcqMcGZM>{+&{K^fSeb1Zlf~&O<@A@Y@dO$ zeo?0porQ(bR7}Vw{SG_ak!Ab6LKs=|x^{QR&bS3{;Ve$)UhvQ}R*&H@vjpa-wNvX% z=xgpSBzan|_I0hv(QyHO&}@;yeMA79UOWU$3szMoKy#cjw=(!5ojZ)9y=!;-V1kov z(KnUPTsXLsS3G=_+91nUY|!53qUG#GO&uNu6}BLS9_7R^b}hF4_HbGjIBFUk!|>Kn z_)pqn?u&<&+fXex6!}5#??jkTt8G6$C9Vthke*ksGiG7&vQxlI~nM)Y)Q`$8;`~^%p!sgDJbN=QzG?j0If)Nr9v$0?jm_qr2~iHBDYE>WFu6Tc!;#xfv#*(IHW4#4A#=7Z zvxkmM@Wv(O(B#lIO^UbuS!ReOoDuRV&)$P-0PCs(TW4LTNJeu>XS~Cto{k3}}41zkx zxA9K~8R*a)u)q02_Llw?9PN5I) zaaT}Atj`I*MxEsK!oe3DFO=7NN<_eUzUU{t+8FM7)vU?q;CyE&y~Ef|ky z@2F*UwoN8=G%?B*=q@rtY$hBL{p9(9wlG-dH3d!_vje3- zmcXU?DRstwS3ebUgmTdtaxDLLITDThkDkKd(2x%w-0WcvpVz$yhzCt`(ciw+waf~g0 zL=sQHM|gASyFj21A`2@*QxXaArV%rHE9CWqNAcH*=(MMD1;O5jsSKQL(PiqYLRquj z_dygWE$0qbI{2}NK(bvGG6(7c^5RxhFbo&;eJqC$O*d~8GFDhX!uv$;w!b&{_CWY~ zM_f$E;IuO7k4OoN_(7l$g`aLs} zz+Ao%Hp5eh6+KU+ua9-dLk=5#x8w9MtCsSrYLC4K2FhF-mxj%*VAU79gK;9$#y_Yc zQ)s0GKskfMzaALE=s}GCIz%@$qN6Q1>O-uVvy{)VuV)Y$KYj9)9||Ejm6acsop{Rb zT8p*+@&c!iyLxDS&rL8s0GIR35o5}bI+i8Wu-M(}$MAD{rYRst15^$EF(+Ez^Qh9Z zt%cr>l37;CF1|;^ic6l36`ud293T0tiKXRvJ~$^ibwv+S3P?3S5Tk=YV=xm4;qT%y z$4qtTgNZB3g}Mj?60AeGD(Fh%d~hIBLWb6V*3<`nOTS%Dd}^S<;P+H)w%5Iyk1@t{ znKieIoQ{VLbyJmJaeatC?>22Q%9JI-YxV4jatsc7RM^!s96Y|&Xp2E)s*($gN~g?A z6!%N~=@0!XTphVcY2S)G$McDxl)VnT;!nBz!3Ii&a00?}Fg0~W_GSfyf#JI~y1o9^ z(mo~zcQTomL@t(#;)?X6q>0z1xsoySEsvi3S83pGJyAa)CGV;Aad+5 z8L`imLprKmNTxg#4+3xNTdnaCeMhhzhAc5(ZZ9?~({~jrqkykf7-$ zP@o|o$58F&G~loja=#e*?k4Q%>A4<5$WxE?T|>~)vizi1c`Z2L%5EibV8CZPFjg^u z32F_Q+S*q2AFpY9)i>OQl5n7Mr*B(lRD*im?JNL4_QSdTs$j3z>8|~w8>R9+v)V5lGYWx3KCfQQip8jdkQN1dK*cTnF&onJ)Z--L$iQ1b&-3Nul~v^fF1$J&lL z(-T>Ce|$({$BsZ}`PFtXhJuw!&}wE)w978@4_A{%#)`nNpJ0=Wp(%B?zZJIdQA`@e zm&9=KS$u+q=mu0i2G;enDbv{TnonUG!lO%MG18Zhbat<)ygT@_xU+m{2Fo3L;VGvJ z*#|Rz`AdorrbSy=FX2NMhWma_(^OK+ii7W??|T9YECD9+3lKhkE+m@jJp(8Npu1nAL0(2rGm=!oRs zWD)ukrunRFDL9G;V)er?a>PwjkKhct^;G7eo^O6I#F>FjH!8>uWpJ?E$SZgy5=63e zP?A^nux#74Vp+8C1@GZ8z*Y`t8D~0pk&rdt4t)nUWce2Z==|^qWUsd+(j}2s@c6m& z*!-@EPW;&!JHqX|P@-Zz)B31y!^nPAvm0cM?I|0zt~M*3HIa6~qhx+_u{ni@{1EKt z_IoXa_zl1Z{rUVHL%3x+1~QAiF^xL9D9jlz$yw$ZmA0Y0{Qy)Hy&Noso}WW|t?;lBw(&KjFLyzceK03T!c zF@PSZSMI?5!R47+CLN@PmLc5!Oih8S@M*kz6mYYxYISGjUoJUGC~JL8#0+s4@ZVMv zJ8pfT|ItAlesZEdTN^Eh@)s9bR48M5%>#<|iP>`mCM}z`in(PFuro^Dov_g2w>Czi zo5e%|at(@mg^F@J^>+(`R-Ji*xR;w}Z`FV?!caUej&T5>14ZdrT~&y{y}ZiuZk&Rm z6>E3~61)qx;ziLFp{1`eE6MQIsJcb2*dHBL)p4#tH%+RP1UGSHMuXLuYMJ|-JybZh=0=7BkTt!rv> z5ZnF*IlK(fK8~3}VCQKxAn0ndtc7QH4)u<5Xbd+1QIndwf_w$-Z@?^OnIu!rf!5p< zv~Yq$-iPgH)j%oL^p~Ws;>lSJvhEd$|;CJ!2l6n92J zFK`juHV;}YcTv>fLV)M|Vnfsj%it66MW0gH$g0<+@F$;jXORme$UFD$Uxmf#Z;aYI z|K`m0PA!M%d#X4u2J*Q9rk27Di`|=X+>WMinZdO6kB-vZE_`IEMRwH{werpKHL&kR zz}(%ke8@N>xN{xR2yo_QL$n!|`#JDJbQ8dA{)+Dsb8q-&LCwh-t+dIPx(2S}?cg)mjPSv5OF=1#n$mvvachDn80$ zhUT>mcd`VsyN{OCrEPmWxz+5ldh!gZ;8yEb*|I08v%R8uRemkw)Wy``yVC#gobTZ4i1#mNk#`jb zm9mB6vRmEC%t4TktlFOaZ39%FPn+=zV&LqL*ZxNMvpT)tDHK}Jz$YZGqm2|xPpJ-2E_b7oc-i6) zIs+=f)miV>SGA8fHDWktxeo~0@adOZrSJkmQh)V$!?xF~ItU^ZxIg6m_lS0=Q2rCQ zGG3qj{FM^56;$ma&_Kc$v(`z33m8+_gch!YzN8vWbabVrIG^lC4k_etXEDCJQILDL z^$T}4yv+ZX;QuXD;C})Mw*%YSm&PyrZFb8YqC0O3=@^;=+3^?a5rtTN@BVfJFURK5 zXMsLSDj9{=GQAOVHIq!-2svYOY;|}yBv-O`_283_8fPPS7X&S1MW;0IFV$M%48+ubY^S`J1PEvR)=B#Q89$ePRwlGiSaNCg${c}=qOy!JAU2OF{t+IA4XQ-Kvp}x; zPhssq_a=hANthI z>dq7>Y>Ez`tgK77*JfmI8f$?mrXbd%zwX8u2%O)Lvy5=e{xRFHj2*GNP zP-AOTZZ3zG6)M4_dbV2q;A<^7=WrP!QM!+s%N!v!%`&etl8)60vFkN3o08kUhHqAJ zt-(+@VEngW6SV`!-eet)i?OHGUBN>SQn0Qu7d!zKhEJ4bZB}9+91#f>YyWE7L6a57 z9ALu*-Eh_YoBwE?YRZV28K74x>okoi#E1N0NkoH#a}zy29CD!10ZO=|!3CVYZ(I4R(IbcakxM|C zoMChpWhsP^C?XXabSZvGPl4Hz_mFZv>`G0bzNtlr5GT}&6UubV9U`Hmdfa!gV;l4J zdJvkIs0zbiW?W1J!)d8fxq(^9xS@JY?~59GuDsmKBX^^`)0DxHYSWK_^V|>$sO0&t zWlqi?`|Qd2@P-R)fFobL#Ew)67-4NvXE?S_?G2wd73cYMdquVDiTUh~AMm2hdmj zcj%&kD|8D7q7lo7pGPOGIG7f(6m*Z~n3-VMzsSV3A%H?QKXj$ zIshYi>X0}{4yF+lBVM5yxr+(tV5gLG>wDxmYRdfqx>U6vZxlF z?Oj%UI4*GN&5c-&7lce>zP~#y`8$|L-^fdh?eeADAzAS! z`0fP(vfO_>U9a=vobfVKkI{KlaS8Hww`_p1S7&eYTRa1Y#^8_4hjfdmxV-~q7%SIb zj)~XIDl^LMZhW7HkiyqOkC6@U!+(XDK|b&Op&C2qB*|B#3~1{#vRQ-ZmiLo5__CC+ zUqCPRwgJ%{gKVe4jBYPd*ZFTqQHNO(Mkt2n{0{)2l-=6vz5*6qc?sCc+)3Xp=+Fy2qR!&PDXm9pC^w62d10NxPrpo)H#b1TQ{2C>C3x^85D23?-C zfG;oHe;9~_#1>yD?!*RJ(0KI;UGxLXhE~F3xj@agz#Hm_DJ}3M018wtTDfMVI*--m zm#E0>p%IpsMc;$Hsj2a*N)g#LvO61XVK^oLRHKDb+E+KLK5PBW)e}1kCnKK=4V|+4 zkpwMR*J(to)dR`lFa4uy_#p4f8hcPnLWJB zRwe1KT{{)`F!ki$ukCTVoq6r)p)Mi{6o=b1w@UfevXi`MyG%Z*(Z6ME2v8sac<;ak zDixS2*A1c3x+=saI+~N&&gZQA&x|cgdS4@xeGVWqTGl{WEtEZhN;Kgmv;@st`XO}Nk5nE-!&v(NCiH*5Rd;eFFgE$Q9 zD~`07v)OlgB_%aFAf8^#PcF!SuXT(RD^4pkryemY_TVxUB`t@}*=(_893tw!HDnM@ z1#ihIR7XIosBYaO{vL-VpdVLLI$%|pEuC7b6s#`$hrkpk02lR0{LKh4pV5qlSF?Etv+ql#LsI)3U8ZbSDP?kD1MPh zPThYs%Ytr@f@wIjnvS?+URC@uN^zT&ar;NUI2O!OuEj5wsOfX3SgrTu_L6{cnpIw; z_kTlJ1As-O=55fr+XPKPn?6XqcqerLB97r9sM|@37H3u6cRt}BA&j}jpe*CzJt<)V|$lYCJe{$GDGnQ(afHqeRL4H&i@7p z1!>k(jvw$^D=BLo?xMM)wE~IrFAtTS-21=bUeW!`vT>%lw@$xf5k@Sw0>-jzu3LEh zW-Kps!)=m_%QgE(6OBMeQWpEcvn{abuhzsFtnk;!t{T1i*@p9z`Oz(X>ccR==k5!+JN{B9X_ z&xwJXB#*Tmg8gdaCw z{Z&-siV>Am&c^ZHbiKWWD>g5b8oRs$7IfxKhaWRyh+lHWY{E_80>B`7z{+&OeH8&z z67p+l43`c z;^`(JKHeHxHlnZ$-Dkt9!1~+*G1f#IVJs@%@54M`i*&01m@UZH5r!|$7?WVks+7%H z&F|&%^e<%O(4dUu2`GP>UaXr%AVu8YZHKi#Nd!A4YL&=JSS4D2*n3y-4Y+6VX4laZ z@}>n8IO#umoaR*J$4`;V77IV7pO|x%3RO|>IUJKyxPc1Fgd*+`rj1@t*Yacb=0G}E z173P&jx}{1{L~PvUxUA=|0pKt2W~XDhYG@`<1~xaw`)hum#?=|{M|SSq&=wDzdlPq zKu4R?w~!C-{VueH1GcsP6yVpof)S#l@v&GS-i*Jw9Dh%3c8Ji%EuW)5^xGR5{apQ= zJLhy@mkkMfFFA>s-~4x^=+nsvr7>!{_eqo&G73_8GyAqnakGT3sE)#>elE5Z*pn4C zqCAaB(x;MV6f6_yJRBqOWJIBbN&>+# zc32y#Lb9G`*tR>~bbpb$tAb54KLLpS;V+Iq8F?9{Gzi!?7C-`j^=TC#lTDM^()HAK z-5;4(`_v-kCtvlpQr{hSm?+Ec8liGmsI*-mQL-rw{8}5YB^}GifN{`;3UCWx3D70{ zt%a(iV_lEjU+b~wPAG?Fx#`!BcUJAX;E0$ z75P7xJ0W;gtZSAs{T;>xZy2d^n_h|53ggZdFR2oO%4kCScE0QbOUO4Jc!LzA;At8o zOchqv168J(^W8fbhA8Ua+

. + if gccgoRE.MatchString(functionPath) { + functionPath = gccgoRE.Split(functionPath, -1)[0] + } + parts := strings.Split(functionPath, ".") + functionName := parts[len(parts)-1] + return m.MethodCalled(functionName, arguments...) +} + +// MethodCalled tells the mock object that the given method has been called, and gets +// an array of arguments to return. Panics if the call is unexpected (i.e. not preceded +// by appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { + m.mutex.Lock() + // TODO: could combine expected and closes in single loop + found, call := m.findExpectedCall(methodName, arguments...) + + if found < 0 { + // expected call found, but it has already been called with repeatable times + if call != nil { + m.mutex.Unlock() + m.fail("\nassert: mock: The method has been called over %d times.\n\tEither do one more Mock.On(%#v).Return(...), or remove extra call.\n\tThis call was unexpected:\n\t\t%s\n\tat: %s", call.totalCalls, methodName, callString(methodName, arguments, true), assert.CallerInfo()) + } + // we have to fail here - because we don't know what to do + // as the return arguments. This is because: + // + // a) this is a totally unexpected call to this method, + // b) the arguments are not what was expected, or + // c) the developer has forgotten to add an accompanying On...Return pair. + closestCall, mismatch := m.findClosestCall(methodName, arguments...) + m.mutex.Unlock() + + if closestCall != nil { + m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s\nat: %s\n", + callString(methodName, arguments, true), + callString(methodName, closestCall.Arguments, true), + diffArguments(closestCall.Arguments, arguments), + strings.TrimSpace(mismatch), + assert.CallerInfo(), + ) + } else { + m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(%#v).Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo()) + } + } + + for _, requirement := range call.requires { + if satisfied, _ := requirement.Parent.checkExpectation(requirement); !satisfied { + m.mutex.Unlock() + m.fail("mock: Unexpected Method Call\n-----------------------------\n\n%s\n\nMust not be called before%s:\n\n%s", + callString(call.Method, call.Arguments, true), + func() (s string) { + if requirement.totalCalls > 0 { + s = " another call of" + } + if call.Parent != requirement.Parent { + s += " method from another mock instance" + } + return + }(), + callString(requirement.Method, requirement.Arguments, true), + ) + } + } + + if call.Repeatability == 1 { + call.Repeatability = -1 + } else if call.Repeatability > 1 { + call.Repeatability-- + } + call.totalCalls++ + + // add the call + m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments, call.ReturnArguments)) + m.mutex.Unlock() + + // block if specified + if call.WaitFor != nil { + <-call.WaitFor + } else { + time.Sleep(call.waitTime) + } + + m.mutex.Lock() + panicMsg := call.PanicMsg + m.mutex.Unlock() + if panicMsg != nil { + panic(*panicMsg) + } + + m.mutex.Lock() + runFn := call.RunFn + m.mutex.Unlock() + + if runFn != nil { + runFn(arguments) + } + + m.mutex.Lock() + returnArgs := call.ReturnArguments + m.mutex.Unlock() + + return returnArgs +} + +/* + Assertions +*/ + +type assertExpectationiser interface { + AssertExpectations(TestingT) bool +} + +// AssertExpectationsForObjects asserts that everything specified with On and Return +// of the specified objects was in fact called as expected. +// +// Calls may have occurred in any order. +func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + for _, obj := range testObjects { + if m, ok := obj.(*Mock); ok { + t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") + obj = m + } + m := obj.(assertExpectationiser) + if !m.AssertExpectations(t) { + t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) + return false + } + } + return true +} + +// AssertExpectations asserts that everything specified with On and Return was +// in fact called as expected. Calls may have occurred in any order. +func (m *Mock) AssertExpectations(t TestingT) bool { + if s, ok := t.(interface{ Skipped() bool }); ok && s.Skipped() { + return true + } + if h, ok := t.(tHelper); ok { + h.Helper() + } + + m.mutex.Lock() + defer m.mutex.Unlock() + var failedExpectations int + + // iterate through each expectation + expectedCalls := m.expectedCalls() + for _, expectedCall := range expectedCalls { + satisfied, reason := m.checkExpectation(expectedCall) + if !satisfied { + failedExpectations++ + t.Logf(reason) + } + } + + if failedExpectations != 0 { + t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) + } + + return failedExpectations == 0 +} + +func (m *Mock) checkExpectation(call *Call) (bool, string) { + if !call.optional && !m.methodWasCalled(call.Method, call.Arguments) && call.totalCalls == 0 { + return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo) + } + if call.Repeatability > 0 { + return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo) + } + return true, fmt.Sprintf("PASS:\t%s(%s)", call.Method, call.Arguments.String()) +} + +// AssertNumberOfCalls asserts that the method was called expectedCalls times. +func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + var actualCalls int + for _, call := range m.calls() { + if call.Method == methodName { + actualCalls++ + } + } + return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) of method %s does not match the actual number of calls (%d).", expectedCalls, methodName, actualCalls)) +} + +// AssertCalled asserts that the method was called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + if !m.methodWasCalled(methodName, arguments) { + var calledWithArgs []string + for _, call := range m.calls() { + calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) + } + if len(calledWithArgs) == 0 { + return assert.Fail(t, "Should have called with given arguments", + fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) + } + return assert.Fail(t, "Should have called with given arguments", + fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) + } + return true +} + +// AssertNotCalled asserts that the method was not called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + if m.methodWasCalled(methodName, arguments) { + return assert.Fail(t, "Should not have called with given arguments", + fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) + } + return true +} + +// IsMethodCallable checking that the method can be called +// If the method was called more than `Repeatability` return false +func (m *Mock) IsMethodCallable(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + + for _, v := range m.ExpectedCalls { + if v.Method != methodName { + continue + } + if len(arguments) != len(v.Arguments) { + continue + } + if v.Repeatability < v.totalCalls { + continue + } + if isArgsEqual(v.Arguments, arguments) { + return true + } + } + return false +} + +// isArgsEqual compares arguments +func isArgsEqual(expected Arguments, args []interface{}) bool { + if len(expected) != len(args) { + return false + } + for i, v := range args { + if !reflect.DeepEqual(expected[i], v) { + return false + } + } + return true +} + +func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { + for _, call := range m.calls() { + if call.Method == methodName { + + _, differences := Arguments(expected).Diff(call.Arguments) + + if differences == 0 { + // found the expected call + return true + } + + } + } + // we didn't find the expected call + return false +} + +func (m *Mock) expectedCalls() []*Call { + return append([]*Call{}, m.ExpectedCalls...) +} + +func (m *Mock) calls() []Call { + return append([]Call{}, m.Calls...) +} + +/* + Arguments +*/ + +// Arguments holds an array of method arguments or return values. +type Arguments []interface{} + +const ( + // Anything is used in Diff and Assert when the argument being tested + // shouldn't be taken into consideration. + Anything = "mock.Anything" +) + +// AnythingOfTypeArgument contains the type of an argument +// for use when type checking. Used in [Arguments.Diff] and [Arguments.Assert]. +// +// Deprecated: this is an implementation detail that must not be used. Use the [AnythingOfType] constructor instead, example: +// +// m.On("Do", mock.AnythingOfType("string")) +// +// All explicit type declarations can be replaced with interface{} as is expected by [Mock.On], example: +// +// func anyString interface{} { +// return mock.AnythingOfType("string") +// } +type AnythingOfTypeArgument = anythingOfTypeArgument + +// anythingOfTypeArgument is a string that contains the type of an argument +// for use when type checking. Used in Diff and Assert. +type anythingOfTypeArgument string + +// AnythingOfType returns a special value containing the +// name of the type to check for. The type name will be matched against the type name returned by [reflect.Type.String]. +// +// Used in Diff and Assert. +// +// For example: +// +// args.Assert(t, AnythingOfType("string"), AnythingOfType("int")) +func AnythingOfType(t string) AnythingOfTypeArgument { + return anythingOfTypeArgument(t) +} + +// IsTypeArgument is a struct that contains the type of an argument +// for use when type checking. This is an alternative to [AnythingOfType]. +// Used in [Arguments.Diff] and [Arguments.Assert]. +type IsTypeArgument struct { + t reflect.Type +} + +// IsType returns an IsTypeArgument object containing the type to check for. +// You can provide a zero-value of the type to check. This is an +// alternative to [AnythingOfType]. Used in [Arguments.Diff] and [Arguments.Assert]. +// +// For example: +// +// args.Assert(t, IsType(""), IsType(0)) +func IsType(t interface{}) *IsTypeArgument { + return &IsTypeArgument{t: reflect.TypeOf(t)} +} + +// FunctionalOptionsArgument contains a list of functional options arguments +// expected for use when matching a list of arguments. +type FunctionalOptionsArgument struct { + values []interface{} +} + +// String returns the string representation of FunctionalOptionsArgument +func (f *FunctionalOptionsArgument) String() string { + var name string + if len(f.values) > 0 { + name = "[]" + reflect.TypeOf(f.values[0]).String() + } + + return strings.Replace(fmt.Sprintf("%#v", f.values), "[]interface {}", name, 1) +} + +// FunctionalOptions returns an [FunctionalOptionsArgument] object containing +// the expected functional-options to check for. +// +// For example: +// +// args.Assert(t, FunctionalOptions(foo.Opt1("strValue"), foo.Opt2(613))) +func FunctionalOptions(values ...interface{}) *FunctionalOptionsArgument { + return &FunctionalOptionsArgument{ + values: values, + } +} + +// argumentMatcher performs custom argument matching, returning whether or +// not the argument is matched by the expectation fixture function. +type argumentMatcher struct { + // fn is a function which accepts one argument, and returns a bool. + fn reflect.Value +} + +func (f argumentMatcher) Matches(argument interface{}) bool { + expectType := f.fn.Type().In(0) + expectTypeNilSupported := false + switch expectType.Kind() { + case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr: + expectTypeNilSupported = true + } + + argType := reflect.TypeOf(argument) + var arg reflect.Value + if argType == nil { + arg = reflect.New(expectType).Elem() + } else { + arg = reflect.ValueOf(argument) + } + + if argType == nil && !expectTypeNilSupported { + panic(errors.New("attempting to call matcher with nil for non-nil expected type")) + } + if argType == nil || argType.AssignableTo(expectType) { + result := f.fn.Call([]reflect.Value{arg}) + return result[0].Bool() + } + return false +} + +func (f argumentMatcher) String() string { + return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).String()) +} + +// MatchedBy can be used to match a mock call based on only certain properties +// from a complex struct or some calculation. It takes a function that will be +// evaluated with the called argument and will return true when there's a match +// and false otherwise. +// +// Example: +// +// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) +// +// fn must be a function accepting a single argument (of the expected type) +// which returns a bool. If fn doesn't match the required signature, +// MatchedBy() panics. +func MatchedBy(fn interface{}) argumentMatcher { + fnType := reflect.TypeOf(fn) + + if fnType.Kind() != reflect.Func { + panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) + } + if fnType.NumIn() != 1 { + panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) + } + if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { + panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) + } + + return argumentMatcher{fn: reflect.ValueOf(fn)} +} + +// Get Returns the argument at the specified index. +func (args Arguments) Get(index int) interface{} { + if index+1 > len(args) { + panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) + } + return args[index] +} + +// Is gets whether the objects match the arguments specified. +func (args Arguments) Is(objects ...interface{}) bool { + for i, obj := range args { + if obj != objects[i] { + return false + } + } + return true +} + +// Diff gets a string describing the differences between the arguments +// and the specified objects. +// +// Returns the diff string and number of differences found. +func (args Arguments) Diff(objects []interface{}) (string, int) { + // TODO: could return string as error and nil for No difference + + output := "\n" + var differences int + + maxArgCount := len(args) + if len(objects) > maxArgCount { + maxArgCount = len(objects) + } + + for i := 0; i < maxArgCount; i++ { + var actual, expected interface{} + var actualFmt, expectedFmt string + + if len(objects) <= i { + actual = "(Missing)" + actualFmt = "(Missing)" + } else { + actual = objects[i] + actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual) + } + + if len(args) <= i { + expected = "(Missing)" + expectedFmt = "(Missing)" + } else { + expected = args[i] + expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected) + } + + if matcher, ok := expected.(argumentMatcher); ok { + var matches bool + func() { + defer func() { + if r := recover(); r != nil { + actualFmt = fmt.Sprintf("panic in argument matcher: %v", r) + } + }() + matches = matcher.Matches(actual) + }() + if matches { + output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher) + } else { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) + } + } else { + switch expected := expected.(type) { + case anythingOfTypeArgument: + // type checking + if reflect.TypeOf(actual).Name() != string(expected) && reflect.TypeOf(actual).String() != string(expected) { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) + } + case *IsTypeArgument: + actualT := reflect.TypeOf(actual) + if actualT != expected.t { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected.t.Name(), actualT.Name(), actualFmt) + } + case *FunctionalOptionsArgument: + var name string + if len(expected.values) > 0 { + name = "[]" + reflect.TypeOf(expected.values[0]).String() + } + + const tName = "[]interface{}" + if name != reflect.TypeOf(actual).String() && len(expected.values) != 0 { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, tName, reflect.TypeOf(actual).Name(), actualFmt) + } else { + if ef, af := assertOpts(expected.values, actual); ef == "" && af == "" { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, tName, tName) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, af, ef) + } + } + + default: + if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) + } + } + } + + } + + if differences == 0 { + return "No differences.", differences + } + + return output, differences +} + +// Assert compares the arguments with the specified objects and fails if +// they do not exactly match. +func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + // get the differences + diff, diffCount := args.Diff(objects) + + if diffCount == 0 { + return true + } + + // there are differences... report them... + t.Logf(diff) + t.Errorf("%sArguments do not match.", assert.CallerInfo()) + + return false +} + +// String gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +// +// If no index is provided, String() returns a complete string representation +// of the arguments. +func (args Arguments) String(indexOrNil ...int) string { + if len(indexOrNil) == 0 { + // normal String() method - return a string representation of the args + var argsStr []string + for _, arg := range args { + argsStr = append(argsStr, fmt.Sprintf("%T", arg)) // handles nil nicely + } + return strings.Join(argsStr, ",") + } else if len(indexOrNil) == 1 { + // Index has been specified - get the argument at that index + index := indexOrNil[0] + var s string + var ok bool + if s, ok = args.Get(index).(string); !ok { + panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) + } + return s + } + + panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) +} + +// Int gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Int(index int) int { + var s int + var ok bool + if s, ok = args.Get(index).(int); !ok { + panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Error gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Error(index int) error { + obj := args.Get(index) + var s error + var ok bool + if obj == nil { + return nil + } + if s, ok = obj.(error); !ok { + panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, obj)) + } + return s +} + +// Bool gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Bool(index int) bool { + var s bool + var ok bool + if s, ok = args.Get(index).(bool); !ok { + panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { + t := reflect.TypeOf(v) + k := t.Kind() + + if k == reflect.Ptr { + t = t.Elem() + k = t.Kind() + } + return t, k +} + +func diffArguments(expected Arguments, actual Arguments) string { + if len(expected) != len(actual) { + return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) + } + + for x := range expected { + if diffString := diff(expected[x], actual[x]); diffString != "" { + return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) + } + } + + return "" +} + +// diff returns a diff of both values as long as both are of the same type and +// are a struct, map, slice or array. Otherwise it returns an empty string. +func diff(expected interface{}, actual interface{}) string { + if expected == nil || actual == nil { + return "" + } + + et, ek := typeAndKind(expected) + at, _ := typeAndKind(actual) + + if et != at { + return "" + } + + if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { + return "" + } + + e := spewConfig.Sdump(expected) + a := spewConfig.Sdump(actual) + + diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ + A: difflib.SplitLines(e), + B: difflib.SplitLines(a), + FromFile: "Expected", + FromDate: "", + ToFile: "Actual", + ToDate: "", + Context: 1, + }) + + return diff +} + +var spewConfig = spew.ConfigState{ + Indent: " ", + DisablePointerAddresses: true, + DisableCapacities: true, + SortKeys: true, +} + +type tHelper interface { + Helper() +} + +func assertOpts(expected, actual interface{}) (expectedFmt, actualFmt string) { + expectedOpts := reflect.ValueOf(expected) + actualOpts := reflect.ValueOf(actual) + + var expectedFuncs []*runtime.Func + var expectedNames []string + for i := 0; i < expectedOpts.Len(); i++ { + f := runtimeFunc(expectedOpts.Index(i).Interface()) + expectedFuncs = append(expectedFuncs, f) + expectedNames = append(expectedNames, funcName(f)) + } + var actualFuncs []*runtime.Func + var actualNames []string + for i := 0; i < actualOpts.Len(); i++ { + f := runtimeFunc(actualOpts.Index(i).Interface()) + actualFuncs = append(actualFuncs, f) + actualNames = append(actualNames, funcName(f)) + } + + if expectedOpts.Len() != actualOpts.Len() { + expectedFmt = fmt.Sprintf("%v", expectedNames) + actualFmt = fmt.Sprintf("%v", actualNames) + return + } + + for i := 0; i < expectedOpts.Len(); i++ { + if !isFuncSame(expectedFuncs[i], actualFuncs[i]) { + expectedFmt = expectedNames[i] + actualFmt = actualNames[i] + return + } + + expectedOpt := expectedOpts.Index(i).Interface() + actualOpt := actualOpts.Index(i).Interface() + + ot := reflect.TypeOf(expectedOpt) + var expectedValues []reflect.Value + var actualValues []reflect.Value + if ot.NumIn() == 0 { + return + } + + for i := 0; i < ot.NumIn(); i++ { + vt := ot.In(i).Elem() + expectedValues = append(expectedValues, reflect.New(vt)) + actualValues = append(actualValues, reflect.New(vt)) + } + + reflect.ValueOf(expectedOpt).Call(expectedValues) + reflect.ValueOf(actualOpt).Call(actualValues) + + for i := 0; i < ot.NumIn(); i++ { + if expectedArg, actualArg := expectedValues[i].Interface(), actualValues[i].Interface(); !assert.ObjectsAreEqual(expectedArg, actualArg) { + expectedFmt = fmt.Sprintf("%s(%T) -> %#v", expectedNames[i], expectedArg, expectedArg) + actualFmt = fmt.Sprintf("%s(%T) -> %#v", expectedNames[i], actualArg, actualArg) + return + } + } + } + + return "", "" +} + +func runtimeFunc(opt interface{}) *runtime.Func { + return runtime.FuncForPC(reflect.ValueOf(opt).Pointer()) +} + +func funcName(f *runtime.Func) string { + name := f.Name() + trimmed := strings.TrimSuffix(path.Base(name), path.Ext(name)) + splitted := strings.Split(trimmed, ".") + + if len(splitted) == 0 { + return trimmed + } + + return splitted[len(splitted)-1] +} + +func isFuncSame(f1, f2 *runtime.Func) bool { + f1File, f1Loc := f1.FileLine(f1.Entry()) + f2File, f2Loc := f2.FileLine(f2.Entry()) + + return f1File == f2File && f1Loc == f2Loc +} diff --git a/vendor/github.com/technoweenie/multipartstreamer/LICENSE b/vendor/github.com/technoweenie/multipartstreamer/LICENSE new file mode 100644 index 000000000..20d92fbac --- /dev/null +++ b/vendor/github.com/technoweenie/multipartstreamer/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2013-* rick olson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/technoweenie/multipartstreamer/README.md b/vendor/github.com/technoweenie/multipartstreamer/README.md new file mode 100644 index 000000000..dc1f824fe --- /dev/null +++ b/vendor/github.com/technoweenie/multipartstreamer/README.md @@ -0,0 +1,47 @@ +# multipartstreamer + +Package multipartstreamer helps you encode large files in MIME multipart format +without reading the entire content into memory. It uses io.MultiReader to +combine an inner multipart.Reader with a file handle. + +```go +package main + +import ( + "github.com/technoweenie/multipartstreamer.go" + "net/http" +) + +func main() { + ms := multipartstreamer.New() + + ms.WriteFields(map[string]string{ + "key": "some-key", + "AWSAccessKeyId": "ABCDEF", + "acl": "some-acl", + }) + + // Add any io.Reader to the multipart.Reader. + ms.WriteReader("file", "filename", some_ioReader, size) + + // Shortcut for adding local file. + ms.WriteFile("file", "path/to/file") + + req, _ := http.NewRequest("POST", "someurl", nil) + ms.SetupRequest(req) + + res, _ := http.DefaultClient.Do(req) +} +``` + +One limitation: You can only write a single file. + +## TODO + +* Multiple files? + +## Credits + +Heavily inspired by James + +https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/Zjg5l4nKcQ0 diff --git a/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go b/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go new file mode 100644 index 000000000..26d8e8509 --- /dev/null +++ b/vendor/github.com/technoweenie/multipartstreamer/multipartstreamer.go @@ -0,0 +1,101 @@ +/* +Package multipartstreamer helps you encode large files in MIME multipart format +without reading the entire content into memory. It uses io.MultiReader to +combine an inner multipart.Reader with a file handle. +*/ +package multipartstreamer + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "mime/multipart" + "net/http" + "os" + "path/filepath" +) + +type MultipartStreamer struct { + ContentType string + bodyBuffer *bytes.Buffer + bodyWriter *multipart.Writer + closeBuffer *bytes.Buffer + reader io.Reader + contentLength int64 +} + +// New initializes a new MultipartStreamer. +func New() (m *MultipartStreamer) { + m = &MultipartStreamer{bodyBuffer: new(bytes.Buffer)} + + m.bodyWriter = multipart.NewWriter(m.bodyBuffer) + boundary := m.bodyWriter.Boundary() + m.ContentType = "multipart/form-data; boundary=" + boundary + + closeBoundary := fmt.Sprintf("\r\n--%s--\r\n", boundary) + m.closeBuffer = bytes.NewBufferString(closeBoundary) + + return +} + +// WriteFields writes multiple form fields to the multipart.Writer. +func (m *MultipartStreamer) WriteFields(fields map[string]string) error { + var err error + + for key, value := range fields { + err = m.bodyWriter.WriteField(key, value) + if err != nil { + return err + } + } + + return nil +} + +// WriteReader adds an io.Reader to get the content of a file. The reader is +// not accessed until the multipart.Reader is copied to some output writer. +func (m *MultipartStreamer) WriteReader(key, filename string, size int64, reader io.Reader) (err error) { + m.reader = reader + m.contentLength = size + + _, err = m.bodyWriter.CreateFormFile(key, filename) + return +} + +// WriteFile is a shortcut for adding a local file as an io.Reader. +func (m *MultipartStreamer) WriteFile(key, filename string) error { + fh, err := os.Open(filename) + if err != nil { + return err + } + + stat, err := fh.Stat() + if err != nil { + return err + } + + return m.WriteReader(key, filepath.Base(filename), stat.Size(), fh) +} + +// SetupRequest sets up the http.Request body, and some crucial HTTP headers. +func (m *MultipartStreamer) SetupRequest(req *http.Request) { + req.Body = m.GetReader() + req.Header.Add("Content-Type", m.ContentType) + req.ContentLength = m.Len() +} + +func (m *MultipartStreamer) Boundary() string { + return m.bodyWriter.Boundary() +} + +// Len calculates the byte size of the multipart content. +func (m *MultipartStreamer) Len() int64 { + return m.contentLength + int64(m.bodyBuffer.Len()) + int64(m.closeBuffer.Len()) +} + +// GetReader gets an io.ReadCloser for passing to an http.Request. +func (m *MultipartStreamer) GetReader() io.ReadCloser { + reader := io.MultiReader(m.bodyBuffer, m.reader, m.closeBuffer) + return ioutil.NopCloser(reader) +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go index e65c4907c..2dc8eaea9 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go @@ -52,6 +52,12 @@ type Option interface { apply(*config) } +type optionFunc func(*config) + +func (f optionFunc) apply(c *config) { + f(c) +} + // newConfig returns a config configured with all the passed Options. func newConfig(opts []Option) *config { c := &config{ @@ -65,27 +71,13 @@ func newConfig(opts []Option) *config { return c } -type publicEndpointOption struct{ p bool } - -func (o publicEndpointOption) apply(c *config) { - c.PublicEndpoint = o.p -} - // WithPublicEndpoint configures the Handler to link the span with an incoming // span context. If this option is not provided, then the association is a child // association instead of a link. func WithPublicEndpoint() Option { - return publicEndpointOption{p: true} -} - -type publicEndpointFnOption struct { - fn func(context.Context, *stats.RPCTagInfo) bool -} - -func (o publicEndpointFnOption) apply(c *config) { - if o.fn != nil { - c.PublicEndpointFn = o.fn - } + return optionFunc(func(c *config) { + c.PublicEndpoint = true + }) } // WithPublicEndpointFn runs with every request, and allows conditionally @@ -94,81 +86,55 @@ func (o publicEndpointFnOption) apply(c *config) { // child association instead of a link. // Note: WithPublicEndpoint takes precedence over WithPublicEndpointFn. func WithPublicEndpointFn(fn func(context.Context, *stats.RPCTagInfo) bool) Option { - return publicEndpointFnOption{fn: fn} -} - -type propagatorsOption struct{ p propagation.TextMapPropagator } - -func (o propagatorsOption) apply(c *config) { - if o.p != nil { - c.Propagators = o.p - } + return optionFunc(func(c *config) { + c.PublicEndpointFn = fn + }) } // WithPropagators returns an Option to use the Propagators when extracting // and injecting trace context from requests. func WithPropagators(p propagation.TextMapPropagator) Option { - return propagatorsOption{p: p} -} - -type tracerProviderOption struct{ tp trace.TracerProvider } - -func (o tracerProviderOption) apply(c *config) { - if o.tp != nil { - c.TracerProvider = o.tp - } + return optionFunc(func(c *config) { + if p != nil { + c.Propagators = p + } + }) } // WithInterceptorFilter returns an Option to use the request filter. // // Deprecated: Use stats handlers instead. func WithInterceptorFilter(f InterceptorFilter) Option { - return interceptorFilterOption{f: f} -} - -type interceptorFilterOption struct { - f InterceptorFilter -} - -func (o interceptorFilterOption) apply(c *config) { - if o.f != nil { - c.InterceptorFilter = o.f - } + return optionFunc(func(c *config) { + if f != nil { + c.InterceptorFilter = f + } + }) } // WithFilter returns an Option to use the request filter. func WithFilter(f Filter) Option { - return filterOption{f: f} -} - -type filterOption struct { - f Filter -} - -func (o filterOption) apply(c *config) { - if o.f != nil { - c.Filter = o.f - } + return optionFunc(func(c *config) { + if f != nil { + c.Filter = f + } + }) } // WithTracerProvider returns an Option to use the TracerProvider when // creating a Tracer. func WithTracerProvider(tp trace.TracerProvider) Option { - return tracerProviderOption{tp: tp} -} - -type meterProviderOption struct{ mp metric.MeterProvider } - -func (o meterProviderOption) apply(c *config) { - if o.mp != nil { - c.MeterProvider = o.mp - } + return optionFunc(func(c *config) { + c.TracerProvider = tp + }) } // WithMeterProvider returns an Option to use the MeterProvider when // creating a Meter. If this option is not provide the global MeterProvider will be used. func WithMeterProvider(mp metric.MeterProvider) Option { - return meterProviderOption{mp: mp} + return optionFunc(func(c *config) { + c.MeterProvider = mp + }) } // Event type that can be recorded, see WithMessageEvents. @@ -180,21 +146,6 @@ const ( SentEvents ) -type messageEventsProviderOption struct { - events []Event -} - -func (m messageEventsProviderOption) apply(c *config) { - for _, e := range m.events { - switch e { - case ReceivedEvents: - c.ReceivedEvent = true - case SentEvents: - c.SentEvent = true - } - } -} - // WithMessageEvents configures the Handler to record the specified events // (span.AddEvent) on spans. By default only summary attributes are added at the // end of the request. @@ -203,13 +154,16 @@ func (m messageEventsProviderOption) apply(c *config) { // - ReceivedEvents: Record the number of bytes read after every gRPC read operation. // - SentEvents: Record the number of bytes written after every gRPC write operation. func WithMessageEvents(events ...Event) Option { - return messageEventsProviderOption{events: events} -} - -type spanStartOption struct{ opts []trace.SpanStartOption } - -func (o spanStartOption) apply(c *config) { - c.SpanStartOptions = append(c.SpanStartOptions, o.opts...) + return optionFunc(func(c *config) { + for _, e := range events { + switch e { + case ReceivedEvents: + c.ReceivedEvent = true + case SentEvents: + c.SentEvent = true + } + } + }) } // WithSpanOptions configures an additional set of @@ -217,31 +171,25 @@ func (o spanStartOption) apply(c *config) { // // Deprecated: It is only used by the deprecated interceptor, and is unused by [NewClientHandler] and [NewServerHandler]. func WithSpanOptions(opts ...trace.SpanStartOption) Option { - return spanStartOption{opts} -} - -type spanAttributesOption struct{ a []attribute.KeyValue } - -func (o spanAttributesOption) apply(c *config) { - if o.a != nil { - c.SpanAttributes = o.a - } + return optionFunc(func(c *config) { + c.SpanStartOptions = append(c.SpanStartOptions, opts...) + }) } // WithSpanAttributes returns an Option to add custom attributes to the spans. func WithSpanAttributes(a ...attribute.KeyValue) Option { - return spanAttributesOption{a: a} -} - -type metricAttributesOption struct{ a []attribute.KeyValue } - -func (o metricAttributesOption) apply(c *config) { - if o.a != nil { - c.MetricAttributes = o.a - } + return optionFunc(func(c *config) { + if a != nil { + c.SpanAttributes = a + } + }) } // WithMetricAttributes returns an Option to add custom attributes to the metrics. func WithMetricAttributes(a ...attribute.KeyValue) Option { - return metricAttributesOption{a: a} + return optionFunc(func(c *config) { + if a != nil { + c.MetricAttributes = append(c.MetricAttributes, a...) + } + }) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go index b427e1724..4c62341d6 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go @@ -6,9 +6,7 @@ package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.g import ( "context" - "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" "google.golang.org/grpc/metadata" ) @@ -17,9 +15,9 @@ type metadataSupplier struct { } // assert that metadataSupplier implements the TextMapCarrier interface. -var _ propagation.TextMapCarrier = &metadataSupplier{} +var _ propagation.TextMapCarrier = metadataSupplier{} -func (s *metadataSupplier) Get(key string) string { +func (s metadataSupplier) Get(key string) string { values := s.metadata.Get(key) if len(values) == 0 { return "" @@ -27,11 +25,11 @@ func (s *metadataSupplier) Get(key string) string { return values[0] } -func (s *metadataSupplier) Set(key, value string) { +func (s metadataSupplier) Set(key, value string) { s.metadata.Set(key, value) } -func (s *metadataSupplier) Keys() []string { +func (s metadataSupplier) Keys() []string { out := make([]string, 0, len(s.metadata)) for key := range s.metadata { out = append(out, key) @@ -39,50 +37,24 @@ func (s *metadataSupplier) Keys() []string { return out } -// Inject injects correlation context and span context into the gRPC -// metadata object. This function is meant to be used on outgoing -// requests. -// -// Deprecated: Unnecessary public func. -func Inject(ctx context.Context, md *metadata.MD, opts ...Option) { - c := newConfig(opts) - c.Propagators.Inject(ctx, &metadataSupplier{ - metadata: *md, - }) -} - func inject(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { md, ok := metadata.FromOutgoingContext(ctx) if !ok { md = metadata.MD{} } - propagators.Inject(ctx, &metadataSupplier{ + propagators.Inject(ctx, metadataSupplier{ metadata: md, }) return metadata.NewOutgoingContext(ctx, md) } -// Extract returns the correlation context and span context that -// another service encoded in the gRPC metadata object with Inject. -// This function is meant to be used on incoming requests. -// -// Deprecated: Unnecessary public func. -func Extract(ctx context.Context, md *metadata.MD, opts ...Option) (baggage.Baggage, trace.SpanContext) { - c := newConfig(opts) - ctx = c.Propagators.Extract(ctx, &metadataSupplier{ - metadata: *md, - }) - - return baggage.FromContext(ctx), trace.SpanContextFromContext(ctx) -} - func extract(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { md, ok := metadata.FromIncomingContext(ctx) if !ok { md = metadata.MD{} } - return propagators.Extract(ctx, &metadataSupplier{ + return propagators.Extract(ctx, metadataSupplier{ metadata: md, }) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go index 29d7ab2bd..278f6d0d9 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/stats_handler.go @@ -26,10 +26,11 @@ import ( type gRPCContextKey struct{} type gRPCContext struct { - inMessages int64 - outMessages int64 - metricAttrs []attribute.KeyValue - record bool + inMessages int64 + outMessages int64 + metricAttrs []attribute.KeyValue + metricAttrSet attribute.Set + record bool } type serverHandler struct { @@ -38,8 +39,8 @@ type serverHandler struct { tracer trace.Tracer duration rpcconv.ServerDuration - inSize rpcconv.ServerRequestSize - outSize rpcconv.ServerResponseSize + inSize int64Hist + outSize int64Hist inMsg rpcconv.ServerRequestsPerRPC outMsg rpcconv.ServerResponsesPerRPC } @@ -111,9 +112,12 @@ func (h *serverHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) cont } if record { + // Make a new slice to avoid aliasing into the same attrs slice used by metrics. + spanAttributes := make([]attribute.KeyValue, 0, len(attrs)+len(h.SpanAttributes)) + spanAttributes = append(append(spanAttributes, attrs...), h.SpanAttributes...) opts := []trace.SpanStartOption{ trace.WithSpanKind(trace.SpanKindServer), - trace.WithAttributes(append(attrs, h.SpanAttributes...)...), + trace.WithAttributes(spanAttributes...), } if h.PublicEndpoint || (h.PublicEndpointFn != nil && h.PublicEndpointFn(ctx, info)) { opts = append(opts, trace.WithNewRoot()) @@ -133,6 +137,7 @@ func (h *serverHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) cont metricAttrs: append(attrs, h.MetricAttributes...), record: record, } + gctx.metricAttrSet = attribute.NewSet(gctx.metricAttrs...) return context.WithValue(ctx, gRPCContextKey{}, &gctx) } @@ -157,8 +162,8 @@ type clientHandler struct { tracer trace.Tracer duration rpcconv.ClientDuration - inSize rpcconv.ClientResponseSize - outSize rpcconv.ClientRequestSize + inSize int64Hist + outSize int64Hist inMsg rpcconv.ClientResponsesPerRPC outMsg rpcconv.ClientRequestsPerRPC } @@ -219,11 +224,14 @@ func (h *clientHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) cont } if record { + // Make a new slice to avoid aliasing into the same attrs slice used by metrics. + spanAttributes := make([]attribute.KeyValue, 0, len(attrs)+len(h.SpanAttributes)) + spanAttributes = append(append(spanAttributes, attrs...), h.SpanAttributes...) ctx, _ = h.tracer.Start( ctx, name, trace.WithSpanKind(trace.SpanKindClient), - trace.WithAttributes(append(attrs, h.SpanAttributes...)...), + trace.WithAttributes(spanAttributes...), ) } @@ -231,6 +239,7 @@ func (h *clientHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) cont metricAttrs: append(attrs, h.MetricAttributes...), record: record, } + gctx.metricAttrSet = attribute.NewSet(gctx.metricAttrs...) return inject(context.WithValue(ctx, gRPCContextKey{}, &gctx), h.Propagators) } @@ -262,7 +271,7 @@ func (*clientHandler) HandleConn(context.Context, stats.ConnStats) { } type int64Hist interface { - Record(context.Context, int64, ...attribute.KeyValue) + RecordSet(context.Context, int64, attribute.Set) } func (c *config) handleRPC( @@ -286,7 +295,7 @@ func (c *config) handleRPC( case *stats.InPayload: if gctx != nil { messageId = atomic.AddInt64(&gctx.inMessages, 1) - inSize.Record(ctx, int64(rs.Length), gctx.metricAttrs...) + inSize.RecordSet(ctx, int64(rs.Length), gctx.metricAttrSet) } if c.ReceivedEvent && span.IsRecording() { @@ -302,7 +311,7 @@ func (c *config) handleRPC( case *stats.OutPayload: if gctx != nil { messageId = atomic.AddInt64(&gctx.outMessages, 1) - outSize.Record(ctx, int64(rs.Length), gctx.metricAttrs...) + outSize.RecordSet(ctx, int64(rs.Length), gctx.metricAttrSet) } if c.SentEvent && span.IsRecording() { @@ -343,6 +352,9 @@ func (c *config) handleRPC( var metricAttrs []attribute.KeyValue if gctx != nil { + // Don't use gctx.metricAttrSet here, because it requires passing + // multiple RecordOptions, which would call metric.mergeSets and + // allocate a new set for each Record call. metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+1) metricAttrs = append(metricAttrs, gctx.metricAttrs...) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go index aa4f4e212..98f148be5 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go @@ -5,6 +5,6 @@ package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.g // Version is the current release version of the gRPC instrumentation. func Version() string { - return "0.63.0" + return "0.64.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/LICENSE b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/LICENSE index 261eeb9e9..f1aee0f11 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/LICENSE +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/LICENSE @@ -199,3 +199,33 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +-------------------------------------------------------------------------------- + +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go index b25641c55..e980ab62b 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go @@ -14,11 +14,17 @@ import ( // DefaultClient is the default Client and is used by Get, Head, Post and PostForm. // Please be careful of initialization order - for example, if you change // the global propagator, the DefaultClient might still be using the old one. +// +// Deprecated: [DefaultClient] will be removed in a future release. +// Create your own [http.Client] based on the [Transport] example: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp#example-NewTransport var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)} // Get is a convenient replacement for http.Get that adds a span around the request. +// +// Deprecated: [Get] will be removed in a future release. +// Create your own [http.Client] based on the [Transport] example: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp#example-NewTransport func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, http.NoBody) if err != nil { return nil, err } @@ -26,8 +32,11 @@ func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) } // Head is a convenient replacement for http.Head that adds a span around the request. +// +// Deprecated: [Head] will be removed in a future release. +// Create your own [http.Client] based on the [Transport] example: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp#example-NewTransport func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, http.MethodHead, targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodHead, targetURL, http.NoBody) if err != nil { return nil, err } @@ -35,6 +44,9 @@ func Head(ctx context.Context, targetURL string) (resp *http.Response, err error } // Post is a convenient replacement for http.Post that adds a span around the request. +// +// Deprecated: [Post] will be removed in a future release. +// Create your own [http.Client] based on the [Transport] example: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp#example-NewTransport func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, body) if err != nil { @@ -45,6 +57,9 @@ func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (r } // PostForm is a convenient replacement for http.PostForm that adds a span around the request. +// +// Deprecated: [PostForm] will be removed in a future release. +// Create your own [http.Client] based on the [Transport] example: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp#example-NewTransport func PostForm(ctx context.Context, targetURL string, data url.Values) (resp *http.Response, err error) { return Post(ctx, targetURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go index 6bd50d4c9..c3be78616 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go @@ -8,9 +8,8 @@ import ( "net/http" "net/http/httptrace" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" @@ -27,7 +26,6 @@ type config struct { Meter metric.Meter Propagators propagation.TextMapPropagator SpanStartOptions []trace.SpanStartOption - PublicEndpoint bool PublicEndpointFn func(*http.Request) bool ReadEvent bool WriteEvent bool @@ -97,17 +95,19 @@ func WithMeterProvider(provider metric.MeterProvider) Option { // WithPublicEndpoint configures the Handler to link the span with an incoming // span context. If this option is not provided, then the association is a child // association instead of a link. +// +// Deprecated: Use [WithPublicEndpointFn] instead. +// To migrate, replace WithPublicEndpoint() with: +// +// WithPublicEndpointFn(func(*http.Request) bool { return true }) func WithPublicEndpoint() Option { - return optionFunc(func(c *config) { - c.PublicEndpoint = true - }) + return WithPublicEndpointFn(func(*http.Request) bool { return true }) } // WithPublicEndpointFn runs with every request, and allows conditionally // configuring the Handler to link the span with an incoming span context. If // this option is not provided or returns false, then the association is a // child association instead of a link. -// Note: WithPublicEndpoint takes precedence over WithPublicEndpointFn. func WithPublicEndpointFn(fn func(*http.Request) bool) Option { return optionFunc(func(c *config) { c.PublicEndpointFn = fn @@ -144,11 +144,13 @@ func WithFilter(f Filter) Option { }) } -type event int +// Event represents message event types for [WithMessageEvents]. +type Event int // Different types of events that can be recorded, see WithMessageEvents. const ( - ReadEvents event = iota + unspecifiedEvents Event = iota + ReadEvents WriteEvents ) @@ -161,7 +163,7 @@ const ( // using the ReadBytesKey // - WriteEvents: Record the number of bytes written after every http.ResponeWriter.Write // using the WriteBytesKey -func WithMessageEvents(events ...event) Option { +func WithMessageEvents(events ...Event) Option { return optionFunc(func(c *config) { for _, e := range events { switch e { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/doc.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/doc.go index 56b24b982..1c9aa3ff4 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/doc.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/doc.go @@ -2,6 +2,5 @@ // SPDX-License-Identifier: Apache-2.0 // Package otelhttp provides an http.Handler and functions that are intended -// to be used to add tracing by wrapping existing handlers (with Handler) and -// routes WithRouteTag. +// to be used to add tracing by wrapping existing handlers. package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index 937f9b4e7..c1bbf3a3c 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -8,13 +8,13 @@ import ( "time" "github.com/felixge/httpsnoop" - - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" + + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" ) // middleware is an http middleware which wraps the next handler in a span. @@ -29,7 +29,6 @@ type middleware struct { writeEvent bool filters []Filter spanNameFormatter func(string, *http.Request) string - publicEndpoint bool publicEndpointFn func(*http.Request) bool metricAttributesFn func(*http.Request) []attribute.KeyValue @@ -77,7 +76,6 @@ func (h *middleware) configure(c *config) { h.writeEvent = c.WriteEvent h.filters = c.Filters h.spanNameFormatter = c.SpanNameFormatter - h.publicEndpoint = c.PublicEndpoint h.publicEndpointFn = c.PublicEndpointFn h.server = c.ServerName h.semconv = semconv.NewHTTPServer(c.Meter) @@ -102,7 +100,7 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http } opts = append(opts, h.spanStartOptions...) - if h.publicEndpoint || (h.publicEndpointFn != nil && h.publicEndpointFn(r.WithContext(ctx))) { + if h.publicEndpointFn != nil && h.publicEndpointFn(r.WithContext(ctx)) { opts = append(opts, trace.WithNewRoot()) // Linking incoming span context if any for public endpoint. if s := trace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() { @@ -224,6 +222,9 @@ func (h *middleware) metricAttributesFromRequest(r *http.Request) []attribute.Ke // WithRouteTag annotates spans and metrics with the provided route name // with HTTP route attribute. +// +// Deprecated: spans are automatically annotated with the route attribute. +// To annotate metrics, use the [WithMetricAttributesFn] option. func WithRouteTag(route string, h http.Handler) http.Handler { attr := semconv.NewHTTPServer(nil).Route(route) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/client.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/client.go new file mode 100644 index 000000000..45d3d934f --- /dev/null +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/client.go @@ -0,0 +1,305 @@ +// Code generated by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/client.go.tmpl + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package semconv provides OpenTelemetry semantic convention types and +// functionality. +package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" + +import ( + "context" + "fmt" + "net/http" + "reflect" + "slices" + "strconv" + "strings" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/semconv/v1.37.0" + "go.opentelemetry.io/otel/semconv/v1.37.0/httpconv" +) + +type HTTPClient struct{ + requestBodySize httpconv.ClientRequestBodySize + requestDuration httpconv.ClientRequestDuration +} + +func NewHTTPClient(meter metric.Meter) HTTPClient { + client := HTTPClient{} + + var err error + client.requestBodySize, err = httpconv.NewClientRequestBodySize(meter) + handleErr(err) + + client.requestDuration, err = httpconv.NewClientRequestDuration( + meter, + metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10), + ) + handleErr(err) + + return client +} + +func (n HTTPClient) Status(code int) (codes.Code, string) { + if code < 100 || code >= 600 { + return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) + } + if code >= 400 { + return codes.Error, "" + } + return codes.Unset, "" +} + +// RequestTraceAttrs returns trace attributes for an HTTP request made by a client. +func (n HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { + /* + below attributes are returned: + - http.request.method + - http.request.method.original + - url.full + - server.address + - server.port + - network.protocol.name + - network.protocol.version + */ + numOfAttributes := 3 // URL, server address, proto, and method. + + var urlHost string + if req.URL != nil { + urlHost = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{urlHost, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + eligiblePort := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if eligiblePort > 0 { + numOfAttributes++ + } + useragent := req.UserAgent() + if useragent != "" { + numOfAttributes++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" && protoName != "http" { + numOfAttributes++ + } + if protoVersion != "" { + numOfAttributes++ + } + + method, originalMethod := n.method(req.Method) + if originalMethod != (attribute.KeyValue{}) { + numOfAttributes++ + } + + attrs := make([]attribute.KeyValue, 0, numOfAttributes) + + attrs = append(attrs, method) + if originalMethod != (attribute.KeyValue{}) { + attrs = append(attrs, originalMethod) + } + + var u string + if req.URL != nil { + // Remove any username/password info that may be in the URL. + userinfo := req.URL.User + req.URL.User = nil + u = req.URL.String() + // Restore any username/password info that was removed. + req.URL.User = userinfo + } + attrs = append(attrs, semconv.URLFull(u)) + + attrs = append(attrs, semconv.ServerAddress(requestHost)) + if eligiblePort > 0 { + attrs = append(attrs, semconv.ServerPort(eligiblePort)) + } + + if protoName != "" && protoName != "http" { + attrs = append(attrs, semconv.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion)) + } + + return attrs +} + +// ResponseTraceAttrs returns trace attributes for an HTTP response made by a client. +func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { + /* + below attributes are returned: + - http.response.status_code + - error.type + */ + var count int + if resp.StatusCode > 0 { + count++ + } + + if isErrorStatusCode(resp.StatusCode) { + count++ + } + + attrs := make([]attribute.KeyValue, 0, count) + if resp.StatusCode > 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(resp.StatusCode)) + } + + if isErrorStatusCode(resp.StatusCode) { + errorType := strconv.Itoa(resp.StatusCode) + attrs = append(attrs, semconv.ErrorTypeKey.String(errorType)) + } + return attrs +} + +func (n HTTPClient) ErrorType(err error) attribute.KeyValue { + t := reflect.TypeOf(err) + var value string + if t.PkgPath() == "" && t.Name() == "" { + // Likely a builtin type. + value = t.String() + } else { + value = fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) + } + + if value == "" { + return semconv.ErrorTypeOther + } + + return semconv.ErrorTypeKey.String(value) +} + +func (n HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) { + if method == "" { + return semconv.HTTPRequestMethodGet, attribute.KeyValue{} + } + if attr, ok := methodLookup[method]; ok { + return attr, attribute.KeyValue{} + } + + orig := semconv.HTTPRequestMethodOriginal(method) + if attr, ok := methodLookup[strings.ToUpper(method)]; ok { + return attr, orig + } + return semconv.HTTPRequestMethodGet, orig +} + +func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + num := len(additionalAttributes) + 2 + var h string + if req.URL != nil { + h = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{h, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if port > 0 { + num++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" { + num++ + } + if protoVersion != "" { + num++ + } + + if statusCode > 0 { + num++ + } + + attributes := slices.Grow(additionalAttributes, num) + attributes = append(attributes, + semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), + semconv.ServerAddress(requestHost), + n.scheme(req), + ) + + if port > 0 { + attributes = append(attributes, semconv.ServerPort(port)) + } + if protoName != "" { + attributes = append(attributes, semconv.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attributes = append(attributes, semconv.NetworkProtocolVersion(protoVersion)) + } + + if statusCode > 0 { + attributes = append(attributes, semconv.HTTPResponseStatusCode(statusCode)) + } + return attributes +} + +type MetricOpts struct { + measurement metric.MeasurementOption + addOptions metric.AddOption +} + +func (o MetricOpts) MeasurementOption() metric.MeasurementOption { + return o.measurement +} + +func (o MetricOpts) AddOptions() metric.AddOption { + return o.addOptions +} + +func (n HTTPClient) MetricOptions(ma MetricAttributes) map[string]MetricOpts { + opts := map[string]MetricOpts{} + + attributes := n.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) + set := metric.WithAttributeSet(attribute.NewSet(attributes...)) + opts["new"] = MetricOpts{ + measurement: set, + addOptions: set, + } + + return opts +} + +func (n HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts map[string]MetricOpts) { + n.requestBodySize.Inst().Record(ctx, md.RequestSize, opts["new"].MeasurementOption()) + n.requestDuration.Inst().Record(ctx, md.ElapsedTime/1000, opts["new"].MeasurementOption()) +} + +// TraceAttributes returns attributes for httptrace. +func (n HTTPClient) TraceAttributes(host string) []attribute.KeyValue { + return []attribute.KeyValue{ + semconv.ServerAddress(host), + } +} + +func (n HTTPClient) scheme(req *http.Request) attribute.KeyValue { + if req.URL != nil && req.URL.Scheme != "" { + return semconv.URLScheme(req.URL.Scheme) + } + if req.TLS != nil { + return semconv.URLScheme("https") + } + return semconv.URLScheme("http") +} + +func isErrorStatusCode(code int) bool { + return code >= 400 || code < 100 +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go deleted file mode 100644 index 7cb9693d9..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go +++ /dev/null @@ -1,323 +0,0 @@ -// Code generated by gotmpl. DO NOT MODIFY. -// source: internal/shared/semconv/env.go.tmpl - -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - -import ( - "context" - "fmt" - "net/http" - "os" - "strings" - "sync" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/metric" -) - -// OTelSemConvStabilityOptIn is an environment variable. -// That can be set to "http/dup" to keep getting the old HTTP semantic conventions. -const OTelSemConvStabilityOptIn = "OTEL_SEMCONV_STABILITY_OPT_IN" - -type ResponseTelemetry struct { - StatusCode int - ReadBytes int64 - ReadError error - WriteBytes int64 - WriteError error -} - -type HTTPServer struct { - duplicate bool - - // Old metrics - requestBytesCounter metric.Int64Counter - responseBytesCounter metric.Int64Counter - serverLatencyMeasure metric.Float64Histogram - - // New metrics - requestBodySizeHistogram metric.Int64Histogram - responseBodySizeHistogram metric.Int64Histogram - requestDurationHistogram metric.Float64Histogram -} - -// RequestTraceAttrs returns trace attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -func (s HTTPServer) RequestTraceAttrs(server string, req *http.Request, opts RequestTraceAttrsOpts) []attribute.KeyValue { - attrs := CurrentHTTPServer{}.RequestTraceAttrs(server, req, opts) - if s.duplicate { - return OldHTTPServer{}.RequestTraceAttrs(server, req, attrs) - } - return attrs -} - -func (s HTTPServer) NetworkTransportAttr(network string) []attribute.KeyValue { - if s.duplicate { - return []attribute.KeyValue{ - OldHTTPServer{}.NetworkTransportAttr(network), - CurrentHTTPServer{}.NetworkTransportAttr(network), - } - } - return []attribute.KeyValue{ - CurrentHTTPServer{}.NetworkTransportAttr(network), - } -} - -// ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. -// -// If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (s HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { - attrs := CurrentHTTPServer{}.ResponseTraceAttrs(resp) - if s.duplicate { - return OldHTTPServer{}.ResponseTraceAttrs(resp, attrs) - } - return attrs -} - -// Route returns the attribute for the route. -func (s HTTPServer) Route(route string) attribute.KeyValue { - return CurrentHTTPServer{}.Route(route) -} - -// Status returns a span status code and message for an HTTP status code -// value returned by a server. Status codes in the 400-499 range are not -// returned as errors. -func (s HTTPServer) Status(code int) (codes.Code, string) { - if code < 100 || code >= 600 { - return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) - } - if code >= 500 { - return codes.Error, "" - } - return codes.Unset, "" -} - -type ServerMetricData struct { - ServerName string - ResponseSize int64 - - MetricData - MetricAttributes -} - -type MetricAttributes struct { - Req *http.Request - StatusCode int - AdditionalAttributes []attribute.KeyValue -} - -type MetricData struct { - RequestSize int64 - - // The request duration, in milliseconds - ElapsedTime float64 -} - -var ( - metricAddOptionPool = &sync.Pool{ - New: func() interface{} { - return &[]metric.AddOption{} - }, - } - - metricRecordOptionPool = &sync.Pool{ - New: func() interface{} { - return &[]metric.RecordOption{} - }, - } -) - -func (s HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { - if s.requestDurationHistogram != nil && s.requestBodySizeHistogram != nil && s.responseBodySizeHistogram != nil { - attributes := CurrentHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) - o := metric.WithAttributeSet(attribute.NewSet(attributes...)) - recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption) - *recordOpts = append(*recordOpts, o) - s.requestBodySizeHistogram.Record(ctx, md.RequestSize, *recordOpts...) - s.responseBodySizeHistogram.Record(ctx, md.ResponseSize, *recordOpts...) - s.requestDurationHistogram.Record(ctx, md.ElapsedTime/1000.0, o) - *recordOpts = (*recordOpts)[:0] - metricRecordOptionPool.Put(recordOpts) - } - - if s.duplicate && s.requestBytesCounter != nil && s.responseBytesCounter != nil && s.serverLatencyMeasure != nil { - attributes := OldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) - o := metric.WithAttributeSet(attribute.NewSet(attributes...)) - addOpts := metricAddOptionPool.Get().(*[]metric.AddOption) - *addOpts = append(*addOpts, o) - s.requestBytesCounter.Add(ctx, md.RequestSize, *addOpts...) - s.responseBytesCounter.Add(ctx, md.ResponseSize, *addOpts...) - s.serverLatencyMeasure.Record(ctx, md.ElapsedTime, o) - *addOpts = (*addOpts)[:0] - metricAddOptionPool.Put(addOpts) - } -} - -// hasOptIn returns true if the comma-separated version string contains the -// exact optIn value. -func hasOptIn(version, optIn string) bool { - for _, v := range strings.Split(version, ",") { - if strings.TrimSpace(v) == optIn { - return true - } - } - return false -} - -func NewHTTPServer(meter metric.Meter) HTTPServer { - env := strings.ToLower(os.Getenv(OTelSemConvStabilityOptIn)) - duplicate := hasOptIn(env, "http/dup") - server := HTTPServer{ - duplicate: duplicate, - } - server.requestBodySizeHistogram, server.responseBodySizeHistogram, server.requestDurationHistogram = CurrentHTTPServer{}.createMeasures(meter) - if duplicate { - server.requestBytesCounter, server.responseBytesCounter, server.serverLatencyMeasure = OldHTTPServer{}.createMeasures(meter) - } - return server -} - -type HTTPClient struct { - duplicate bool - - // old metrics - requestBytesCounter metric.Int64Counter - responseBytesCounter metric.Int64Counter - latencyMeasure metric.Float64Histogram - - // new metrics - requestBodySize metric.Int64Histogram - requestDuration metric.Float64Histogram -} - -func NewHTTPClient(meter metric.Meter) HTTPClient { - env := strings.ToLower(os.Getenv(OTelSemConvStabilityOptIn)) - duplicate := hasOptIn(env, "http/dup") - client := HTTPClient{ - duplicate: duplicate, - } - client.requestBodySize, client.requestDuration = CurrentHTTPClient{}.createMeasures(meter) - if duplicate { - client.requestBytesCounter, client.responseBytesCounter, client.latencyMeasure = OldHTTPClient{}.createMeasures(meter) - } - - return client -} - -// RequestTraceAttrs returns attributes for an HTTP request made by a client. -func (c HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { - attrs := CurrentHTTPClient{}.RequestTraceAttrs(req) - if c.duplicate { - return OldHTTPClient{}.RequestTraceAttrs(req, attrs) - } - return attrs -} - -// ResponseTraceAttrs returns metric attributes for an HTTP request made by a client. -func (c HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { - attrs := CurrentHTTPClient{}.ResponseTraceAttrs(resp) - if c.duplicate { - return OldHTTPClient{}.ResponseTraceAttrs(resp, attrs) - } - return attrs -} - -func (c HTTPClient) Status(code int) (codes.Code, string) { - if code < 100 || code >= 600 { - return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) - } - if code >= 400 { - return codes.Error, "" - } - return codes.Unset, "" -} - -func (c HTTPClient) ErrorType(err error) attribute.KeyValue { - return CurrentHTTPClient{}.ErrorType(err) -} - -type MetricOpts struct { - measurement metric.MeasurementOption - addOptions metric.AddOption -} - -func (o MetricOpts) MeasurementOption() metric.MeasurementOption { - return o.measurement -} - -func (o MetricOpts) AddOptions() metric.AddOption { - return o.addOptions -} - -func (c HTTPClient) MetricOptions(ma MetricAttributes) map[string]MetricOpts { - opts := map[string]MetricOpts{} - - attributes := CurrentHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) - set := metric.WithAttributeSet(attribute.NewSet(attributes...)) - opts["new"] = MetricOpts{ - measurement: set, - addOptions: set, - } - - if c.duplicate { - attributes := OldHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) - set := metric.WithAttributeSet(attribute.NewSet(attributes...)) - opts["old"] = MetricOpts{ - measurement: set, - addOptions: set, - } - } - - return opts -} - -func (s HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts map[string]MetricOpts) { - if s.requestBodySize == nil || s.requestDuration == nil { - // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). - return - } - - s.requestBodySize.Record(ctx, md.RequestSize, opts["new"].MeasurementOption()) - s.requestDuration.Record(ctx, md.ElapsedTime/1000, opts["new"].MeasurementOption()) - - if s.duplicate { - s.requestBytesCounter.Add(ctx, md.RequestSize, opts["old"].AddOptions()) - s.latencyMeasure.Record(ctx, md.ElapsedTime, opts["old"].MeasurementOption()) - } -} - -func (s HTTPClient) RecordResponseSize(ctx context.Context, responseData int64, opts map[string]MetricOpts) { - if s.responseBytesCounter == nil { - // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). - return - } - - s.responseBytesCounter.Add(ctx, responseData, opts["old"].AddOptions()) -} - -func (s HTTPClient) TraceAttributes(host string) []attribute.KeyValue { - attrs := CurrentHTTPClient{}.TraceAttributes(host) - if s.duplicate { - return OldHTTPClient{}.TraceAttributes(host, attrs) - } - - return attrs -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go index f2cf8a152..a8a0d58df 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/gen.go @@ -5,10 +5,11 @@ package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/ // Generate semconv package: //go:generate gotmpl --body=../../../../../../internal/shared/semconv/bench_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=bench_test.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconv/env.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=env.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconv/env_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=env_test.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconv.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=httpconv.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconv_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=httpconv_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/common_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=common_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/server.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=server.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/server_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=server_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/client.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=client.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/client_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=client_test.go +//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconvtest_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=httpconvtest_test.go //go:generate gotmpl --body=../../../../../../internal/shared/semconv/util.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=util.go //go:generate gotmpl --body=../../../../../../internal/shared/semconv/util_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=util_test.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconv/v1.20.0.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=v1.20.0.go diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go deleted file mode 100644 index 53976b0d5..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go +++ /dev/null @@ -1,573 +0,0 @@ -// Code generated by gotmpl. DO NOT MODIFY. -// source: internal/shared/semconv/httpconv.go.tmpl - -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconv provides OpenTelemetry semantic convention types and -// functionality. -package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - -import ( - "fmt" - "net/http" - "reflect" - "slices" - "strconv" - "strings" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/noop" - semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" -) - -type RequestTraceAttrsOpts struct { - // If set, this is used as value for the "http.client_ip" attribute. - HTTPClientIP string -} - -type CurrentHTTPServer struct{} - -// RequestTraceAttrs returns trace attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -func (n CurrentHTTPServer) RequestTraceAttrs(server string, req *http.Request, opts RequestTraceAttrsOpts) []attribute.KeyValue { - count := 3 // ServerAddress, Method, Scheme - - var host string - var p int - if server == "" { - host, p = SplitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = SplitHostPort(server) - if p < 0 { - _, p = SplitHostPort(req.Host) - } - } - - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - count++ - } - - method, methodOriginal := n.method(req.Method) - if methodOriginal != (attribute.KeyValue{}) { - count++ - } - - scheme := n.scheme(req.TLS != nil) - - peer, peerPort := SplitHostPort(req.RemoteAddr) - if peer != "" { - // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a - // file-path that would be interpreted with a sock family. - count++ - if peerPort > 0 { - count++ - } - } - - useragent := req.UserAgent() - if useragent != "" { - count++ - } - - // For client IP, use, in order: - // 1. The value passed in the options - // 2. The value in the X-Forwarded-For header - // 3. The peer address - clientIP := opts.HTTPClientIP - if clientIP == "" { - clientIP = serverClientIP(req.Header.Get("X-Forwarded-For")) - if clientIP == "" { - clientIP = peer - } - } - if clientIP != "" { - count++ - } - - if req.URL != nil && req.URL.Path != "" { - count++ - } - - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" && protoName != "http" { - count++ - } - if protoVersion != "" { - count++ - } - - route := httpRoute(req.Pattern) - if route != "" { - count++ - } - - attrs := make([]attribute.KeyValue, 0, count) - attrs = append(attrs, - semconvNew.ServerAddress(host), - method, - scheme, - ) - - if hostPort > 0 { - attrs = append(attrs, semconvNew.ServerPort(hostPort)) - } - if methodOriginal != (attribute.KeyValue{}) { - attrs = append(attrs, methodOriginal) - } - - if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { - // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a - // file-path that would be interpreted with a sock family. - attrs = append(attrs, semconvNew.NetworkPeerAddress(peer)) - if peerPort > 0 { - attrs = append(attrs, semconvNew.NetworkPeerPort(peerPort)) - } - } - - if useragent != "" { - attrs = append(attrs, semconvNew.UserAgentOriginal(useragent)) - } - - if clientIP != "" { - attrs = append(attrs, semconvNew.ClientAddress(clientIP)) - } - - if req.URL != nil && req.URL.Path != "" { - attrs = append(attrs, semconvNew.URLPath(req.URL.Path)) - } - - if protoName != "" && protoName != "http" { - attrs = append(attrs, semconvNew.NetworkProtocolName(protoName)) - } - if protoVersion != "" { - attrs = append(attrs, semconvNew.NetworkProtocolVersion(protoVersion)) - } - - if route != "" { - attrs = append(attrs, n.Route(route)) - } - - return attrs -} - -func (n CurrentHTTPServer) NetworkTransportAttr(network string) attribute.KeyValue { - switch network { - case "tcp", "tcp4", "tcp6": - return semconvNew.NetworkTransportTCP - case "udp", "udp4", "udp6": - return semconvNew.NetworkTransportUDP - case "unix", "unixgram", "unixpacket": - return semconvNew.NetworkTransportUnix - default: - return semconvNew.NetworkTransportPipe - } -} - -func (n CurrentHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { - if method == "" { - return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} - } - if attr, ok := methodLookup[method]; ok { - return attr, attribute.KeyValue{} - } - - orig := semconvNew.HTTPRequestMethodOriginal(method) - if attr, ok := methodLookup[strings.ToUpper(method)]; ok { - return attr, orig - } - return semconvNew.HTTPRequestMethodGet, orig -} - -func (n CurrentHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive - if https { - return semconvNew.URLScheme("https") - } - return semconvNew.URLScheme("http") -} - -// ResponseTraceAttrs returns trace attributes for telemetry from an HTTP -// response. -// -// If any of the fields in the ResponseTelemetry are not set the attribute will -// be omitted. -func (n CurrentHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { - var count int - - if resp.ReadBytes > 0 { - count++ - } - if resp.WriteBytes > 0 { - count++ - } - if resp.StatusCode > 0 { - count++ - } - - attributes := make([]attribute.KeyValue, 0, count) - - if resp.ReadBytes > 0 { - attributes = append(attributes, - semconvNew.HTTPRequestBodySize(int(resp.ReadBytes)), - ) - } - if resp.WriteBytes > 0 { - attributes = append(attributes, - semconvNew.HTTPResponseBodySize(int(resp.WriteBytes)), - ) - } - if resp.StatusCode > 0 { - attributes = append(attributes, - semconvNew.HTTPResponseStatusCode(resp.StatusCode), - ) - } - - return attributes -} - -// Route returns the attribute for the route. -func (n CurrentHTTPServer) Route(route string) attribute.KeyValue { - return semconvNew.HTTPRoute(route) -} - -func (n CurrentHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Histogram, metric.Int64Histogram, metric.Float64Histogram) { - if meter == nil { - return noop.Int64Histogram{}, noop.Int64Histogram{}, noop.Float64Histogram{} - } - - var err error - requestBodySizeHistogram, err := meter.Int64Histogram( - semconvNew.HTTPServerRequestBodySizeName, - metric.WithUnit(semconvNew.HTTPServerRequestBodySizeUnit), - metric.WithDescription(semconvNew.HTTPServerRequestBodySizeDescription), - ) - handleErr(err) - - responseBodySizeHistogram, err := meter.Int64Histogram( - semconvNew.HTTPServerResponseBodySizeName, - metric.WithUnit(semconvNew.HTTPServerResponseBodySizeUnit), - metric.WithDescription(semconvNew.HTTPServerResponseBodySizeDescription), - ) - handleErr(err) - requestDurationHistogram, err := meter.Float64Histogram( - semconvNew.HTTPServerRequestDurationName, - metric.WithUnit(semconvNew.HTTPServerRequestDurationUnit), - metric.WithDescription(semconvNew.HTTPServerRequestDurationDescription), - metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10), - ) - handleErr(err) - - return requestBodySizeHistogram, responseBodySizeHistogram, requestDurationHistogram -} - -func (n CurrentHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { - num := len(additionalAttributes) + 3 - var host string - var p int - if server == "" { - host, p = SplitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = SplitHostPort(server) - if p < 0 { - _, p = SplitHostPort(req.Host) - } - } - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - num++ - } - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" { - num++ - } - if protoVersion != "" { - num++ - } - - if statusCode > 0 { - num++ - } - - attributes := slices.Grow(additionalAttributes, num) - attributes = append(attributes, - semconvNew.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), - n.scheme(req.TLS != nil), - semconvNew.ServerAddress(host)) - - if hostPort > 0 { - attributes = append(attributes, semconvNew.ServerPort(hostPort)) - } - if protoName != "" { - attributes = append(attributes, semconvNew.NetworkProtocolName(protoName)) - } - if protoVersion != "" { - attributes = append(attributes, semconvNew.NetworkProtocolVersion(protoVersion)) - } - - if statusCode > 0 { - attributes = append(attributes, semconvNew.HTTPResponseStatusCode(statusCode)) - } - return attributes -} - -type CurrentHTTPClient struct{} - -// RequestTraceAttrs returns trace attributes for an HTTP request made by a client. -func (n CurrentHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { - /* - below attributes are returned: - - http.request.method - - http.request.method.original - - url.full - - server.address - - server.port - - network.protocol.name - - network.protocol.version - */ - numOfAttributes := 3 // URL, server address, proto, and method. - - var urlHost string - if req.URL != nil { - urlHost = req.URL.Host - } - var requestHost string - var requestPort int - for _, hostport := range []string{urlHost, req.Header.Get("Host")} { - requestHost, requestPort = SplitHostPort(hostport) - if requestHost != "" || requestPort > 0 { - break - } - } - - eligiblePort := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) - if eligiblePort > 0 { - numOfAttributes++ - } - useragent := req.UserAgent() - if useragent != "" { - numOfAttributes++ - } - - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" && protoName != "http" { - numOfAttributes++ - } - if protoVersion != "" { - numOfAttributes++ - } - - method, originalMethod := n.method(req.Method) - if originalMethod != (attribute.KeyValue{}) { - numOfAttributes++ - } - - attrs := make([]attribute.KeyValue, 0, numOfAttributes) - - attrs = append(attrs, method) - if originalMethod != (attribute.KeyValue{}) { - attrs = append(attrs, originalMethod) - } - - var u string - if req.URL != nil { - // Remove any username/password info that may be in the URL. - userinfo := req.URL.User - req.URL.User = nil - u = req.URL.String() - // Restore any username/password info that was removed. - req.URL.User = userinfo - } - attrs = append(attrs, semconvNew.URLFull(u)) - - attrs = append(attrs, semconvNew.ServerAddress(requestHost)) - if eligiblePort > 0 { - attrs = append(attrs, semconvNew.ServerPort(eligiblePort)) - } - - if protoName != "" && protoName != "http" { - attrs = append(attrs, semconvNew.NetworkProtocolName(protoName)) - } - if protoVersion != "" { - attrs = append(attrs, semconvNew.NetworkProtocolVersion(protoVersion)) - } - - return attrs -} - -// ResponseTraceAttrs returns trace attributes for an HTTP response made by a client. -func (n CurrentHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { - /* - below attributes are returned: - - http.response.status_code - - error.type - */ - var count int - if resp.StatusCode > 0 { - count++ - } - - if isErrorStatusCode(resp.StatusCode) { - count++ - } - - attrs := make([]attribute.KeyValue, 0, count) - if resp.StatusCode > 0 { - attrs = append(attrs, semconvNew.HTTPResponseStatusCode(resp.StatusCode)) - } - - if isErrorStatusCode(resp.StatusCode) { - errorType := strconv.Itoa(resp.StatusCode) - attrs = append(attrs, semconvNew.ErrorTypeKey.String(errorType)) - } - return attrs -} - -func (n CurrentHTTPClient) ErrorType(err error) attribute.KeyValue { - t := reflect.TypeOf(err) - var value string - if t.PkgPath() == "" && t.Name() == "" { - // Likely a builtin type. - value = t.String() - } else { - value = fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) - } - - if value == "" { - return semconvNew.ErrorTypeOther - } - - return semconvNew.ErrorTypeKey.String(value) -} - -func (n CurrentHTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) { - if method == "" { - return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} - } - if attr, ok := methodLookup[method]; ok { - return attr, attribute.KeyValue{} - } - - orig := semconvNew.HTTPRequestMethodOriginal(method) - if attr, ok := methodLookup[strings.ToUpper(method)]; ok { - return attr, orig - } - return semconvNew.HTTPRequestMethodGet, orig -} - -func (n CurrentHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Histogram, metric.Float64Histogram) { - if meter == nil { - return noop.Int64Histogram{}, noop.Float64Histogram{} - } - - var err error - requestBodySize, err := meter.Int64Histogram( - semconvNew.HTTPClientRequestBodySizeName, - metric.WithUnit(semconvNew.HTTPClientRequestBodySizeUnit), - metric.WithDescription(semconvNew.HTTPClientRequestBodySizeDescription), - ) - handleErr(err) - - requestDuration, err := meter.Float64Histogram( - semconvNew.HTTPClientRequestDurationName, - metric.WithUnit(semconvNew.HTTPClientRequestDurationUnit), - metric.WithDescription(semconvNew.HTTPClientRequestDurationDescription), - metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10), - ) - handleErr(err) - - return requestBodySize, requestDuration -} - -func (n CurrentHTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { - num := len(additionalAttributes) + 2 - var h string - if req.URL != nil { - h = req.URL.Host - } - var requestHost string - var requestPort int - for _, hostport := range []string{h, req.Header.Get("Host")} { - requestHost, requestPort = SplitHostPort(hostport) - if requestHost != "" || requestPort > 0 { - break - } - } - - port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) - if port > 0 { - num++ - } - - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" { - num++ - } - if protoVersion != "" { - num++ - } - - if statusCode > 0 { - num++ - } - - attributes := slices.Grow(additionalAttributes, num) - attributes = append(attributes, - semconvNew.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), - semconvNew.ServerAddress(requestHost), - n.scheme(req), - ) - - if port > 0 { - attributes = append(attributes, semconvNew.ServerPort(port)) - } - if protoName != "" { - attributes = append(attributes, semconvNew.NetworkProtocolName(protoName)) - } - if protoVersion != "" { - attributes = append(attributes, semconvNew.NetworkProtocolVersion(protoVersion)) - } - - if statusCode > 0 { - attributes = append(attributes, semconvNew.HTTPResponseStatusCode(statusCode)) - } - return attributes -} - -// TraceAttributes returns attributes for httptrace. -func (n CurrentHTTPClient) TraceAttributes(host string) []attribute.KeyValue { - return []attribute.KeyValue{ - semconvNew.ServerAddress(host), - } -} - -func (n CurrentHTTPClient) scheme(req *http.Request) attribute.KeyValue { - if req.URL != nil && req.URL.Scheme != "" { - return semconvNew.URLScheme(req.URL.Scheme) - } - if req.TLS != nil { - return semconvNew.URLScheme("https") - } - return semconvNew.URLScheme("http") -} - -func isErrorStatusCode(code int) bool { - return code >= 400 || code < 100 -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/server.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/server.go new file mode 100644 index 000000000..5ae6a0738 --- /dev/null +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/server.go @@ -0,0 +1,403 @@ +// Code generated by gotmpl. DO NOT MODIFY. +// source: internal/shared/semconv/server.go.tmpl + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package semconv provides OpenTelemetry semantic convention types and +// functionality. +package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" + +import ( + "context" + "fmt" + "net/http" + "slices" + "strings" + "sync" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/semconv/v1.37.0" + "go.opentelemetry.io/otel/semconv/v1.37.0/httpconv" +) + +type RequestTraceAttrsOpts struct { + // If set, this is used as value for the "http.client_ip" attribute. + HTTPClientIP string +} + +type ResponseTelemetry struct { + StatusCode int + ReadBytes int64 + ReadError error + WriteBytes int64 + WriteError error +} + +type HTTPServer struct{ + requestBodySizeHistogram httpconv.ServerRequestBodySize + responseBodySizeHistogram httpconv.ServerResponseBodySize + requestDurationHistogram httpconv.ServerRequestDuration +} + +func NewHTTPServer(meter metric.Meter) HTTPServer { + server := HTTPServer{} + + var err error + server.requestBodySizeHistogram, err = httpconv.NewServerRequestBodySize(meter) + handleErr(err) + + server.responseBodySizeHistogram, err = httpconv.NewServerResponseBodySize(meter) + handleErr(err) + + server.requestDurationHistogram, err = httpconv.NewServerRequestDuration( + meter, + metric.WithExplicitBucketBoundaries( + 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, + 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10, + ), + ) + handleErr(err) + return server +} + +// Status returns a span status code and message for an HTTP status code +// value returned by a server. Status codes in the 400-499 range are not +// returned as errors. +func (n HTTPServer) Status(code int) (codes.Code, string) { + if code < 100 || code >= 600 { + return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) + } + if code >= 500 { + return codes.Error, "" + } + return codes.Unset, "" +} + +// RequestTraceAttrs returns trace attributes for an HTTP request received by a +// server. +// +// The server must be the primary server name if it is known. For example this +// would be the ServerName directive +// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache +// server, and the server_name directive +// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an +// nginx server. More generically, the primary server name would be the host +// header value that matches the default virtual host of an HTTP server. It +// should include the host identifier and if a port is used to route to the +// server that port identifier should be included as an appropriate port +// suffix. +// +// If the primary server name is not known, server should be an empty string. +// The req Host will be used to determine the server instead. +func (n HTTPServer) RequestTraceAttrs(server string, req *http.Request, opts RequestTraceAttrsOpts) []attribute.KeyValue { + count := 3 // ServerAddress, Method, Scheme + + var host string + var p int + if server == "" { + host, p = SplitHostPort(req.Host) + } else { + // Prioritize the primary server name. + host, p = SplitHostPort(server) + if p < 0 { + _, p = SplitHostPort(req.Host) + } + } + + hostPort := requiredHTTPPort(req.TLS != nil, p) + if hostPort > 0 { + count++ + } + + method, methodOriginal := n.method(req.Method) + if methodOriginal != (attribute.KeyValue{}) { + count++ + } + + scheme := n.scheme(req.TLS != nil) + + peer, peerPort := SplitHostPort(req.RemoteAddr) + if peer != "" { + // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a + // file-path that would be interpreted with a sock family. + count++ + if peerPort > 0 { + count++ + } + } + + useragent := req.UserAgent() + if useragent != "" { + count++ + } + + // For client IP, use, in order: + // 1. The value passed in the options + // 2. The value in the X-Forwarded-For header + // 3. The peer address + clientIP := opts.HTTPClientIP + if clientIP == "" { + clientIP = serverClientIP(req.Header.Get("X-Forwarded-For")) + if clientIP == "" { + clientIP = peer + } + } + if clientIP != "" { + count++ + } + + if req.URL != nil && req.URL.Path != "" { + count++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" && protoName != "http" { + count++ + } + if protoVersion != "" { + count++ + } + + route := httpRoute(req.Pattern) + if route != "" { + count++ + } + + attrs := make([]attribute.KeyValue, 0, count) + attrs = append(attrs, + semconv.ServerAddress(host), + method, + scheme, + ) + + if hostPort > 0 { + attrs = append(attrs, semconv.ServerPort(hostPort)) + } + if methodOriginal != (attribute.KeyValue{}) { + attrs = append(attrs, methodOriginal) + } + + if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { + // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a + // file-path that would be interpreted with a sock family. + attrs = append(attrs, semconv.NetworkPeerAddress(peer)) + if peerPort > 0 { + attrs = append(attrs, semconv.NetworkPeerPort(peerPort)) + } + } + + if useragent != "" { + attrs = append(attrs, semconv.UserAgentOriginal(useragent)) + } + + if clientIP != "" { + attrs = append(attrs, semconv.ClientAddress(clientIP)) + } + + if req.URL != nil && req.URL.Path != "" { + attrs = append(attrs, semconv.URLPath(req.URL.Path)) + } + + if protoName != "" && protoName != "http" { + attrs = append(attrs, semconv.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion)) + } + + if route != "" { + attrs = append(attrs, n.Route(route)) + } + + return attrs +} + +func (s HTTPServer) NetworkTransportAttr(network string) []attribute.KeyValue { + attr := semconv.NetworkTransportPipe + switch network { + case "tcp", "tcp4", "tcp6": + attr = semconv.NetworkTransportTCP + case "udp", "udp4", "udp6": + attr = semconv.NetworkTransportUDP + case "unix", "unixgram", "unixpacket": + attr = semconv.NetworkTransportUnix + } + + return []attribute.KeyValue{attr} +} + +type ServerMetricData struct { + ServerName string + ResponseSize int64 + + MetricData + MetricAttributes +} + +type MetricAttributes struct { + Req *http.Request + StatusCode int + Route string + AdditionalAttributes []attribute.KeyValue +} + +type MetricData struct { + RequestSize int64 + + // The request duration, in milliseconds + ElapsedTime float64 +} + +var ( + metricAddOptionPool = &sync.Pool{ + New: func() any { + return &[]metric.AddOption{} + }, + } + + metricRecordOptionPool = &sync.Pool{ + New: func() any { + return &[]metric.RecordOption{} + }, + } +) + +func (n HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { + attributes := n.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.Route, md.AdditionalAttributes) + o := metric.WithAttributeSet(attribute.NewSet(attributes...)) + recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption) + *recordOpts = append(*recordOpts, o) + n.requestBodySizeHistogram.Inst().Record(ctx, md.RequestSize, *recordOpts...) + n.responseBodySizeHistogram.Inst().Record(ctx, md.ResponseSize, *recordOpts...) + n.requestDurationHistogram.Inst().Record(ctx, md.ElapsedTime/1000.0, o) + *recordOpts = (*recordOpts)[:0] + metricRecordOptionPool.Put(recordOpts) +} + +func (n HTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { + if method == "" { + return semconv.HTTPRequestMethodGet, attribute.KeyValue{} + } + if attr, ok := methodLookup[method]; ok { + return attr, attribute.KeyValue{} + } + + orig := semconv.HTTPRequestMethodOriginal(method) + if attr, ok := methodLookup[strings.ToUpper(method)]; ok { + return attr, orig + } + return semconv.HTTPRequestMethodGet, orig +} + +func (n HTTPServer) scheme(https bool) attribute.KeyValue { //nolint:revive // ignore linter + if https { + return semconv.URLScheme("https") + } + return semconv.URLScheme("http") +} + +// ResponseTraceAttrs returns trace attributes for telemetry from an HTTP +// response. +// +// If any of the fields in the ResponseTelemetry are not set the attribute will +// be omitted. +func (n HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { + var count int + + if resp.ReadBytes > 0 { + count++ + } + if resp.WriteBytes > 0 { + count++ + } + if resp.StatusCode > 0 { + count++ + } + + attributes := make([]attribute.KeyValue, 0, count) + + if resp.ReadBytes > 0 { + attributes = append(attributes, + semconv.HTTPRequestBodySize(int(resp.ReadBytes)), + ) + } + if resp.WriteBytes > 0 { + attributes = append(attributes, + semconv.HTTPResponseBodySize(int(resp.WriteBytes)), + ) + } + if resp.StatusCode > 0 { + attributes = append(attributes, + semconv.HTTPResponseStatusCode(resp.StatusCode), + ) + } + + return attributes +} + +// Route returns the attribute for the route. +func (n HTTPServer) Route(route string) attribute.KeyValue { + return semconv.HTTPRoute(route) +} + +func (n HTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, route string, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + num := len(additionalAttributes) + 3 + var host string + var p int + if server == "" { + host, p = SplitHostPort(req.Host) + } else { + // Prioritize the primary server name. + host, p = SplitHostPort(server) + if p < 0 { + _, p = SplitHostPort(req.Host) + } + } + hostPort := requiredHTTPPort(req.TLS != nil, p) + if hostPort > 0 { + num++ + } + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" { + num++ + } + if protoVersion != "" { + num++ + } + + if statusCode > 0 { + num++ + } + + if route != "" { + num++ + } + + attributes := slices.Grow(additionalAttributes, num) + attributes = append(attributes, + semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)), + n.scheme(req.TLS != nil), + semconv.ServerAddress(host)) + + if hostPort > 0 { + attributes = append(attributes, semconv.ServerPort(hostPort)) + } + if protoName != "" { + attributes = append(attributes, semconv.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attributes = append(attributes, semconv.NetworkProtocolVersion(protoVersion)) + } + + if statusCode > 0 { + attributes = append(attributes, semconv.HTTPResponseStatusCode(statusCode)) + } + + if route != "" { + attributes = append(attributes, semconv.HTTPRoute(route)) + } + return attributes +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go index bc1f7751d..96422ad1e 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go @@ -14,7 +14,7 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" - semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" + semconvNew "go.opentelemetry.io/otel/semconv/v1.37.0" ) // SplitHostPort splits a network address hostport of the form "host", @@ -53,10 +53,10 @@ func SplitHostPort(hostport string) (host string, port int) { if err != nil { return } - return host, int(p) // nolint: gosec // Byte size checked 16 above. + return host, int(p) //nolint:gosec // Byte size checked 16 above. } -func requiredHTTPPort(https bool, port int) int { // nolint:revive +func requiredHTTPPort(https bool, port int) int { //nolint:revive // ignore linter if https { if port > 0 && port != 443 { return port diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go deleted file mode 100644 index ba7fccf1e..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go +++ /dev/null @@ -1,273 +0,0 @@ -// Code generated by gotmpl. DO NOT MODIFY. -// source: internal/shared/semconv/v120.0.go.tmpl - -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - -import ( - "errors" - "io" - "net/http" - "slices" - - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/noop" - semconv "go.opentelemetry.io/otel/semconv/v1.20.0" -) - -type OldHTTPServer struct{} - -// RequestTraceAttrs returns trace attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -func (o OldHTTPServer) RequestTraceAttrs(server string, req *http.Request, attrs []attribute.KeyValue) []attribute.KeyValue { - return semconvutil.HTTPServerRequest(server, req, semconvutil.HTTPServerRequestOptions{}, attrs) -} - -func (o OldHTTPServer) NetworkTransportAttr(network string) attribute.KeyValue { - return semconvutil.NetTransport(network) -} - -// ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. -// -// If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (o OldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry, attributes []attribute.KeyValue) []attribute.KeyValue { - if resp.ReadBytes > 0 { - attributes = append(attributes, semconv.HTTPRequestContentLength(int(resp.ReadBytes))) - } - if resp.ReadError != nil && !errors.Is(resp.ReadError, io.EOF) { - // This is not in the semantic conventions, but is historically provided - attributes = append(attributes, attribute.String("http.read_error", resp.ReadError.Error())) - } - if resp.WriteBytes > 0 { - attributes = append(attributes, semconv.HTTPResponseContentLength(int(resp.WriteBytes))) - } - if resp.StatusCode > 0 { - attributes = append(attributes, semconv.HTTPStatusCode(resp.StatusCode)) - } - if resp.WriteError != nil && !errors.Is(resp.WriteError, io.EOF) { - // This is not in the semantic conventions, but is historically provided - attributes = append(attributes, attribute.String("http.write_error", resp.WriteError.Error())) - } - - return attributes -} - -// Route returns the attribute for the route. -func (o OldHTTPServer) Route(route string) attribute.KeyValue { - return semconv.HTTPRoute(route) -} - -// HTTPStatusCode returns the attribute for the HTTP status code. -// This is a temporary function needed by metrics. This will be removed when MetricsRequest is added. -func HTTPStatusCode(status int) attribute.KeyValue { - return semconv.HTTPStatusCode(status) -} - -// Server HTTP metrics. -const ( - serverRequestSize = "http.server.request.size" // Incoming request bytes total - serverResponseSize = "http.server.response.size" // Incoming response bytes total - serverDuration = "http.server.duration" // Incoming end to end duration, milliseconds -) - -func (h OldHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { - if meter == nil { - return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} - } - var err error - requestBytesCounter, err := meter.Int64Counter( - serverRequestSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP request messages."), - ) - handleErr(err) - - responseBytesCounter, err := meter.Int64Counter( - serverResponseSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP response messages."), - ) - handleErr(err) - - serverLatencyMeasure, err := meter.Float64Histogram( - serverDuration, - metric.WithUnit("ms"), - metric.WithDescription("Measures the duration of inbound HTTP requests."), - ) - handleErr(err) - - return requestBytesCounter, responseBytesCounter, serverLatencyMeasure -} - -func (o OldHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { - n := len(additionalAttributes) + 3 - var host string - var p int - if server == "" { - host, p = SplitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = SplitHostPort(server) - if p < 0 { - _, p = SplitHostPort(req.Host) - } - } - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - n++ - } - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" { - n++ - } - if protoVersion != "" { - n++ - } - - if statusCode > 0 { - n++ - } - - attributes := slices.Grow(additionalAttributes, n) - attributes = append(attributes, - semconv.HTTPMethod(standardizeHTTPMethod(req.Method)), - o.scheme(req.TLS != nil), - semconv.NetHostName(host)) - - if hostPort > 0 { - attributes = append(attributes, semconv.NetHostPort(hostPort)) - } - if protoName != "" { - attributes = append(attributes, semconv.NetProtocolName(protoName)) - } - if protoVersion != "" { - attributes = append(attributes, semconv.NetProtocolVersion(protoVersion)) - } - - if statusCode > 0 { - attributes = append(attributes, semconv.HTTPStatusCode(statusCode)) - } - return attributes -} - -func (o OldHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive - if https { - return semconv.HTTPSchemeHTTPS - } - return semconv.HTTPSchemeHTTP -} - -type OldHTTPClient struct{} - -func (o OldHTTPClient) RequestTraceAttrs(req *http.Request, attrs []attribute.KeyValue) []attribute.KeyValue { - return semconvutil.HTTPClientRequest(req, attrs) -} - -func (o OldHTTPClient) ResponseTraceAttrs(resp *http.Response, attrs []attribute.KeyValue) []attribute.KeyValue { - return semconvutil.HTTPClientResponse(resp, attrs) -} - -func (o OldHTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.method string - http.status_code int - net.peer.name string - net.peer.port int - */ - - n := 2 // method, peer name. - var h string - if req.URL != nil { - h = req.URL.Host - } - var requestHost string - var requestPort int - for _, hostport := range []string{h, req.Header.Get("Host")} { - requestHost, requestPort = SplitHostPort(hostport) - if requestHost != "" || requestPort > 0 { - break - } - } - - port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) - if port > 0 { - n++ - } - - if statusCode > 0 { - n++ - } - - attributes := slices.Grow(additionalAttributes, n) - attributes = append(attributes, - semconv.HTTPMethod(standardizeHTTPMethod(req.Method)), - semconv.NetPeerName(requestHost), - ) - - if port > 0 { - attributes = append(attributes, semconv.NetPeerPort(port)) - } - - if statusCode > 0 { - attributes = append(attributes, semconv.HTTPStatusCode(statusCode)) - } - return attributes -} - -// Client HTTP metrics. -const ( - clientRequestSize = "http.client.request.size" // Incoming request bytes total - clientResponseSize = "http.client.response.size" // Incoming response bytes total - clientDuration = "http.client.duration" // Incoming end to end duration, milliseconds -) - -func (o OldHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { - if meter == nil { - return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} - } - requestBytesCounter, err := meter.Int64Counter( - clientRequestSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP request messages."), - ) - handleErr(err) - - responseBytesCounter, err := meter.Int64Counter( - clientResponseSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP response messages."), - ) - handleErr(err) - - latencyMeasure, err := meter.Float64Histogram( - clientDuration, - metric.WithUnit("ms"), - metric.WithDescription("Measures the duration of outbound HTTP requests."), - ) - handleErr(err) - - return requestBytesCounter, responseBytesCounter, latencyMeasure -} - -// TraceAttributes returns attributes for httptrace. -func (c OldHTTPClient) TraceAttributes(host string, attrs []attribute.KeyValue) []attribute.KeyValue { - return append(attrs, semconv.NetHostName(host)) -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/gen.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/gen.go deleted file mode 100644 index 7aa5f99e8..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/gen.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" - -// Generate semconvutil package: -//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/httpconv_test.go.tmpl "--data={}" --out=httpconv_test.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/httpconv.go.tmpl "--data={}" --out=httpconv.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/netconv_test.go.tmpl "--data={}" --out=netconv_test.go -//go:generate gotmpl --body=../../../../../../internal/shared/semconvutil/netconv.go.tmpl "--data={}" --out=netconv.go diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/httpconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/httpconv.go deleted file mode 100644 index b99735479..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/httpconv.go +++ /dev/null @@ -1,594 +0,0 @@ -// Code generated by gotmpl. DO NOT MODIFY. -// source: internal/shared/semconvutil/httpconv.go.tmpl - -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconvutil provides OpenTelemetry semantic convention utilities. -package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" - -import ( - "fmt" - "net/http" - "slices" - "strings" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - semconv "go.opentelemetry.io/otel/semconv/v1.20.0" -) - -type HTTPServerRequestOptions struct { - // If set, this is used as value for the "http.client_ip" attribute. - HTTPClientIP string -} - -// HTTPClientResponse returns trace attributes for an HTTP response received by a -// client from a server. It will return the following attributes if the related -// values are defined in resp: "http.status.code", -// "http.response_content_length". -// -// This does not add all OpenTelemetry required attributes for an HTTP event, -// it assumes ClientRequest was used to create the span with a complete set of -// attributes. If a complete set of attributes can be generated using the -// request contained in resp. For example: -// -// HTTPClientResponse(resp, ClientRequest(resp.Request))) -func HTTPClientResponse(resp *http.Response, attrs []attribute.KeyValue) []attribute.KeyValue { - return hc.ClientResponse(resp, attrs) -} - -// HTTPClientRequest returns trace attributes for an HTTP request made by a client. -// The following attributes are always returned: "http.url", "http.method", -// "net.peer.name". The following attributes are returned if the related values -// are defined in req: "net.peer.port", "user_agent.original", -// "http.request_content_length". -func HTTPClientRequest(req *http.Request, attrs []attribute.KeyValue) []attribute.KeyValue { - return hc.ClientRequest(req, attrs) -} - -// HTTPClientRequestMetrics returns metric attributes for an HTTP request made by a client. -// The following attributes are always returned: "http.method", "net.peer.name". -// The following attributes are returned if the -// related values are defined in req: "net.peer.port". -func HTTPClientRequestMetrics(req *http.Request) []attribute.KeyValue { - return hc.ClientRequestMetrics(req) -} - -// HTTPClientStatus returns a span status code and message for an HTTP status code -// value received by a client. -func HTTPClientStatus(code int) (codes.Code, string) { - return hc.ClientStatus(code) -} - -// HTTPServerRequest returns trace attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -// -// The following attributes are always returned: "http.method", "http.scheme", -// "http.target", "net.host.name". The following attributes are returned if -// they related values are defined in req: "net.host.port", "net.sock.peer.addr", -// "net.sock.peer.port", "user_agent.original", "http.client_ip". -func HTTPServerRequest(server string, req *http.Request, opts HTTPServerRequestOptions, attrs []attribute.KeyValue) []attribute.KeyValue { - return hc.ServerRequest(server, req, opts, attrs) -} - -// HTTPServerRequestMetrics returns metric attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -// -// The following attributes are always returned: "http.method", "http.scheme", -// "net.host.name". The following attributes are returned if they related -// values are defined in req: "net.host.port". -func HTTPServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue { - return hc.ServerRequestMetrics(server, req) -} - -// HTTPServerStatus returns a span status code and message for an HTTP status code -// value returned by a server. Status codes in the 400-499 range are not -// returned as errors. -func HTTPServerStatus(code int) (codes.Code, string) { - return hc.ServerStatus(code) -} - -// httpConv are the HTTP semantic convention attributes defined for a version -// of the OpenTelemetry specification. -type httpConv struct { - NetConv *netConv - - HTTPClientIPKey attribute.Key - HTTPMethodKey attribute.Key - HTTPRequestContentLengthKey attribute.Key - HTTPResponseContentLengthKey attribute.Key - HTTPRouteKey attribute.Key - HTTPSchemeHTTP attribute.KeyValue - HTTPSchemeHTTPS attribute.KeyValue - HTTPStatusCodeKey attribute.Key - HTTPTargetKey attribute.Key - HTTPURLKey attribute.Key - UserAgentOriginalKey attribute.Key -} - -var hc = &httpConv{ - NetConv: nc, - - HTTPClientIPKey: semconv.HTTPClientIPKey, - HTTPMethodKey: semconv.HTTPMethodKey, - HTTPRequestContentLengthKey: semconv.HTTPRequestContentLengthKey, - HTTPResponseContentLengthKey: semconv.HTTPResponseContentLengthKey, - HTTPRouteKey: semconv.HTTPRouteKey, - HTTPSchemeHTTP: semconv.HTTPSchemeHTTP, - HTTPSchemeHTTPS: semconv.HTTPSchemeHTTPS, - HTTPStatusCodeKey: semconv.HTTPStatusCodeKey, - HTTPTargetKey: semconv.HTTPTargetKey, - HTTPURLKey: semconv.HTTPURLKey, - UserAgentOriginalKey: semconv.UserAgentOriginalKey, -} - -// ClientResponse returns attributes for an HTTP response received by a client -// from a server. The following attributes are returned if the related values -// are defined in resp: "http.status.code", "http.response_content_length". -// -// This does not add all OpenTelemetry required attributes for an HTTP event, -// it assumes ClientRequest was used to create the span with a complete set of -// attributes. If a complete set of attributes can be generated using the -// request contained in resp. For example: -// -// ClientResponse(resp, ClientRequest(resp.Request)) -func (c *httpConv) ClientResponse(resp *http.Response, attrs []attribute.KeyValue) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.status_code int - http.response_content_length int - */ - var n int - if resp.StatusCode > 0 { - n++ - } - if resp.ContentLength > 0 { - n++ - } - if n == 0 { - return attrs - } - - attrs = slices.Grow(attrs, n) - if resp.StatusCode > 0 { - attrs = append(attrs, c.HTTPStatusCodeKey.Int(resp.StatusCode)) - } - if resp.ContentLength > 0 { - attrs = append(attrs, c.HTTPResponseContentLengthKey.Int(int(resp.ContentLength))) - } - return attrs -} - -// ClientRequest returns attributes for an HTTP request made by a client. The -// following attributes are always returned: "http.url", "http.method", -// "net.peer.name". The following attributes are returned if the related values -// are defined in req: "net.peer.port", "user_agent.original", -// "http.request_content_length", "user_agent.original". -func (c *httpConv) ClientRequest(req *http.Request, attrs []attribute.KeyValue) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.method string - user_agent.original string - http.url string - net.peer.name string - net.peer.port int - http.request_content_length int - */ - - /* The following semantic conventions are not returned: - http.status_code This requires the response. See ClientResponse. - http.response_content_length This requires the response. See ClientResponse. - net.sock.family This requires the socket used. - net.sock.peer.addr This requires the socket used. - net.sock.peer.name This requires the socket used. - net.sock.peer.port This requires the socket used. - http.resend_count This is something outside of a single request. - net.protocol.name The value is the Request is ignored, and the go client will always use "http". - net.protocol.version The value in the Request is ignored, and the go client will always use 1.1 or 2.0. - */ - n := 3 // URL, peer name, proto, and method. - var h string - if req.URL != nil { - h = req.URL.Host - } - peer, p := firstHostPort(h, req.Header.Get("Host")) - port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", p) - if port > 0 { - n++ - } - useragent := req.UserAgent() - if useragent != "" { - n++ - } - if req.ContentLength > 0 { - n++ - } - - attrs = slices.Grow(attrs, n) - attrs = append(attrs, c.method(req.Method)) - - var u string - if req.URL != nil { - // Remove any username/password info that may be in the URL. - userinfo := req.URL.User - req.URL.User = nil - u = req.URL.String() - // Restore any username/password info that was removed. - req.URL.User = userinfo - } - attrs = append(attrs, c.HTTPURLKey.String(u)) - - attrs = append(attrs, c.NetConv.PeerName(peer)) - if port > 0 { - attrs = append(attrs, c.NetConv.PeerPort(port)) - } - - if useragent != "" { - attrs = append(attrs, c.UserAgentOriginalKey.String(useragent)) - } - - if l := req.ContentLength; l > 0 { - attrs = append(attrs, c.HTTPRequestContentLengthKey.Int64(l)) - } - - return attrs -} - -// ClientRequestMetrics returns metric attributes for an HTTP request made by a client. The -// following attributes are always returned: "http.method", "net.peer.name". -// The following attributes are returned if the related values -// are defined in req: "net.peer.port". -func (c *httpConv) ClientRequestMetrics(req *http.Request) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.method string - net.peer.name string - net.peer.port int - */ - - n := 2 // method, peer name. - var h string - if req.URL != nil { - h = req.URL.Host - } - peer, p := firstHostPort(h, req.Header.Get("Host")) - port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", p) - if port > 0 { - n++ - } - - attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.method(req.Method), c.NetConv.PeerName(peer)) - - if port > 0 { - attrs = append(attrs, c.NetConv.PeerPort(port)) - } - - return attrs -} - -// ServerRequest returns attributes for an HTTP request received by a server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -// -// The following attributes are always returned: "http.method", "http.scheme", -// "http.target", "net.host.name". The following attributes are returned if they -// related values are defined in req: "net.host.port", "net.sock.peer.addr", -// "net.sock.peer.port", "user_agent.original", "http.client_ip", -// "net.protocol.name", "net.protocol.version". -func (c *httpConv) ServerRequest(server string, req *http.Request, opts HTTPServerRequestOptions, attrs []attribute.KeyValue) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.method string - http.scheme string - net.host.name string - net.host.port int - net.sock.peer.addr string - net.sock.peer.port int - user_agent.original string - http.client_ip string - net.protocol.name string Note: not set if the value is "http". - net.protocol.version string - http.target string Note: doesn't include the query parameter. - */ - - /* The following semantic conventions are not returned: - http.status_code This requires the response. - http.request_content_length This requires the len() of body, which can mutate it. - http.response_content_length This requires the response. - http.route This is not available. - net.sock.peer.name This would require a DNS lookup. - net.sock.host.addr The request doesn't have access to the underlying socket. - net.sock.host.port The request doesn't have access to the underlying socket. - - */ - n := 4 // Method, scheme, proto, and host name. - var host string - var p int - if server == "" { - host, p = splitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = splitHostPort(server) - if p < 0 { - _, p = splitHostPort(req.Host) - } - } - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - n++ - } - peer, peerPort := splitHostPort(req.RemoteAddr) - if peer != "" { - n++ - if peerPort > 0 { - n++ - } - } - useragent := req.UserAgent() - if useragent != "" { - n++ - } - - // For client IP, use, in order: - // 1. The value passed in the options - // 2. The value in the X-Forwarded-For header - // 3. The peer address - clientIP := opts.HTTPClientIP - if clientIP == "" { - clientIP = serverClientIP(req.Header.Get("X-Forwarded-For")) - if clientIP == "" { - clientIP = peer - } - } - if clientIP != "" { - n++ - } - - var target string - if req.URL != nil { - target = req.URL.Path - if target != "" { - n++ - } - } - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" && protoName != "http" { - n++ - } - if protoVersion != "" { - n++ - } - - attrs = slices.Grow(attrs, n) - - attrs = append(attrs, c.method(req.Method)) - attrs = append(attrs, c.scheme(req.TLS != nil)) - attrs = append(attrs, c.NetConv.HostName(host)) - - if hostPort > 0 { - attrs = append(attrs, c.NetConv.HostPort(hostPort)) - } - - if peer != "" { - // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a - // file-path that would be interpreted with a sock family. - attrs = append(attrs, c.NetConv.SockPeerAddr(peer)) - if peerPort > 0 { - attrs = append(attrs, c.NetConv.SockPeerPort(peerPort)) - } - } - - if useragent != "" { - attrs = append(attrs, c.UserAgentOriginalKey.String(useragent)) - } - - if clientIP != "" { - attrs = append(attrs, c.HTTPClientIPKey.String(clientIP)) - } - - if target != "" { - attrs = append(attrs, c.HTTPTargetKey.String(target)) - } - - if protoName != "" && protoName != "http" { - attrs = append(attrs, c.NetConv.NetProtocolName.String(protoName)) - } - if protoVersion != "" { - attrs = append(attrs, c.NetConv.NetProtocolVersion.String(protoVersion)) - } - - return attrs -} - -// ServerRequestMetrics returns metric attributes for an HTTP request received -// by a server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -// -// The following attributes are always returned: "http.method", "http.scheme", -// "net.host.name". The following attributes are returned if they related -// values are defined in req: "net.host.port". -func (c *httpConv) ServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue { - /* The following semantic conventions are returned if present: - http.scheme string - http.route string - http.method string - http.status_code int - net.host.name string - net.host.port int - net.protocol.name string Note: not set if the value is "http". - net.protocol.version string - */ - - n := 3 // Method, scheme, and host name. - var host string - var p int - if server == "" { - host, p = splitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = splitHostPort(server) - if p < 0 { - _, p = splitHostPort(req.Host) - } - } - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - n++ - } - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" { - n++ - } - if protoVersion != "" { - n++ - } - - attrs := make([]attribute.KeyValue, 0, n) - - attrs = append(attrs, c.methodMetric(req.Method)) - attrs = append(attrs, c.scheme(req.TLS != nil)) - attrs = append(attrs, c.NetConv.HostName(host)) - - if hostPort > 0 { - attrs = append(attrs, c.NetConv.HostPort(hostPort)) - } - if protoName != "" { - attrs = append(attrs, c.NetConv.NetProtocolName.String(protoName)) - } - if protoVersion != "" { - attrs = append(attrs, c.NetConv.NetProtocolVersion.String(protoVersion)) - } - - return attrs -} - -func (c *httpConv) method(method string) attribute.KeyValue { - if method == "" { - return c.HTTPMethodKey.String(http.MethodGet) - } - return c.HTTPMethodKey.String(method) -} - -func (c *httpConv) methodMetric(method string) attribute.KeyValue { - method = strings.ToUpper(method) - switch method { - case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: - default: - method = "_OTHER" - } - return c.HTTPMethodKey.String(method) -} - -func (c *httpConv) scheme(https bool) attribute.KeyValue { // nolint:revive - if https { - return c.HTTPSchemeHTTPS - } - return c.HTTPSchemeHTTP -} - -func serverClientIP(xForwardedFor string) string { - if idx := strings.Index(xForwardedFor, ","); idx >= 0 { - xForwardedFor = xForwardedFor[:idx] - } - return xForwardedFor -} - -func requiredHTTPPort(https bool, port int) int { // nolint:revive - if https { - if port > 0 && port != 443 { - return port - } - } else { - if port > 0 && port != 80 { - return port - } - } - return -1 -} - -// Return the request host and port from the first non-empty source. -func firstHostPort(source ...string) (host string, port int) { - for _, hostport := range source { - host, port = splitHostPort(hostport) - if host != "" || port > 0 { - break - } - } - return -} - -// ClientStatus returns a span status code and message for an HTTP status code -// value received by a client. -func (c *httpConv) ClientStatus(code int) (codes.Code, string) { - if code < 100 || code >= 600 { - return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) - } - if code >= 400 { - return codes.Error, "" - } - return codes.Unset, "" -} - -// ServerStatus returns a span status code and message for an HTTP status code -// value returned by a server. Status codes in the 400-499 range are not -// returned as errors. -func (c *httpConv) ServerStatus(code int) (codes.Code, string) { - if code < 100 || code >= 600 { - return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) - } - if code >= 500 { - return codes.Error, "" - } - return codes.Unset, "" -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go deleted file mode 100644 index df97255e4..000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go +++ /dev/null @@ -1,214 +0,0 @@ -// Code generated by gotmpl. DO NOT MODIFY. -// source: internal/shared/semconvutil/netconv.go.tmpl - -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconvutil // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" - -import ( - "net" - "strconv" - "strings" - - "go.opentelemetry.io/otel/attribute" - semconv "go.opentelemetry.io/otel/semconv/v1.20.0" -) - -// NetTransport returns a trace attribute describing the transport protocol of the -// passed network. See the net.Dial for information about acceptable network -// values. -func NetTransport(network string) attribute.KeyValue { - return nc.Transport(network) -} - -// netConv are the network semantic convention attributes defined for a version -// of the OpenTelemetry specification. -type netConv struct { - NetHostNameKey attribute.Key - NetHostPortKey attribute.Key - NetPeerNameKey attribute.Key - NetPeerPortKey attribute.Key - NetProtocolName attribute.Key - NetProtocolVersion attribute.Key - NetSockFamilyKey attribute.Key - NetSockPeerAddrKey attribute.Key - NetSockPeerPortKey attribute.Key - NetSockHostAddrKey attribute.Key - NetSockHostPortKey attribute.Key - NetTransportOther attribute.KeyValue - NetTransportTCP attribute.KeyValue - NetTransportUDP attribute.KeyValue - NetTransportInProc attribute.KeyValue -} - -var nc = &netConv{ - NetHostNameKey: semconv.NetHostNameKey, - NetHostPortKey: semconv.NetHostPortKey, - NetPeerNameKey: semconv.NetPeerNameKey, - NetPeerPortKey: semconv.NetPeerPortKey, - NetProtocolName: semconv.NetProtocolNameKey, - NetProtocolVersion: semconv.NetProtocolVersionKey, - NetSockFamilyKey: semconv.NetSockFamilyKey, - NetSockPeerAddrKey: semconv.NetSockPeerAddrKey, - NetSockPeerPortKey: semconv.NetSockPeerPortKey, - NetSockHostAddrKey: semconv.NetSockHostAddrKey, - NetSockHostPortKey: semconv.NetSockHostPortKey, - NetTransportOther: semconv.NetTransportOther, - NetTransportTCP: semconv.NetTransportTCP, - NetTransportUDP: semconv.NetTransportUDP, - NetTransportInProc: semconv.NetTransportInProc, -} - -func (c *netConv) Transport(network string) attribute.KeyValue { - switch network { - case "tcp", "tcp4", "tcp6": - return c.NetTransportTCP - case "udp", "udp4", "udp6": - return c.NetTransportUDP - case "unix", "unixgram", "unixpacket": - return c.NetTransportInProc - default: - // "ip:*", "ip4:*", and "ip6:*" all are considered other. - return c.NetTransportOther - } -} - -// Host returns attributes for a network host address. -func (c *netConv) Host(address string) []attribute.KeyValue { - h, p := splitHostPort(address) - var n int - if h != "" { - n++ - if p > 0 { - n++ - } - } - - if n == 0 { - return nil - } - - attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.HostName(h)) - if p > 0 { - attrs = append(attrs, c.HostPort(p)) - } - return attrs -} - -func (c *netConv) HostName(name string) attribute.KeyValue { - return c.NetHostNameKey.String(name) -} - -func (c *netConv) HostPort(port int) attribute.KeyValue { - return c.NetHostPortKey.Int(port) -} - -func family(network, address string) string { - switch network { - case "unix", "unixgram", "unixpacket": - return "unix" - default: - if ip := net.ParseIP(address); ip != nil { - if ip.To4() == nil { - return "inet6" - } - return "inet" - } - } - return "" -} - -// Peer returns attributes for a network peer address. -func (c *netConv) Peer(address string) []attribute.KeyValue { - h, p := splitHostPort(address) - var n int - if h != "" { - n++ - if p > 0 { - n++ - } - } - - if n == 0 { - return nil - } - - attrs := make([]attribute.KeyValue, 0, n) - attrs = append(attrs, c.PeerName(h)) - if p > 0 { - attrs = append(attrs, c.PeerPort(p)) - } - return attrs -} - -func (c *netConv) PeerName(name string) attribute.KeyValue { - return c.NetPeerNameKey.String(name) -} - -func (c *netConv) PeerPort(port int) attribute.KeyValue { - return c.NetPeerPortKey.Int(port) -} - -func (c *netConv) SockPeerAddr(addr string) attribute.KeyValue { - return c.NetSockPeerAddrKey.String(addr) -} - -func (c *netConv) SockPeerPort(port int) attribute.KeyValue { - return c.NetSockPeerPortKey.Int(port) -} - -// splitHostPort splits a network address hostport of the form "host", -// "host%zone", "[host]", "[host%zone], "host:port", "host%zone:port", -// "[host]:port", "[host%zone]:port", or ":port" into host or host%zone and -// port. -// -// An empty host is returned if it is not provided or unparsable. A negative -// port is returned if it is not provided or unparsable. -func splitHostPort(hostport string) (host string, port int) { - port = -1 - - if strings.HasPrefix(hostport, "[") { - addrEnd := strings.LastIndex(hostport, "]") - if addrEnd < 0 { - // Invalid hostport. - return - } - if i := strings.LastIndex(hostport[addrEnd:], ":"); i < 0 { - host = hostport[1:addrEnd] - return - } - } else { - if i := strings.LastIndex(hostport, ":"); i < 0 { - host = hostport - return - } - } - - host, pStr, err := net.SplitHostPort(hostport) - if err != nil { - return - } - - p, err := strconv.ParseUint(pStr, 10, 16) - if err != nil { - return - } - return host, int(p) // nolint: gosec // Bitsize checked to be 16 above. -} - -func netProtocol(proto string) (name string, version string) { - name, version, _ = strings.Cut(proto, "/") - switch name { - case "HTTP": - name = "http" - case "QUIC": - name = "quic" - case "SPDY": - name = "spdy" - default: - name = strings.ToLower(name) - } - return name, version -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go index 44b86ad86..514ae6753 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go @@ -11,14 +11,14 @@ import ( "sync/atomic" "time" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" + + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" ) // Transport implements the http.RoundTripper interface and wraps @@ -129,6 +129,37 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { t.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header)) res, err := t.rt.RoundTrip(r) + + // Defer metrics recording function to record the metrics on error or no error. + defer func() { + metricAttributes := semconv.MetricAttributes{ + Req: r, + AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), + } + + if err == nil { + metricAttributes.StatusCode = res.StatusCode + } + + metricOpts := t.semconv.MetricOptions(metricAttributes) + + metricData := semconv.MetricData{ + RequestSize: bw.BytesRead(), + } + + if err == nil { + readRecordFunc := func(int64) {} + res.Body = newWrappedBody(span, readRecordFunc, res.Body) + } + + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) + + metricData.ElapsedTime = elapsedTime + + t.semconv.RecordMetrics(ctx, metricData, metricOpts) + }() + if err != nil { // set error type attribute if the error is part of the predefined // error types. @@ -141,35 +172,14 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { span.SetStatus(codes.Error, err.Error()) span.End() - return res, err - } - - // metrics - metricOpts := t.semconv.MetricOptions(semconv.MetricAttributes{ - Req: r, - StatusCode: res.StatusCode, - AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), - }) - // For handling response bytes we leverage a callback when the client reads the http response - readRecordFunc := func(n int64) { - t.semconv.RecordResponseSize(ctx, n, metricOpts) + return res, err } // traces span.SetAttributes(t.semconv.ResponseTraceAttrs(res)...) span.SetStatus(t.semconv.Status(res.StatusCode)) - res.Body = newWrappedBody(span, readRecordFunc, res.Body) - - // Use floating point division here for higher precision (instead of Millisecond method). - elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - - t.semconv.RecordMetrics(ctx, semconv.MetricData{ - RequestSize: bw.BytesRead(), - ElapsedTime: elapsedTime, - }, metricOpts) - return res, nil } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index 6be4c1fde..6e096da5e 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -5,6 +5,6 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.61.0" + return "0.64.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/README.md b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/README.md deleted file mode 100644 index 82e1f46b4..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Semconv v1.20.0 - -[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/semconv/v1.20.0)](https://pkg.go.dev/go.opentelemetry.io/otel/semconv/v1.20.0) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go deleted file mode 100644 index 6685c392b..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go +++ /dev/null @@ -1,1198 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -import "go.opentelemetry.io/otel/attribute" - -// Describes HTTP attributes. -const ( - // HTTPMethodKey is the attribute Key conforming to the "http.method" - // semantic conventions. It represents the hTTP request method. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'GET', 'POST', 'HEAD' - HTTPMethodKey = attribute.Key("http.method") - - // HTTPStatusCodeKey is the attribute Key conforming to the - // "http.status_code" semantic conventions. It represents the [HTTP - // response status code](https://tools.ietf.org/html/rfc7231#section-6). - // - // Type: int - // RequirementLevel: ConditionallyRequired (If and only if one was - // received/sent.) - // Stability: stable - // Examples: 200 - HTTPStatusCodeKey = attribute.Key("http.status_code") -) - -// HTTPMethod returns an attribute KeyValue conforming to the "http.method" -// semantic conventions. It represents the hTTP request method. -func HTTPMethod(val string) attribute.KeyValue { - return HTTPMethodKey.String(val) -} - -// HTTPStatusCode returns an attribute KeyValue conforming to the -// "http.status_code" semantic conventions. It represents the [HTTP response -// status code](https://tools.ietf.org/html/rfc7231#section-6). -func HTTPStatusCode(val int) attribute.KeyValue { - return HTTPStatusCodeKey.Int(val) -} - -// HTTP Server spans attributes -const ( - // HTTPSchemeKey is the attribute Key conforming to the "http.scheme" - // semantic conventions. It represents the URI scheme identifying the used - // protocol. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'http', 'https' - HTTPSchemeKey = attribute.Key("http.scheme") - - // HTTPRouteKey is the attribute Key conforming to the "http.route" - // semantic conventions. It represents the matched route (path template in - // the format used by the respective server framework). See note below - // - // Type: string - // RequirementLevel: ConditionallyRequired (If and only if it's available) - // Stability: stable - // Examples: '/users/:userID?', '{controller}/{action}/{id?}' - // Note: MUST NOT be populated when this is not supported by the HTTP - // server framework as the route attribute should have low-cardinality and - // the URI path can NOT substitute it. - // SHOULD include the [application - // root](/specification/trace/semantic_conventions/http.md#http-server-definitions) - // if there is one. - HTTPRouteKey = attribute.Key("http.route") -) - -// HTTPScheme returns an attribute KeyValue conforming to the "http.scheme" -// semantic conventions. It represents the URI scheme identifying the used -// protocol. -func HTTPScheme(val string) attribute.KeyValue { - return HTTPSchemeKey.String(val) -} - -// HTTPRoute returns an attribute KeyValue conforming to the "http.route" -// semantic conventions. It represents the matched route (path template in the -// format used by the respective server framework). See note below -func HTTPRoute(val string) attribute.KeyValue { - return HTTPRouteKey.String(val) -} - -// Attributes for Events represented using Log Records. -const ( - // EventNameKey is the attribute Key conforming to the "event.name" - // semantic conventions. It represents the name identifies the event. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'click', 'exception' - EventNameKey = attribute.Key("event.name") - - // EventDomainKey is the attribute Key conforming to the "event.domain" - // semantic conventions. It represents the domain identifies the business - // context for the events. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: Events across different domains may have same `event.name`, yet be - // unrelated events. - EventDomainKey = attribute.Key("event.domain") -) - -var ( - // Events from browser apps - EventDomainBrowser = EventDomainKey.String("browser") - // Events from mobile apps - EventDomainDevice = EventDomainKey.String("device") - // Events from Kubernetes - EventDomainK8S = EventDomainKey.String("k8s") -) - -// EventName returns an attribute KeyValue conforming to the "event.name" -// semantic conventions. It represents the name identifies the event. -func EventName(val string) attribute.KeyValue { - return EventNameKey.String(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetTransportKey is the attribute Key conforming to the "net.transport" - // semantic conventions. It represents the transport protocol used. See - // note below. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - NetTransportKey = attribute.Key("net.transport") - - // NetProtocolNameKey is the attribute Key conforming to the - // "net.protocol.name" semantic conventions. It represents the application - // layer protocol used. The value SHOULD be normalized to lowercase. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'amqp', 'http', 'mqtt' - NetProtocolNameKey = attribute.Key("net.protocol.name") - - // NetProtocolVersionKey is the attribute Key conforming to the - // "net.protocol.version" semantic conventions. It represents the version - // of the application layer protocol used. See note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '3.1.1' - // Note: `net.protocol.version` refers to the version of the protocol used - // and might be different from the protocol client's version. If the HTTP - // client used has a version of `0.27.2`, but sends HTTP version `1.1`, - // this attribute should be set to `1.1`. - NetProtocolVersionKey = attribute.Key("net.protocol.version") - - // NetSockPeerNameKey is the attribute Key conforming to the - // "net.sock.peer.name" semantic conventions. It represents the remote - // socket peer name. - // - // Type: string - // RequirementLevel: Recommended (If available and different from - // `net.peer.name` and if `net.sock.peer.addr` is set.) - // Stability: stable - // Examples: 'proxy.example.com' - NetSockPeerNameKey = attribute.Key("net.sock.peer.name") - - // NetSockPeerAddrKey is the attribute Key conforming to the - // "net.sock.peer.addr" semantic conventions. It represents the remote - // socket peer address: IPv4 or IPv6 for internet protocols, path for local - // communication, - // [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '127.0.0.1', '/tmp/mysql.sock' - NetSockPeerAddrKey = attribute.Key("net.sock.peer.addr") - - // NetSockPeerPortKey is the attribute Key conforming to the - // "net.sock.peer.port" semantic conventions. It represents the remote - // socket peer port. - // - // Type: int - // RequirementLevel: Recommended (If defined for the address family and if - // different than `net.peer.port` and if `net.sock.peer.addr` is set.) - // Stability: stable - // Examples: 16456 - NetSockPeerPortKey = attribute.Key("net.sock.peer.port") - - // NetSockFamilyKey is the attribute Key conforming to the - // "net.sock.family" semantic conventions. It represents the protocol - // [address - // family](https://man7.org/linux/man-pages/man7/address_families.7.html) - // which is used for communication. - // - // Type: Enum - // RequirementLevel: ConditionallyRequired (If different than `inet` and if - // any of `net.sock.peer.addr` or `net.sock.host.addr` are set. Consumers - // of telemetry SHOULD accept both IPv4 and IPv6 formats for the address in - // `net.sock.peer.addr` if `net.sock.family` is not set. This is to support - // instrumentations that follow previous versions of this document.) - // Stability: stable - // Examples: 'inet6', 'bluetooth' - NetSockFamilyKey = attribute.Key("net.sock.family") - - // NetPeerNameKey is the attribute Key conforming to the "net.peer.name" - // semantic conventions. It represents the logical remote hostname, see - // note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'example.com' - // Note: `net.peer.name` SHOULD NOT be set if capturing it would require an - // extra DNS lookup. - NetPeerNameKey = attribute.Key("net.peer.name") - - // NetPeerPortKey is the attribute Key conforming to the "net.peer.port" - // semantic conventions. It represents the logical remote port number - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 80, 8080, 443 - NetPeerPortKey = attribute.Key("net.peer.port") - - // NetHostNameKey is the attribute Key conforming to the "net.host.name" - // semantic conventions. It represents the logical local hostname or - // similar, see note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'localhost' - NetHostNameKey = attribute.Key("net.host.name") - - // NetHostPortKey is the attribute Key conforming to the "net.host.port" - // semantic conventions. It represents the logical local port number, - // preferably the one that the peer used to connect - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 8080 - NetHostPortKey = attribute.Key("net.host.port") - - // NetSockHostAddrKey is the attribute Key conforming to the - // "net.sock.host.addr" semantic conventions. It represents the local - // socket address. Useful in case of a multi-IP host. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '192.168.0.1' - NetSockHostAddrKey = attribute.Key("net.sock.host.addr") - - // NetSockHostPortKey is the attribute Key conforming to the - // "net.sock.host.port" semantic conventions. It represents the local - // socket port number. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If defined for the address - // family and if different than `net.host.port` and if `net.sock.host.addr` - // is set. In other cases, it is still recommended to set this.) - // Stability: stable - // Examples: 35555 - NetSockHostPortKey = attribute.Key("net.sock.host.port") -) - -var ( - // ip_tcp - NetTransportTCP = NetTransportKey.String("ip_tcp") - // ip_udp - NetTransportUDP = NetTransportKey.String("ip_udp") - // Named or anonymous pipe. See note below - NetTransportPipe = NetTransportKey.String("pipe") - // In-process communication - NetTransportInProc = NetTransportKey.String("inproc") - // Something else (non IP-based) - NetTransportOther = NetTransportKey.String("other") -) - -var ( - // IPv4 address - NetSockFamilyInet = NetSockFamilyKey.String("inet") - // IPv6 address - NetSockFamilyInet6 = NetSockFamilyKey.String("inet6") - // Unix domain socket path - NetSockFamilyUnix = NetSockFamilyKey.String("unix") -) - -// NetProtocolName returns an attribute KeyValue conforming to the -// "net.protocol.name" semantic conventions. It represents the application -// layer protocol used. The value SHOULD be normalized to lowercase. -func NetProtocolName(val string) attribute.KeyValue { - return NetProtocolNameKey.String(val) -} - -// NetProtocolVersion returns an attribute KeyValue conforming to the -// "net.protocol.version" semantic conventions. It represents the version of -// the application layer protocol used. See note below. -func NetProtocolVersion(val string) attribute.KeyValue { - return NetProtocolVersionKey.String(val) -} - -// NetSockPeerName returns an attribute KeyValue conforming to the -// "net.sock.peer.name" semantic conventions. It represents the remote socket -// peer name. -func NetSockPeerName(val string) attribute.KeyValue { - return NetSockPeerNameKey.String(val) -} - -// NetSockPeerAddr returns an attribute KeyValue conforming to the -// "net.sock.peer.addr" semantic conventions. It represents the remote socket -// peer address: IPv4 or IPv6 for internet protocols, path for local -// communication, -// [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). -func NetSockPeerAddr(val string) attribute.KeyValue { - return NetSockPeerAddrKey.String(val) -} - -// NetSockPeerPort returns an attribute KeyValue conforming to the -// "net.sock.peer.port" semantic conventions. It represents the remote socket -// peer port. -func NetSockPeerPort(val int) attribute.KeyValue { - return NetSockPeerPortKey.Int(val) -} - -// NetPeerName returns an attribute KeyValue conforming to the -// "net.peer.name" semantic conventions. It represents the logical remote -// hostname, see note below. -func NetPeerName(val string) attribute.KeyValue { - return NetPeerNameKey.String(val) -} - -// NetPeerPort returns an attribute KeyValue conforming to the -// "net.peer.port" semantic conventions. It represents the logical remote port -// number -func NetPeerPort(val int) attribute.KeyValue { - return NetPeerPortKey.Int(val) -} - -// NetHostName returns an attribute KeyValue conforming to the -// "net.host.name" semantic conventions. It represents the logical local -// hostname or similar, see note below. -func NetHostName(val string) attribute.KeyValue { - return NetHostNameKey.String(val) -} - -// NetHostPort returns an attribute KeyValue conforming to the -// "net.host.port" semantic conventions. It represents the logical local port -// number, preferably the one that the peer used to connect -func NetHostPort(val int) attribute.KeyValue { - return NetHostPortKey.Int(val) -} - -// NetSockHostAddr returns an attribute KeyValue conforming to the -// "net.sock.host.addr" semantic conventions. It represents the local socket -// address. Useful in case of a multi-IP host. -func NetSockHostAddr(val string) attribute.KeyValue { - return NetSockHostAddrKey.String(val) -} - -// NetSockHostPort returns an attribute KeyValue conforming to the -// "net.sock.host.port" semantic conventions. It represents the local socket -// port number. -func NetSockHostPort(val int) attribute.KeyValue { - return NetSockHostPortKey.Int(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetHostConnectionTypeKey is the attribute Key conforming to the - // "net.host.connection.type" semantic conventions. It represents the - // internet connection type currently being used by the host. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'wifi' - NetHostConnectionTypeKey = attribute.Key("net.host.connection.type") - - // NetHostConnectionSubtypeKey is the attribute Key conforming to the - // "net.host.connection.subtype" semantic conventions. It represents the - // this describes more details regarding the connection.type. It may be the - // type of cell technology connection, but it could be used for describing - // details about a wifi connection. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'LTE' - NetHostConnectionSubtypeKey = attribute.Key("net.host.connection.subtype") - - // NetHostCarrierNameKey is the attribute Key conforming to the - // "net.host.carrier.name" semantic conventions. It represents the name of - // the mobile carrier. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'sprint' - NetHostCarrierNameKey = attribute.Key("net.host.carrier.name") - - // NetHostCarrierMccKey is the attribute Key conforming to the - // "net.host.carrier.mcc" semantic conventions. It represents the mobile - // carrier country code. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '310' - NetHostCarrierMccKey = attribute.Key("net.host.carrier.mcc") - - // NetHostCarrierMncKey is the attribute Key conforming to the - // "net.host.carrier.mnc" semantic conventions. It represents the mobile - // carrier network code. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '001' - NetHostCarrierMncKey = attribute.Key("net.host.carrier.mnc") - - // NetHostCarrierIccKey is the attribute Key conforming to the - // "net.host.carrier.icc" semantic conventions. It represents the ISO - // 3166-1 alpha-2 2-character country code associated with the mobile - // carrier network. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'DE' - NetHostCarrierIccKey = attribute.Key("net.host.carrier.icc") -) - -var ( - // wifi - NetHostConnectionTypeWifi = NetHostConnectionTypeKey.String("wifi") - // wired - NetHostConnectionTypeWired = NetHostConnectionTypeKey.String("wired") - // cell - NetHostConnectionTypeCell = NetHostConnectionTypeKey.String("cell") - // unavailable - NetHostConnectionTypeUnavailable = NetHostConnectionTypeKey.String("unavailable") - // unknown - NetHostConnectionTypeUnknown = NetHostConnectionTypeKey.String("unknown") -) - -var ( - // GPRS - NetHostConnectionSubtypeGprs = NetHostConnectionSubtypeKey.String("gprs") - // EDGE - NetHostConnectionSubtypeEdge = NetHostConnectionSubtypeKey.String("edge") - // UMTS - NetHostConnectionSubtypeUmts = NetHostConnectionSubtypeKey.String("umts") - // CDMA - NetHostConnectionSubtypeCdma = NetHostConnectionSubtypeKey.String("cdma") - // EVDO Rel. 0 - NetHostConnectionSubtypeEvdo0 = NetHostConnectionSubtypeKey.String("evdo_0") - // EVDO Rev. A - NetHostConnectionSubtypeEvdoA = NetHostConnectionSubtypeKey.String("evdo_a") - // CDMA2000 1XRTT - NetHostConnectionSubtypeCdma20001xrtt = NetHostConnectionSubtypeKey.String("cdma2000_1xrtt") - // HSDPA - NetHostConnectionSubtypeHsdpa = NetHostConnectionSubtypeKey.String("hsdpa") - // HSUPA - NetHostConnectionSubtypeHsupa = NetHostConnectionSubtypeKey.String("hsupa") - // HSPA - NetHostConnectionSubtypeHspa = NetHostConnectionSubtypeKey.String("hspa") - // IDEN - NetHostConnectionSubtypeIden = NetHostConnectionSubtypeKey.String("iden") - // EVDO Rev. B - NetHostConnectionSubtypeEvdoB = NetHostConnectionSubtypeKey.String("evdo_b") - // LTE - NetHostConnectionSubtypeLte = NetHostConnectionSubtypeKey.String("lte") - // EHRPD - NetHostConnectionSubtypeEhrpd = NetHostConnectionSubtypeKey.String("ehrpd") - // HSPAP - NetHostConnectionSubtypeHspap = NetHostConnectionSubtypeKey.String("hspap") - // GSM - NetHostConnectionSubtypeGsm = NetHostConnectionSubtypeKey.String("gsm") - // TD-SCDMA - NetHostConnectionSubtypeTdScdma = NetHostConnectionSubtypeKey.String("td_scdma") - // IWLAN - NetHostConnectionSubtypeIwlan = NetHostConnectionSubtypeKey.String("iwlan") - // 5G NR (New Radio) - NetHostConnectionSubtypeNr = NetHostConnectionSubtypeKey.String("nr") - // 5G NRNSA (New Radio Non-Standalone) - NetHostConnectionSubtypeNrnsa = NetHostConnectionSubtypeKey.String("nrnsa") - // LTE CA - NetHostConnectionSubtypeLteCa = NetHostConnectionSubtypeKey.String("lte_ca") -) - -// NetHostCarrierName returns an attribute KeyValue conforming to the -// "net.host.carrier.name" semantic conventions. It represents the name of the -// mobile carrier. -func NetHostCarrierName(val string) attribute.KeyValue { - return NetHostCarrierNameKey.String(val) -} - -// NetHostCarrierMcc returns an attribute KeyValue conforming to the -// "net.host.carrier.mcc" semantic conventions. It represents the mobile -// carrier country code. -func NetHostCarrierMcc(val string) attribute.KeyValue { - return NetHostCarrierMccKey.String(val) -} - -// NetHostCarrierMnc returns an attribute KeyValue conforming to the -// "net.host.carrier.mnc" semantic conventions. It represents the mobile -// carrier network code. -func NetHostCarrierMnc(val string) attribute.KeyValue { - return NetHostCarrierMncKey.String(val) -} - -// NetHostCarrierIcc returns an attribute KeyValue conforming to the -// "net.host.carrier.icc" semantic conventions. It represents the ISO 3166-1 -// alpha-2 2-character country code associated with the mobile carrier network. -func NetHostCarrierIcc(val string) attribute.KeyValue { - return NetHostCarrierIccKey.String(val) -} - -// Semantic conventions for HTTP client and server Spans. -const ( - // HTTPRequestContentLengthKey is the attribute Key conforming to the - // "http.request_content_length" semantic conventions. It represents the - // size of the request payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3495 - HTTPRequestContentLengthKey = attribute.Key("http.request_content_length") - - // HTTPResponseContentLengthKey is the attribute Key conforming to the - // "http.response_content_length" semantic conventions. It represents the - // size of the response payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3495 - HTTPResponseContentLengthKey = attribute.Key("http.response_content_length") -) - -// HTTPRequestContentLength returns an attribute KeyValue conforming to the -// "http.request_content_length" semantic conventions. It represents the size -// of the request payload body in bytes. This is the number of bytes -// transferred excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPRequestContentLength(val int) attribute.KeyValue { - return HTTPRequestContentLengthKey.Int(val) -} - -// HTTPResponseContentLength returns an attribute KeyValue conforming to the -// "http.response_content_length" semantic conventions. It represents the size -// of the response payload body in bytes. This is the number of bytes -// transferred excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPResponseContentLength(val int) attribute.KeyValue { - return HTTPResponseContentLengthKey.Int(val) -} - -// Semantic convention describing per-message attributes populated on messaging -// spans or links. -const ( - // MessagingMessageIDKey is the attribute Key conforming to the - // "messaging.message.id" semantic conventions. It represents a value used - // by the messaging system as an identifier for the message, represented as - // a string. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '452a7c7c7c7048c2f887f61572b18fc2' - MessagingMessageIDKey = attribute.Key("messaging.message.id") - - // MessagingMessageConversationIDKey is the attribute Key conforming to the - // "messaging.message.conversation_id" semantic conventions. It represents - // the [conversation ID](#conversations) identifying the conversation to - // which the message belongs, represented as a string. Sometimes called - // "Correlation ID". - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyConversationID' - MessagingMessageConversationIDKey = attribute.Key("messaging.message.conversation_id") - - // MessagingMessagePayloadSizeBytesKey is the attribute Key conforming to - // the "messaging.message.payload_size_bytes" semantic conventions. It - // represents the (uncompressed) size of the message payload in bytes. Also - // use this attribute if it is unknown whether the compressed or - // uncompressed payload size is reported. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2738 - MessagingMessagePayloadSizeBytesKey = attribute.Key("messaging.message.payload_size_bytes") - - // MessagingMessagePayloadCompressedSizeBytesKey is the attribute Key - // conforming to the "messaging.message.payload_compressed_size_bytes" - // semantic conventions. It represents the compressed size of the message - // payload in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2048 - MessagingMessagePayloadCompressedSizeBytesKey = attribute.Key("messaging.message.payload_compressed_size_bytes") -) - -// MessagingMessageID returns an attribute KeyValue conforming to the -// "messaging.message.id" semantic conventions. It represents a value used by -// the messaging system as an identifier for the message, represented as a -// string. -func MessagingMessageID(val string) attribute.KeyValue { - return MessagingMessageIDKey.String(val) -} - -// MessagingMessageConversationID returns an attribute KeyValue conforming -// to the "messaging.message.conversation_id" semantic conventions. It -// represents the [conversation ID](#conversations) identifying the -// conversation to which the message belongs, represented as a string. -// Sometimes called "Correlation ID". -func MessagingMessageConversationID(val string) attribute.KeyValue { - return MessagingMessageConversationIDKey.String(val) -} - -// MessagingMessagePayloadSizeBytes returns an attribute KeyValue conforming -// to the "messaging.message.payload_size_bytes" semantic conventions. It -// represents the (uncompressed) size of the message payload in bytes. Also use -// this attribute if it is unknown whether the compressed or uncompressed -// payload size is reported. -func MessagingMessagePayloadSizeBytes(val int) attribute.KeyValue { - return MessagingMessagePayloadSizeBytesKey.Int(val) -} - -// MessagingMessagePayloadCompressedSizeBytes returns an attribute KeyValue -// conforming to the "messaging.message.payload_compressed_size_bytes" semantic -// conventions. It represents the compressed size of the message payload in -// bytes. -func MessagingMessagePayloadCompressedSizeBytes(val int) attribute.KeyValue { - return MessagingMessagePayloadCompressedSizeBytesKey.Int(val) -} - -// Semantic convention for attributes that describe messaging destination on -// broker -const ( - // MessagingDestinationNameKey is the attribute Key conforming to the - // "messaging.destination.name" semantic conventions. It represents the - // message destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyQueue', 'MyTopic' - // Note: Destination name SHOULD uniquely identify a specific queue, topic - // or other entity within the broker. If - // the broker does not have such notion, the destination name SHOULD - // uniquely identify the broker. - MessagingDestinationNameKey = attribute.Key("messaging.destination.name") - - // MessagingDestinationTemplateKey is the attribute Key conforming to the - // "messaging.destination.template" semantic conventions. It represents the - // low cardinality representation of the messaging destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/customers/{customerID}' - // Note: Destination names could be constructed from templates. An example - // would be a destination name involving a user name or product id. - // Although the destination name in this case is of high cardinality, the - // underlying template is of low cardinality and can be effectively used - // for grouping and aggregation. - MessagingDestinationTemplateKey = attribute.Key("messaging.destination.template") - - // MessagingDestinationTemporaryKey is the attribute Key conforming to the - // "messaging.destination.temporary" semantic conventions. It represents a - // boolean that is true if the message destination is temporary and might - // not exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingDestinationTemporaryKey = attribute.Key("messaging.destination.temporary") - - // MessagingDestinationAnonymousKey is the attribute Key conforming to the - // "messaging.destination.anonymous" semantic conventions. It represents a - // boolean that is true if the message destination is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingDestinationAnonymousKey = attribute.Key("messaging.destination.anonymous") -) - -// MessagingDestinationName returns an attribute KeyValue conforming to the -// "messaging.destination.name" semantic conventions. It represents the message -// destination name -func MessagingDestinationName(val string) attribute.KeyValue { - return MessagingDestinationNameKey.String(val) -} - -// MessagingDestinationTemplate returns an attribute KeyValue conforming to -// the "messaging.destination.template" semantic conventions. It represents the -// low cardinality representation of the messaging destination name -func MessagingDestinationTemplate(val string) attribute.KeyValue { - return MessagingDestinationTemplateKey.String(val) -} - -// MessagingDestinationTemporary returns an attribute KeyValue conforming to -// the "messaging.destination.temporary" semantic conventions. It represents a -// boolean that is true if the message destination is temporary and might not -// exist anymore after messages are processed. -func MessagingDestinationTemporary(val bool) attribute.KeyValue { - return MessagingDestinationTemporaryKey.Bool(val) -} - -// MessagingDestinationAnonymous returns an attribute KeyValue conforming to -// the "messaging.destination.anonymous" semantic conventions. It represents a -// boolean that is true if the message destination is anonymous (could be -// unnamed or have auto-generated name). -func MessagingDestinationAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationAnonymousKey.Bool(val) -} - -// Semantic convention for attributes that describe messaging source on broker -const ( - // MessagingSourceNameKey is the attribute Key conforming to the - // "messaging.source.name" semantic conventions. It represents the message - // source name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyQueue', 'MyTopic' - // Note: Source name SHOULD uniquely identify a specific queue, topic, or - // other entity within the broker. If - // the broker does not have such notion, the source name SHOULD uniquely - // identify the broker. - MessagingSourceNameKey = attribute.Key("messaging.source.name") - - // MessagingSourceTemplateKey is the attribute Key conforming to the - // "messaging.source.template" semantic conventions. It represents the low - // cardinality representation of the messaging source name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/customers/{customerID}' - // Note: Source names could be constructed from templates. An example would - // be a source name involving a user name or product id. Although the - // source name in this case is of high cardinality, the underlying template - // is of low cardinality and can be effectively used for grouping and - // aggregation. - MessagingSourceTemplateKey = attribute.Key("messaging.source.template") - - // MessagingSourceTemporaryKey is the attribute Key conforming to the - // "messaging.source.temporary" semantic conventions. It represents a - // boolean that is true if the message source is temporary and might not - // exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingSourceTemporaryKey = attribute.Key("messaging.source.temporary") - - // MessagingSourceAnonymousKey is the attribute Key conforming to the - // "messaging.source.anonymous" semantic conventions. It represents a - // boolean that is true if the message source is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingSourceAnonymousKey = attribute.Key("messaging.source.anonymous") -) - -// MessagingSourceName returns an attribute KeyValue conforming to the -// "messaging.source.name" semantic conventions. It represents the message -// source name -func MessagingSourceName(val string) attribute.KeyValue { - return MessagingSourceNameKey.String(val) -} - -// MessagingSourceTemplate returns an attribute KeyValue conforming to the -// "messaging.source.template" semantic conventions. It represents the low -// cardinality representation of the messaging source name -func MessagingSourceTemplate(val string) attribute.KeyValue { - return MessagingSourceTemplateKey.String(val) -} - -// MessagingSourceTemporary returns an attribute KeyValue conforming to the -// "messaging.source.temporary" semantic conventions. It represents a boolean -// that is true if the message source is temporary and might not exist anymore -// after messages are processed. -func MessagingSourceTemporary(val bool) attribute.KeyValue { - return MessagingSourceTemporaryKey.Bool(val) -} - -// MessagingSourceAnonymous returns an attribute KeyValue conforming to the -// "messaging.source.anonymous" semantic conventions. It represents a boolean -// that is true if the message source is anonymous (could be unnamed or have -// auto-generated name). -func MessagingSourceAnonymous(val bool) attribute.KeyValue { - return MessagingSourceAnonymousKey.Bool(val) -} - -// Attributes for RabbitMQ -const ( - // MessagingRabbitmqDestinationRoutingKeyKey is the attribute Key - // conforming to the "messaging.rabbitmq.destination.routing_key" semantic - // conventions. It represents the rabbitMQ message routing key. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If not empty.) - // Stability: stable - // Examples: 'myKey' - MessagingRabbitmqDestinationRoutingKeyKey = attribute.Key("messaging.rabbitmq.destination.routing_key") -) - -// MessagingRabbitmqDestinationRoutingKey returns an attribute KeyValue -// conforming to the "messaging.rabbitmq.destination.routing_key" semantic -// conventions. It represents the rabbitMQ message routing key. -func MessagingRabbitmqDestinationRoutingKey(val string) attribute.KeyValue { - return MessagingRabbitmqDestinationRoutingKeyKey.String(val) -} - -// Attributes for Apache Kafka -const ( - // MessagingKafkaMessageKeyKey is the attribute Key conforming to the - // "messaging.kafka.message.key" semantic conventions. It represents the - // message keys in Kafka are used for grouping alike messages to ensure - // they're processed on the same partition. They differ from - // `messaging.message.id` in that they're not unique. If the key is `null`, - // the attribute MUST NOT be set. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'myKey' - // Note: If the key type is not string, it's string representation has to - // be supplied for the attribute. If the key has no unambiguous, canonical - // string form, don't include its value. - MessagingKafkaMessageKeyKey = attribute.Key("messaging.kafka.message.key") - - // MessagingKafkaConsumerGroupKey is the attribute Key conforming to the - // "messaging.kafka.consumer.group" semantic conventions. It represents the - // name of the Kafka Consumer Group that is handling the message. Only - // applies to consumers, not producers. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'my-group' - MessagingKafkaConsumerGroupKey = attribute.Key("messaging.kafka.consumer.group") - - // MessagingKafkaClientIDKey is the attribute Key conforming to the - // "messaging.kafka.client_id" semantic conventions. It represents the - // client ID for the Consumer or Producer that is handling the message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'client-5' - MessagingKafkaClientIDKey = attribute.Key("messaging.kafka.client_id") - - // MessagingKafkaDestinationPartitionKey is the attribute Key conforming to - // the "messaging.kafka.destination.partition" semantic conventions. It - // represents the partition the message is sent to. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2 - MessagingKafkaDestinationPartitionKey = attribute.Key("messaging.kafka.destination.partition") - - // MessagingKafkaSourcePartitionKey is the attribute Key conforming to the - // "messaging.kafka.source.partition" semantic conventions. It represents - // the partition the message is received from. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2 - MessagingKafkaSourcePartitionKey = attribute.Key("messaging.kafka.source.partition") - - // MessagingKafkaMessageOffsetKey is the attribute Key conforming to the - // "messaging.kafka.message.offset" semantic conventions. It represents the - // offset of a record in the corresponding Kafka partition. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - MessagingKafkaMessageOffsetKey = attribute.Key("messaging.kafka.message.offset") - - // MessagingKafkaMessageTombstoneKey is the attribute Key conforming to the - // "messaging.kafka.message.tombstone" semantic conventions. It represents - // a boolean that is true if the message is a tombstone. - // - // Type: boolean - // RequirementLevel: ConditionallyRequired (If value is `true`. When - // missing, the value is assumed to be `false`.) - // Stability: stable - MessagingKafkaMessageTombstoneKey = attribute.Key("messaging.kafka.message.tombstone") -) - -// MessagingKafkaMessageKey returns an attribute KeyValue conforming to the -// "messaging.kafka.message.key" semantic conventions. It represents the -// message keys in Kafka are used for grouping alike messages to ensure they're -// processed on the same partition. They differ from `messaging.message.id` in -// that they're not unique. If the key is `null`, the attribute MUST NOT be -// set. -func MessagingKafkaMessageKey(val string) attribute.KeyValue { - return MessagingKafkaMessageKeyKey.String(val) -} - -// MessagingKafkaConsumerGroup returns an attribute KeyValue conforming to -// the "messaging.kafka.consumer.group" semantic conventions. It represents the -// name of the Kafka Consumer Group that is handling the message. Only applies -// to consumers, not producers. -func MessagingKafkaConsumerGroup(val string) attribute.KeyValue { - return MessagingKafkaConsumerGroupKey.String(val) -} - -// MessagingKafkaClientID returns an attribute KeyValue conforming to the -// "messaging.kafka.client_id" semantic conventions. It represents the client -// ID for the Consumer or Producer that is handling the message. -func MessagingKafkaClientID(val string) attribute.KeyValue { - return MessagingKafkaClientIDKey.String(val) -} - -// MessagingKafkaDestinationPartition returns an attribute KeyValue -// conforming to the "messaging.kafka.destination.partition" semantic -// conventions. It represents the partition the message is sent to. -func MessagingKafkaDestinationPartition(val int) attribute.KeyValue { - return MessagingKafkaDestinationPartitionKey.Int(val) -} - -// MessagingKafkaSourcePartition returns an attribute KeyValue conforming to -// the "messaging.kafka.source.partition" semantic conventions. It represents -// the partition the message is received from. -func MessagingKafkaSourcePartition(val int) attribute.KeyValue { - return MessagingKafkaSourcePartitionKey.Int(val) -} - -// MessagingKafkaMessageOffset returns an attribute KeyValue conforming to -// the "messaging.kafka.message.offset" semantic conventions. It represents the -// offset of a record in the corresponding Kafka partition. -func MessagingKafkaMessageOffset(val int) attribute.KeyValue { - return MessagingKafkaMessageOffsetKey.Int(val) -} - -// MessagingKafkaMessageTombstone returns an attribute KeyValue conforming -// to the "messaging.kafka.message.tombstone" semantic conventions. It -// represents a boolean that is true if the message is a tombstone. -func MessagingKafkaMessageTombstone(val bool) attribute.KeyValue { - return MessagingKafkaMessageTombstoneKey.Bool(val) -} - -// Attributes for Apache RocketMQ -const ( - // MessagingRocketmqNamespaceKey is the attribute Key conforming to the - // "messaging.rocketmq.namespace" semantic conventions. It represents the - // namespace of RocketMQ resources, resources in different namespaces are - // individual. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myNamespace' - MessagingRocketmqNamespaceKey = attribute.Key("messaging.rocketmq.namespace") - - // MessagingRocketmqClientGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.client_group" semantic conventions. It represents - // the name of the RocketMQ producer/consumer group that is handling the - // message. The client type is identified by the SpanKind. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myConsumerGroup' - MessagingRocketmqClientGroupKey = attribute.Key("messaging.rocketmq.client_group") - - // MessagingRocketmqClientIDKey is the attribute Key conforming to the - // "messaging.rocketmq.client_id" semantic conventions. It represents the - // unique identifier for each client. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myhost@8742@s8083jm' - MessagingRocketmqClientIDKey = attribute.Key("messaging.rocketmq.client_id") - - // MessagingRocketmqMessageDeliveryTimestampKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delivery_timestamp" - // semantic conventions. It represents the timestamp in milliseconds that - // the delay message is expected to be delivered to consumer. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the message type is delay - // and delay time level is not specified.) - // Stability: stable - // Examples: 1665987217045 - MessagingRocketmqMessageDeliveryTimestampKey = attribute.Key("messaging.rocketmq.message.delivery_timestamp") - - // MessagingRocketmqMessageDelayTimeLevelKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delay_time_level" semantic - // conventions. It represents the delay time level for delay message, which - // determines the message delay time. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the message type is delay - // and delivery timestamp is not specified.) - // Stability: stable - // Examples: 3 - MessagingRocketmqMessageDelayTimeLevelKey = attribute.Key("messaging.rocketmq.message.delay_time_level") - - // MessagingRocketmqMessageGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.message.group" semantic conventions. It represents - // the it is essential for FIFO message. Messages that belong to the same - // message group are always processed one by one within the same consumer - // group. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If the message type is FIFO.) - // Stability: stable - // Examples: 'myMessageGroup' - MessagingRocketmqMessageGroupKey = attribute.Key("messaging.rocketmq.message.group") - - // MessagingRocketmqMessageTypeKey is the attribute Key conforming to the - // "messaging.rocketmq.message.type" semantic conventions. It represents - // the type of message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingRocketmqMessageTypeKey = attribute.Key("messaging.rocketmq.message.type") - - // MessagingRocketmqMessageTagKey is the attribute Key conforming to the - // "messaging.rocketmq.message.tag" semantic conventions. It represents the - // secondary classifier of message besides topic. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'tagA' - MessagingRocketmqMessageTagKey = attribute.Key("messaging.rocketmq.message.tag") - - // MessagingRocketmqMessageKeysKey is the attribute Key conforming to the - // "messaging.rocketmq.message.keys" semantic conventions. It represents - // the key(s) of message, another way to mark message besides message id. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'keyA', 'keyB' - MessagingRocketmqMessageKeysKey = attribute.Key("messaging.rocketmq.message.keys") - - // MessagingRocketmqConsumptionModelKey is the attribute Key conforming to - // the "messaging.rocketmq.consumption_model" semantic conventions. It - // represents the model of message consumption. This only applies to - // consumer spans. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingRocketmqConsumptionModelKey = attribute.Key("messaging.rocketmq.consumption_model") -) - -var ( - // Normal message - MessagingRocketmqMessageTypeNormal = MessagingRocketmqMessageTypeKey.String("normal") - // FIFO message - MessagingRocketmqMessageTypeFifo = MessagingRocketmqMessageTypeKey.String("fifo") - // Delay message - MessagingRocketmqMessageTypeDelay = MessagingRocketmqMessageTypeKey.String("delay") - // Transaction message - MessagingRocketmqMessageTypeTransaction = MessagingRocketmqMessageTypeKey.String("transaction") -) - -var ( - // Clustering consumption model - MessagingRocketmqConsumptionModelClustering = MessagingRocketmqConsumptionModelKey.String("clustering") - // Broadcasting consumption model - MessagingRocketmqConsumptionModelBroadcasting = MessagingRocketmqConsumptionModelKey.String("broadcasting") -) - -// MessagingRocketmqNamespace returns an attribute KeyValue conforming to -// the "messaging.rocketmq.namespace" semantic conventions. It represents the -// namespace of RocketMQ resources, resources in different namespaces are -// individual. -func MessagingRocketmqNamespace(val string) attribute.KeyValue { - return MessagingRocketmqNamespaceKey.String(val) -} - -// MessagingRocketmqClientGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.client_group" semantic conventions. It represents -// the name of the RocketMQ producer/consumer group that is handling the -// message. The client type is identified by the SpanKind. -func MessagingRocketmqClientGroup(val string) attribute.KeyValue { - return MessagingRocketmqClientGroupKey.String(val) -} - -// MessagingRocketmqClientID returns an attribute KeyValue conforming to the -// "messaging.rocketmq.client_id" semantic conventions. It represents the -// unique identifier for each client. -func MessagingRocketmqClientID(val string) attribute.KeyValue { - return MessagingRocketmqClientIDKey.String(val) -} - -// MessagingRocketmqMessageDeliveryTimestamp returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delivery_timestamp" semantic -// conventions. It represents the timestamp in milliseconds that the delay -// message is expected to be delivered to consumer. -func MessagingRocketmqMessageDeliveryTimestamp(val int) attribute.KeyValue { - return MessagingRocketmqMessageDeliveryTimestampKey.Int(val) -} - -// MessagingRocketmqMessageDelayTimeLevel returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delay_time_level" semantic -// conventions. It represents the delay time level for delay message, which -// determines the message delay time. -func MessagingRocketmqMessageDelayTimeLevel(val int) attribute.KeyValue { - return MessagingRocketmqMessageDelayTimeLevelKey.Int(val) -} - -// MessagingRocketmqMessageGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.group" semantic conventions. It represents -// the it is essential for FIFO message. Messages that belong to the same -// message group are always processed one by one within the same consumer -// group. -func MessagingRocketmqMessageGroup(val string) attribute.KeyValue { - return MessagingRocketmqMessageGroupKey.String(val) -} - -// MessagingRocketmqMessageTag returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.tag" semantic conventions. It represents the -// secondary classifier of message besides topic. -func MessagingRocketmqMessageTag(val string) attribute.KeyValue { - return MessagingRocketmqMessageTagKey.String(val) -} - -// MessagingRocketmqMessageKeys returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.keys" semantic conventions. It represents -// the key(s) of message, another way to mark message besides message id. -func MessagingRocketmqMessageKeys(val ...string) attribute.KeyValue { - return MessagingRocketmqMessageKeysKey.StringSlice(val) -} - -// Describes user-agent attributes. -const ( - // UserAgentOriginalKey is the attribute Key conforming to the - // "user_agent.original" semantic conventions. It represents the value of - // the [HTTP - // User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) - // header sent by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'CERN-LineMode/2.15 libwww/2.17b3' - UserAgentOriginalKey = attribute.Key("user_agent.original") -) - -// UserAgentOriginal returns an attribute KeyValue conforming to the -// "user_agent.original" semantic conventions. It represents the value of the -// [HTTP -// User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) -// header sent by the client. -func UserAgentOriginal(val string) attribute.KeyValue { - return UserAgentOriginalKey.String(val) -} diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go deleted file mode 100644 index 0d1f55a8f..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconv implements OpenTelemetry semantic conventions. -// -// OpenTelemetry semantic conventions are agreed standardized naming -// patterns for OpenTelemetry things. This package represents the conventions -// as of the v1.20.0 version of the OpenTelemetry specification. -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go deleted file mode 100644 index 637763932..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -import "go.opentelemetry.io/otel/attribute" - -// This semantic convention defines the attributes used to represent a feature -// flag evaluation as an event. -const ( - // FeatureFlagKeyKey is the attribute Key conforming to the - // "feature_flag.key" semantic conventions. It represents the unique - // identifier of the feature flag. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'logo-color' - FeatureFlagKeyKey = attribute.Key("feature_flag.key") - - // FeatureFlagProviderNameKey is the attribute Key conforming to the - // "feature_flag.provider_name" semantic conventions. It represents the - // name of the service provider that performs the flag evaluation. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'Flag Manager' - FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") - - // FeatureFlagVariantKey is the attribute Key conforming to the - // "feature_flag.variant" semantic conventions. It represents the sHOULD be - // a semantic identifier for a value. If one is unavailable, a stringified - // version of the value can be used. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'red', 'true', 'on' - // Note: A semantic identifier, commonly referred to as a variant, provides - // a means - // for referring to a value without including the value itself. This can - // provide additional context for understanding the meaning behind a value. - // For example, the variant `red` maybe be used for the value `#c05543`. - // - // A stringified version of the value can be used in situations where a - // semantic identifier is unavailable. String representation of the value - // should be determined by the implementer. - FeatureFlagVariantKey = attribute.Key("feature_flag.variant") -) - -// FeatureFlagKey returns an attribute KeyValue conforming to the -// "feature_flag.key" semantic conventions. It represents the unique identifier -// of the feature flag. -func FeatureFlagKey(val string) attribute.KeyValue { - return FeatureFlagKeyKey.String(val) -} - -// FeatureFlagProviderName returns an attribute KeyValue conforming to the -// "feature_flag.provider_name" semantic conventions. It represents the name of -// the service provider that performs the flag evaluation. -func FeatureFlagProviderName(val string) attribute.KeyValue { - return FeatureFlagProviderNameKey.String(val) -} - -// FeatureFlagVariant returns an attribute KeyValue conforming to the -// "feature_flag.variant" semantic conventions. It represents the sHOULD be a -// semantic identifier for a value. If one is unavailable, a stringified -// version of the value can be used. -func FeatureFlagVariant(val string) attribute.KeyValue { - return FeatureFlagVariantKey.String(val) -} - -// RPC received/sent message. -const ( - // MessageTypeKey is the attribute Key conforming to the "message.type" - // semantic conventions. It represents the whether this is a received or - // sent message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessageTypeKey = attribute.Key("message.type") - - // MessageIDKey is the attribute Key conforming to the "message.id" - // semantic conventions. It represents the mUST be calculated as two - // different counters starting from `1` one for sent messages and one for - // received message. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Note: This way we guarantee that the values will be consistent between - // different implementations. - MessageIDKey = attribute.Key("message.id") - - // MessageCompressedSizeKey is the attribute Key conforming to the - // "message.compressed_size" semantic conventions. It represents the - // compressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - MessageCompressedSizeKey = attribute.Key("message.compressed_size") - - // MessageUncompressedSizeKey is the attribute Key conforming to the - // "message.uncompressed_size" semantic conventions. It represents the - // uncompressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - MessageUncompressedSizeKey = attribute.Key("message.uncompressed_size") -) - -var ( - // sent - MessageTypeSent = MessageTypeKey.String("SENT") - // received - MessageTypeReceived = MessageTypeKey.String("RECEIVED") -) - -// MessageID returns an attribute KeyValue conforming to the "message.id" -// semantic conventions. It represents the mUST be calculated as two different -// counters starting from `1` one for sent messages and one for received -// message. -func MessageID(val int) attribute.KeyValue { - return MessageIDKey.Int(val) -} - -// MessageCompressedSize returns an attribute KeyValue conforming to the -// "message.compressed_size" semantic conventions. It represents the compressed -// size of the message in bytes. -func MessageCompressedSize(val int) attribute.KeyValue { - return MessageCompressedSizeKey.Int(val) -} - -// MessageUncompressedSize returns an attribute KeyValue conforming to the -// "message.uncompressed_size" semantic conventions. It represents the -// uncompressed size of the message in bytes. -func MessageUncompressedSize(val int) attribute.KeyValue { - return MessageUncompressedSizeKey.Int(val) -} - -// The attributes used to report a single exception associated with a span. -const ( - // ExceptionEscapedKey is the attribute Key conforming to the - // "exception.escaped" semantic conventions. It represents the sHOULD be - // set to true if the exception event is recorded at a point where it is - // known that the exception is escaping the scope of the span. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Note: An exception is considered to have escaped (or left) the scope of - // a span, - // if that span is ended while the exception is still logically "in - // flight". - // This may be actually "in flight" in some languages (e.g. if the - // exception - // is passed to a Context manager's `__exit__` method in Python) but will - // usually be caught at the point of recording the exception in most - // languages. - // - // It is usually not possible to determine at the point where an exception - // is thrown - // whether it will escape the scope of a span. - // However, it is trivial to know that an exception - // will escape, if one checks for an active exception just before ending - // the span, - // as done in the [example above](#recording-an-exception). - // - // It follows that an exception may still escape the scope of the span - // even if the `exception.escaped` attribute was not set or set to false, - // since the event might have been recorded at a time where it was not - // clear whether the exception will escape. - ExceptionEscapedKey = attribute.Key("exception.escaped") -) - -// ExceptionEscaped returns an attribute KeyValue conforming to the -// "exception.escaped" semantic conventions. It represents the sHOULD be set to -// true if the exception event is recorded at a point where it is known that -// the exception is escaping the scope of the span. -func ExceptionEscaped(val bool) attribute.KeyValue { - return ExceptionEscapedKey.Bool(val) -} diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go deleted file mode 100644 index f40c97825..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -const ( - // ExceptionEventName is the name of the Span event representing an exception. - ExceptionEventName = "exception" -) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go deleted file mode 100644 index 9c1840631..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -// HTTP scheme attributes. -var ( - HTTPSchemeHTTP = HTTPSchemeKey.String("http") - HTTPSchemeHTTPS = HTTPSchemeKey.String("https") -) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go deleted file mode 100644 index 3d44dae27..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go +++ /dev/null @@ -1,2060 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -import "go.opentelemetry.io/otel/attribute" - -// The web browser in which the application represented by the resource is -// running. The `browser.*` attributes MUST be used only for resources that -// represent applications running in a web browser (regardless of whether -// running on a mobile or desktop device). -const ( - // BrowserBrandsKey is the attribute Key conforming to the "browser.brands" - // semantic conventions. It represents the array of brand name and version - // separated by a space - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: ' Not A;Brand 99', 'Chromium 99', 'Chrome 99' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.brands`). - BrowserBrandsKey = attribute.Key("browser.brands") - - // BrowserPlatformKey is the attribute Key conforming to the - // "browser.platform" semantic conventions. It represents the platform on - // which the browser is running - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Windows', 'macOS', 'Android' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.platform`). If unavailable, the legacy - // `navigator.platform` API SHOULD NOT be used instead and this attribute - // SHOULD be left unset in order for the values to be consistent. - // The list of possible values is defined in the [W3C User-Agent Client - // Hints - // specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). - // Note that some (but not all) of these values can overlap with values in - // the [`os.type` and `os.name` attributes](./os.md). However, for - // consistency, the values in the `browser.platform` attribute should - // capture the exact value that the user agent provides. - BrowserPlatformKey = attribute.Key("browser.platform") - - // BrowserMobileKey is the attribute Key conforming to the "browser.mobile" - // semantic conventions. It represents a boolean that is true if the - // browser is running on a mobile device - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.mobile`). If unavailable, this attribute - // SHOULD be left unset. - BrowserMobileKey = attribute.Key("browser.mobile") - - // BrowserLanguageKey is the attribute Key conforming to the - // "browser.language" semantic conventions. It represents the preferred - // language of the user using the browser - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'en', 'en-US', 'fr', 'fr-FR' - // Note: This value is intended to be taken from the Navigator API - // `navigator.language`. - BrowserLanguageKey = attribute.Key("browser.language") -) - -// BrowserBrands returns an attribute KeyValue conforming to the -// "browser.brands" semantic conventions. It represents the array of brand name -// and version separated by a space -func BrowserBrands(val ...string) attribute.KeyValue { - return BrowserBrandsKey.StringSlice(val) -} - -// BrowserPlatform returns an attribute KeyValue conforming to the -// "browser.platform" semantic conventions. It represents the platform on which -// the browser is running -func BrowserPlatform(val string) attribute.KeyValue { - return BrowserPlatformKey.String(val) -} - -// BrowserMobile returns an attribute KeyValue conforming to the -// "browser.mobile" semantic conventions. It represents a boolean that is true -// if the browser is running on a mobile device -func BrowserMobile(val bool) attribute.KeyValue { - return BrowserMobileKey.Bool(val) -} - -// BrowserLanguage returns an attribute KeyValue conforming to the -// "browser.language" semantic conventions. It represents the preferred -// language of the user using the browser -func BrowserLanguage(val string) attribute.KeyValue { - return BrowserLanguageKey.String(val) -} - -// A cloud environment (e.g. GCP, Azure, AWS) -const ( - // CloudProviderKey is the attribute Key conforming to the "cloud.provider" - // semantic conventions. It represents the name of the cloud provider. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - CloudProviderKey = attribute.Key("cloud.provider") - - // CloudAccountIDKey is the attribute Key conforming to the - // "cloud.account.id" semantic conventions. It represents the cloud account - // ID the resource is assigned to. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '111111111111', 'opentelemetry' - CloudAccountIDKey = attribute.Key("cloud.account.id") - - // CloudRegionKey is the attribute Key conforming to the "cloud.region" - // semantic conventions. It represents the geographical region the resource - // is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-central1', 'us-east-1' - // Note: Refer to your provider's docs to see the available regions, for - // example [Alibaba Cloud - // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS - // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), - // [Azure - // regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), - // [Google Cloud regions](https://cloud.google.com/about/locations), or - // [Tencent Cloud - // regions](https://www.tencentcloud.com/document/product/213/6091). - CloudRegionKey = attribute.Key("cloud.region") - - // CloudResourceIDKey is the attribute Key conforming to the - // "cloud.resource_id" semantic conventions. It represents the cloud - // provider-specific native identifier of the monitored cloud resource - // (e.g. an - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // on AWS, a [fully qualified resource - // ID](https://learn.microsoft.com/en-us/rest/api/resources/resources/get-by-id) - // on Azure, a [full resource - // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // on GCP) - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:lambda:REGION:ACCOUNT_ID:function:my-function', - // '//run.googleapis.com/projects/PROJECT_ID/locations/LOCATION_ID/services/SERVICE_ID', - // '/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/' - // Note: On some cloud providers, it may not be possible to determine the - // full ID at startup, - // so it may be necessary to set `cloud.resource_id` as a span attribute - // instead. - // - // The exact value to use for `cloud.resource_id` depends on the cloud - // provider. - // The following well-known definitions MUST be used if you set this - // attribute and they apply: - // - // * **AWS Lambda:** The function - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - // Take care not to use the "invoked ARN" directly but replace any - // [alias - // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) - // with the resolved function version, as the same runtime instance may - // be invokable with - // multiple different aliases. - // * **GCP:** The [URI of the - // resource](https://cloud.google.com/iam/docs/full-resource-names) - // * **Azure:** The [Fully Qualified Resource - // ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id) - // of the invoked function, - // *not* the function app, having the form - // `/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/`. - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider. - CloudResourceIDKey = attribute.Key("cloud.resource_id") - - // CloudAvailabilityZoneKey is the attribute Key conforming to the - // "cloud.availability_zone" semantic conventions. It represents the cloud - // regions often have multiple, isolated locations known as zones to - // increase availability. Availability zone represents the zone where the - // resource is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-east-1c' - // Note: Availability zones are called "zones" on Alibaba Cloud and Google - // Cloud. - CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") - - // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" - // semantic conventions. It represents the cloud platform in use. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: The prefix of the service SHOULD match the one specified in - // `cloud.provider`. - CloudPlatformKey = attribute.Key("cloud.platform") -) - -var ( - // Alibaba Cloud - CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") - // Amazon Web Services - CloudProviderAWS = CloudProviderKey.String("aws") - // Microsoft Azure - CloudProviderAzure = CloudProviderKey.String("azure") - // Google Cloud Platform - CloudProviderGCP = CloudProviderKey.String("gcp") - // Heroku Platform as a Service - CloudProviderHeroku = CloudProviderKey.String("heroku") - // IBM Cloud - CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") - // Tencent Cloud - CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") -) - -var ( - // Alibaba Cloud Elastic Compute Service - CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") - // Alibaba Cloud Function Compute - CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") - // Red Hat OpenShift on Alibaba Cloud - CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") - // AWS Elastic Compute Cloud - CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") - // AWS Elastic Container Service - CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") - // AWS Elastic Kubernetes Service - CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") - // AWS Lambda - CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") - // AWS Elastic Beanstalk - CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") - // AWS App Runner - CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") - // Red Hat OpenShift on AWS (ROSA) - CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") - // Azure Virtual Machines - CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") - // Azure Container Instances - CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") - // Azure Kubernetes Service - CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") - // Azure Functions - CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") - // Azure App Service - CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") - // Azure Red Hat OpenShift - CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") - // Google Cloud Compute Engine (GCE) - CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") - // Google Cloud Run - CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") - // Google Cloud Kubernetes Engine (GKE) - CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") - // Google Cloud Functions (GCF) - CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") - // Google Cloud App Engine (GAE) - CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") - // Red Hat OpenShift on Google Cloud - CloudPlatformGCPOpenshift = CloudPlatformKey.String("gcp_openshift") - // Red Hat OpenShift on IBM Cloud - CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") - // Tencent Cloud Cloud Virtual Machine (CVM) - CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") - // Tencent Cloud Elastic Kubernetes Service (EKS) - CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") - // Tencent Cloud Serverless Cloud Function (SCF) - CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") -) - -// CloudAccountID returns an attribute KeyValue conforming to the -// "cloud.account.id" semantic conventions. It represents the cloud account ID -// the resource is assigned to. -func CloudAccountID(val string) attribute.KeyValue { - return CloudAccountIDKey.String(val) -} - -// CloudRegion returns an attribute KeyValue conforming to the -// "cloud.region" semantic conventions. It represents the geographical region -// the resource is running. -func CloudRegion(val string) attribute.KeyValue { - return CloudRegionKey.String(val) -} - -// CloudResourceID returns an attribute KeyValue conforming to the -// "cloud.resource_id" semantic conventions. It represents the cloud -// provider-specific native identifier of the monitored cloud resource (e.g. an -// [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) -// on AWS, a [fully qualified resource -// ID](https://learn.microsoft.com/en-us/rest/api/resources/resources/get-by-id) -// on Azure, a [full resource -// name](https://cloud.google.com/apis/design/resource_names#full_resource_name) -// on GCP) -func CloudResourceID(val string) attribute.KeyValue { - return CloudResourceIDKey.String(val) -} - -// CloudAvailabilityZone returns an attribute KeyValue conforming to the -// "cloud.availability_zone" semantic conventions. It represents the cloud -// regions often have multiple, isolated locations known as zones to increase -// availability. Availability zone represents the zone where the resource is -// running. -func CloudAvailabilityZone(val string) attribute.KeyValue { - return CloudAvailabilityZoneKey.String(val) -} - -// Resources used by AWS Elastic Container Service (ECS). -const ( - // AWSECSContainerARNKey is the attribute Key conforming to the - // "aws.ecs.container.arn" semantic conventions. It represents the Amazon - // Resource Name (ARN) of an [ECS container - // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:container/32624152-9086-4f0e-acae-1a75b14fe4d9' - AWSECSContainerARNKey = attribute.Key("aws.ecs.container.arn") - - // AWSECSClusterARNKey is the attribute Key conforming to the - // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an - // [ECS - // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSECSClusterARNKey = attribute.Key("aws.ecs.cluster.arn") - - // AWSECSLaunchtypeKey is the attribute Key conforming to the - // "aws.ecs.launchtype" semantic conventions. It represents the [launch - // type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) - // for an ECS task. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - AWSECSLaunchtypeKey = attribute.Key("aws.ecs.launchtype") - - // AWSECSTaskARNKey is the attribute Key conforming to the - // "aws.ecs.task.arn" semantic conventions. It represents the ARN of an - // [ECS task - // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:task/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSECSTaskARNKey = attribute.Key("aws.ecs.task.arn") - - // AWSECSTaskFamilyKey is the attribute Key conforming to the - // "aws.ecs.task.family" semantic conventions. It represents the task - // definition family this task definition is a member of. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-family' - AWSECSTaskFamilyKey = attribute.Key("aws.ecs.task.family") - - // AWSECSTaskRevisionKey is the attribute Key conforming to the - // "aws.ecs.task.revision" semantic conventions. It represents the revision - // for this task definition. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '8', '26' - AWSECSTaskRevisionKey = attribute.Key("aws.ecs.task.revision") -) - -var ( - // ec2 - AWSECSLaunchtypeEC2 = AWSECSLaunchtypeKey.String("ec2") - // fargate - AWSECSLaunchtypeFargate = AWSECSLaunchtypeKey.String("fargate") -) - -// AWSECSContainerARN returns an attribute KeyValue conforming to the -// "aws.ecs.container.arn" semantic conventions. It represents the Amazon -// Resource Name (ARN) of an [ECS container -// instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). -func AWSECSContainerARN(val string) attribute.KeyValue { - return AWSECSContainerARNKey.String(val) -} - -// AWSECSClusterARN returns an attribute KeyValue conforming to the -// "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an [ECS -// cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). -func AWSECSClusterARN(val string) attribute.KeyValue { - return AWSECSClusterARNKey.String(val) -} - -// AWSECSTaskARN returns an attribute KeyValue conforming to the -// "aws.ecs.task.arn" semantic conventions. It represents the ARN of an [ECS -// task -// definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). -func AWSECSTaskARN(val string) attribute.KeyValue { - return AWSECSTaskARNKey.String(val) -} - -// AWSECSTaskFamily returns an attribute KeyValue conforming to the -// "aws.ecs.task.family" semantic conventions. It represents the task -// definition family this task definition is a member of. -func AWSECSTaskFamily(val string) attribute.KeyValue { - return AWSECSTaskFamilyKey.String(val) -} - -// AWSECSTaskRevision returns an attribute KeyValue conforming to the -// "aws.ecs.task.revision" semantic conventions. It represents the revision for -// this task definition. -func AWSECSTaskRevision(val string) attribute.KeyValue { - return AWSECSTaskRevisionKey.String(val) -} - -// Resources used by AWS Elastic Kubernetes Service (EKS). -const ( - // AWSEKSClusterARNKey is the attribute Key conforming to the - // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an - // EKS cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSEKSClusterARNKey = attribute.Key("aws.eks.cluster.arn") -) - -// AWSEKSClusterARN returns an attribute KeyValue conforming to the -// "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an EKS -// cluster. -func AWSEKSClusterARN(val string) attribute.KeyValue { - return AWSEKSClusterARNKey.String(val) -} - -// Resources specific to Amazon Web Services. -const ( - // AWSLogGroupNamesKey is the attribute Key conforming to the - // "aws.log.group.names" semantic conventions. It represents the name(s) of - // the AWS log group(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '/aws/lambda/my-function', 'opentelemetry-service' - // Note: Multiple log groups must be supported for cases like - // multi-container applications, where a single application has sidecar - // containers, and each write to their own log group. - AWSLogGroupNamesKey = attribute.Key("aws.log.group.names") - - // AWSLogGroupARNsKey is the attribute Key conforming to the - // "aws.log.group.arns" semantic conventions. It represents the Amazon - // Resource Name(s) (ARN) of the AWS log group(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:*' - // Note: See the [log group ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - AWSLogGroupARNsKey = attribute.Key("aws.log.group.arns") - - // AWSLogStreamNamesKey is the attribute Key conforming to the - // "aws.log.stream.names" semantic conventions. It represents the name(s) - // of the AWS log stream(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSLogStreamNamesKey = attribute.Key("aws.log.stream.names") - - // AWSLogStreamARNsKey is the attribute Key conforming to the - // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of - // the AWS log stream(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:log-stream:logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - // Note: See the [log stream ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - // One log group can contain several log streams, so these ARNs necessarily - // identify both a log group and a log stream. - AWSLogStreamARNsKey = attribute.Key("aws.log.stream.arns") -) - -// AWSLogGroupNames returns an attribute KeyValue conforming to the -// "aws.log.group.names" semantic conventions. It represents the name(s) of the -// AWS log group(s) an application is writing to. -func AWSLogGroupNames(val ...string) attribute.KeyValue { - return AWSLogGroupNamesKey.StringSlice(val) -} - -// AWSLogGroupARNs returns an attribute KeyValue conforming to the -// "aws.log.group.arns" semantic conventions. It represents the Amazon Resource -// Name(s) (ARN) of the AWS log group(s). -func AWSLogGroupARNs(val ...string) attribute.KeyValue { - return AWSLogGroupARNsKey.StringSlice(val) -} - -// AWSLogStreamNames returns an attribute KeyValue conforming to the -// "aws.log.stream.names" semantic conventions. It represents the name(s) of -// the AWS log stream(s) an application is writing to. -func AWSLogStreamNames(val ...string) attribute.KeyValue { - return AWSLogStreamNamesKey.StringSlice(val) -} - -// AWSLogStreamARNs returns an attribute KeyValue conforming to the -// "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of the -// AWS log stream(s). -func AWSLogStreamARNs(val ...string) attribute.KeyValue { - return AWSLogStreamARNsKey.StringSlice(val) -} - -// Heroku dyno metadata -const ( - // HerokuReleaseCreationTimestampKey is the attribute Key conforming to the - // "heroku.release.creation_timestamp" semantic conventions. It represents - // the time and date the release was created - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2022-10-23T18:00:42Z' - HerokuReleaseCreationTimestampKey = attribute.Key("heroku.release.creation_timestamp") - - // HerokuReleaseCommitKey is the attribute Key conforming to the - // "heroku.release.commit" semantic conventions. It represents the commit - // hash for the current release - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'e6134959463efd8966b20e75b913cafe3f5ec' - HerokuReleaseCommitKey = attribute.Key("heroku.release.commit") - - // HerokuAppIDKey is the attribute Key conforming to the "heroku.app.id" - // semantic conventions. It represents the unique identifier for the - // application - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2daa2797-e42b-4624-9322-ec3f968df4da' - HerokuAppIDKey = attribute.Key("heroku.app.id") -) - -// HerokuReleaseCreationTimestamp returns an attribute KeyValue conforming -// to the "heroku.release.creation_timestamp" semantic conventions. It -// represents the time and date the release was created -func HerokuReleaseCreationTimestamp(val string) attribute.KeyValue { - return HerokuReleaseCreationTimestampKey.String(val) -} - -// HerokuReleaseCommit returns an attribute KeyValue conforming to the -// "heroku.release.commit" semantic conventions. It represents the commit hash -// for the current release -func HerokuReleaseCommit(val string) attribute.KeyValue { - return HerokuReleaseCommitKey.String(val) -} - -// HerokuAppID returns an attribute KeyValue conforming to the -// "heroku.app.id" semantic conventions. It represents the unique identifier -// for the application -func HerokuAppID(val string) attribute.KeyValue { - return HerokuAppIDKey.String(val) -} - -// A container instance. -const ( - // ContainerNameKey is the attribute Key conforming to the "container.name" - // semantic conventions. It represents the container name used by container - // runtime. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-autoconf' - ContainerNameKey = attribute.Key("container.name") - - // ContainerIDKey is the attribute Key conforming to the "container.id" - // semantic conventions. It represents the container ID. Usually a UUID, as - // for example used to [identify Docker - // containers](https://docs.docker.com/engine/reference/run/#container-identification). - // The UUID might be abbreviated. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'a3bf90e006b2' - ContainerIDKey = attribute.Key("container.id") - - // ContainerRuntimeKey is the attribute Key conforming to the - // "container.runtime" semantic conventions. It represents the container - // runtime managing this container. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'docker', 'containerd', 'rkt' - ContainerRuntimeKey = attribute.Key("container.runtime") - - // ContainerImageNameKey is the attribute Key conforming to the - // "container.image.name" semantic conventions. It represents the name of - // the image the container was built on. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'gcr.io/opentelemetry/operator' - ContainerImageNameKey = attribute.Key("container.image.name") - - // ContainerImageTagKey is the attribute Key conforming to the - // "container.image.tag" semantic conventions. It represents the container - // image tag. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0.1' - ContainerImageTagKey = attribute.Key("container.image.tag") -) - -// ContainerName returns an attribute KeyValue conforming to the -// "container.name" semantic conventions. It represents the container name used -// by container runtime. -func ContainerName(val string) attribute.KeyValue { - return ContainerNameKey.String(val) -} - -// ContainerID returns an attribute KeyValue conforming to the -// "container.id" semantic conventions. It represents the container ID. Usually -// a UUID, as for example used to [identify Docker -// containers](https://docs.docker.com/engine/reference/run/#container-identification). -// The UUID might be abbreviated. -func ContainerID(val string) attribute.KeyValue { - return ContainerIDKey.String(val) -} - -// ContainerRuntime returns an attribute KeyValue conforming to the -// "container.runtime" semantic conventions. It represents the container -// runtime managing this container. -func ContainerRuntime(val string) attribute.KeyValue { - return ContainerRuntimeKey.String(val) -} - -// ContainerImageName returns an attribute KeyValue conforming to the -// "container.image.name" semantic conventions. It represents the name of the -// image the container was built on. -func ContainerImageName(val string) attribute.KeyValue { - return ContainerImageNameKey.String(val) -} - -// ContainerImageTag returns an attribute KeyValue conforming to the -// "container.image.tag" semantic conventions. It represents the container -// image tag. -func ContainerImageTag(val string) attribute.KeyValue { - return ContainerImageTagKey.String(val) -} - -// The software deployment. -const ( - // DeploymentEnvironmentKey is the attribute Key conforming to the - // "deployment.environment" semantic conventions. It represents the name of - // the [deployment - // environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka - // deployment tier). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'staging', 'production' - DeploymentEnvironmentKey = attribute.Key("deployment.environment") -) - -// DeploymentEnvironment returns an attribute KeyValue conforming to the -// "deployment.environment" semantic conventions. It represents the name of the -// [deployment -// environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka -// deployment tier). -func DeploymentEnvironment(val string) attribute.KeyValue { - return DeploymentEnvironmentKey.String(val) -} - -// The device on which the process represented by this resource is running. -const ( - // DeviceIDKey is the attribute Key conforming to the "device.id" semantic - // conventions. It represents a unique identifier representing the device - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' - // Note: The device identifier MUST only be defined using the values - // outlined below. This value is not an advertising identifier and MUST NOT - // be used as such. On iOS (Swift or Objective-C), this value MUST be equal - // to the [vendor - // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). - // On Android (Java or Kotlin), this value MUST be equal to the Firebase - // Installation ID or a globally unique UUID which is persisted across - // sessions in your application. More information can be found - // [here](https://developer.android.com/training/articles/user-data-ids) on - // best practices and exact implementation details. Caution should be taken - // when storing personal data or anything which can identify a user. GDPR - // and data protection laws may apply, ensure you do your own due - // diligence. - DeviceIDKey = attribute.Key("device.id") - - // DeviceModelIdentifierKey is the attribute Key conforming to the - // "device.model.identifier" semantic conventions. It represents the model - // identifier for the device - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iPhone3,4', 'SM-G920F' - // Note: It's recommended this value represents a machine readable version - // of the model identifier rather than the market or consumer-friendly name - // of the device. - DeviceModelIdentifierKey = attribute.Key("device.model.identifier") - - // DeviceModelNameKey is the attribute Key conforming to the - // "device.model.name" semantic conventions. It represents the marketing - // name for the device model - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' - // Note: It's recommended this value represents a human readable version of - // the device model rather than a machine readable alternative. - DeviceModelNameKey = attribute.Key("device.model.name") - - // DeviceManufacturerKey is the attribute Key conforming to the - // "device.manufacturer" semantic conventions. It represents the name of - // the device manufacturer - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Apple', 'Samsung' - // Note: The Android OS provides this field via - // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). - // iOS apps SHOULD hardcode the value `Apple`. - DeviceManufacturerKey = attribute.Key("device.manufacturer") -) - -// DeviceID returns an attribute KeyValue conforming to the "device.id" -// semantic conventions. It represents a unique identifier representing the -// device -func DeviceID(val string) attribute.KeyValue { - return DeviceIDKey.String(val) -} - -// DeviceModelIdentifier returns an attribute KeyValue conforming to the -// "device.model.identifier" semantic conventions. It represents the model -// identifier for the device -func DeviceModelIdentifier(val string) attribute.KeyValue { - return DeviceModelIdentifierKey.String(val) -} - -// DeviceModelName returns an attribute KeyValue conforming to the -// "device.model.name" semantic conventions. It represents the marketing name -// for the device model -func DeviceModelName(val string) attribute.KeyValue { - return DeviceModelNameKey.String(val) -} - -// DeviceManufacturer returns an attribute KeyValue conforming to the -// "device.manufacturer" semantic conventions. It represents the name of the -// device manufacturer -func DeviceManufacturer(val string) attribute.KeyValue { - return DeviceManufacturerKey.String(val) -} - -// A serverless instance. -const ( - // FaaSNameKey is the attribute Key conforming to the "faas.name" semantic - // conventions. It represents the name of the single function that this - // runtime instance executes. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'my-function', 'myazurefunctionapp/some-function-name' - // Note: This is the name of the function as configured/deployed on the - // FaaS - // platform and is usually different from the name of the callback - // function (which may be stored in the - // [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) - // span attributes). - // - // For some cloud providers, the above definition is ambiguous. The - // following - // definition of function name MUST be used for this attribute - // (and consequently the span name) for the listed cloud - // providers/products: - // - // * **Azure:** The full name `/`, i.e., function app name - // followed by a forward slash followed by the function name (this form - // can also be seen in the resource JSON for the function). - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider (see also the `cloud.resource_id` attribute). - FaaSNameKey = attribute.Key("faas.name") - - // FaaSVersionKey is the attribute Key conforming to the "faas.version" - // semantic conventions. It represents the immutable version of the - // function being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '26', 'pinkfroid-00002' - // Note: Depending on the cloud provider and platform, use: - // - // * **AWS Lambda:** The [function - // version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - // (an integer represented as a decimal string). - // * **Google Cloud Run:** The - // [revision](https://cloud.google.com/run/docs/managing/revisions) - // (i.e., the function name plus the revision suffix). - // * **Google Cloud Functions:** The value of the - // [`K_REVISION` environment - // variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - // * **Azure Functions:** Not applicable. Do not set this attribute. - FaaSVersionKey = attribute.Key("faas.version") - - // FaaSInstanceKey is the attribute Key conforming to the "faas.instance" - // semantic conventions. It represents the execution environment ID as a - // string, that will be potentially reused for other invocations to the - // same function/function version. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2021/06/28/[$LATEST]2f399eb14537447da05ab2a2e39309de' - // Note: * **AWS Lambda:** Use the (full) log stream name. - FaaSInstanceKey = attribute.Key("faas.instance") - - // FaaSMaxMemoryKey is the attribute Key conforming to the - // "faas.max_memory" semantic conventions. It represents the amount of - // memory available to the serverless function converted to Bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 134217728 - // Note: It's recommended to set this attribute since e.g. too little - // memory can easily stop a Java AWS Lambda function from working - // correctly. On AWS Lambda, the environment variable - // `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information (which must - // be multiplied by 1,048,576). - FaaSMaxMemoryKey = attribute.Key("faas.max_memory") -) - -// FaaSName returns an attribute KeyValue conforming to the "faas.name" -// semantic conventions. It represents the name of the single function that -// this runtime instance executes. -func FaaSName(val string) attribute.KeyValue { - return FaaSNameKey.String(val) -} - -// FaaSVersion returns an attribute KeyValue conforming to the -// "faas.version" semantic conventions. It represents the immutable version of -// the function being executed. -func FaaSVersion(val string) attribute.KeyValue { - return FaaSVersionKey.String(val) -} - -// FaaSInstance returns an attribute KeyValue conforming to the -// "faas.instance" semantic conventions. It represents the execution -// environment ID as a string, that will be potentially reused for other -// invocations to the same function/function version. -func FaaSInstance(val string) attribute.KeyValue { - return FaaSInstanceKey.String(val) -} - -// FaaSMaxMemory returns an attribute KeyValue conforming to the -// "faas.max_memory" semantic conventions. It represents the amount of memory -// available to the serverless function converted to Bytes. -func FaaSMaxMemory(val int) attribute.KeyValue { - return FaaSMaxMemoryKey.Int(val) -} - -// A host is defined as a general computing instance. -const ( - // HostIDKey is the attribute Key conforming to the "host.id" semantic - // conventions. It represents the unique host ID. For Cloud, this must be - // the instance_id assigned by the cloud provider. For non-containerized - // systems, this should be the `machine-id`. See the table below for the - // sources to use to determine the `machine-id` based on operating system. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'fdbf79e8af94cb7f9e8df36789187052' - HostIDKey = attribute.Key("host.id") - - // HostNameKey is the attribute Key conforming to the "host.name" semantic - // conventions. It represents the name of the host. On Unix systems, it may - // contain what the hostname command returns, or the fully qualified - // hostname, or another name specified by the user. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-test' - HostNameKey = attribute.Key("host.name") - - // HostTypeKey is the attribute Key conforming to the "host.type" semantic - // conventions. It represents the type of host. For Cloud, this must be the - // machine type. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'n1-standard-1' - HostTypeKey = attribute.Key("host.type") - - // HostArchKey is the attribute Key conforming to the "host.arch" semantic - // conventions. It represents the CPU architecture the host system is - // running on. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - HostArchKey = attribute.Key("host.arch") - - // HostImageNameKey is the attribute Key conforming to the - // "host.image.name" semantic conventions. It represents the name of the VM - // image or OS install the host was instantiated from. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'infra-ami-eks-worker-node-7d4ec78312', 'CentOS-8-x86_64-1905' - HostImageNameKey = attribute.Key("host.image.name") - - // HostImageIDKey is the attribute Key conforming to the "host.image.id" - // semantic conventions. It represents the vM image ID. For Cloud, this - // value is from the provider. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ami-07b06b442921831e5' - HostImageIDKey = attribute.Key("host.image.id") - - // HostImageVersionKey is the attribute Key conforming to the - // "host.image.version" semantic conventions. It represents the version - // string of the VM image as defined in [Version - // Attributes](README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0.1' - HostImageVersionKey = attribute.Key("host.image.version") -) - -var ( - // AMD64 - HostArchAMD64 = HostArchKey.String("amd64") - // ARM32 - HostArchARM32 = HostArchKey.String("arm32") - // ARM64 - HostArchARM64 = HostArchKey.String("arm64") - // Itanium - HostArchIA64 = HostArchKey.String("ia64") - // 32-bit PowerPC - HostArchPPC32 = HostArchKey.String("ppc32") - // 64-bit PowerPC - HostArchPPC64 = HostArchKey.String("ppc64") - // IBM z/Architecture - HostArchS390x = HostArchKey.String("s390x") - // 32-bit x86 - HostArchX86 = HostArchKey.String("x86") -) - -// HostID returns an attribute KeyValue conforming to the "host.id" semantic -// conventions. It represents the unique host ID. For Cloud, this must be the -// instance_id assigned by the cloud provider. For non-containerized systems, -// this should be the `machine-id`. See the table below for the sources to use -// to determine the `machine-id` based on operating system. -func HostID(val string) attribute.KeyValue { - return HostIDKey.String(val) -} - -// HostName returns an attribute KeyValue conforming to the "host.name" -// semantic conventions. It represents the name of the host. On Unix systems, -// it may contain what the hostname command returns, or the fully qualified -// hostname, or another name specified by the user. -func HostName(val string) attribute.KeyValue { - return HostNameKey.String(val) -} - -// HostType returns an attribute KeyValue conforming to the "host.type" -// semantic conventions. It represents the type of host. For Cloud, this must -// be the machine type. -func HostType(val string) attribute.KeyValue { - return HostTypeKey.String(val) -} - -// HostImageName returns an attribute KeyValue conforming to the -// "host.image.name" semantic conventions. It represents the name of the VM -// image or OS install the host was instantiated from. -func HostImageName(val string) attribute.KeyValue { - return HostImageNameKey.String(val) -} - -// HostImageID returns an attribute KeyValue conforming to the -// "host.image.id" semantic conventions. It represents the vM image ID. For -// Cloud, this value is from the provider. -func HostImageID(val string) attribute.KeyValue { - return HostImageIDKey.String(val) -} - -// HostImageVersion returns an attribute KeyValue conforming to the -// "host.image.version" semantic conventions. It represents the version string -// of the VM image as defined in [Version -// Attributes](README.md#version-attributes). -func HostImageVersion(val string) attribute.KeyValue { - return HostImageVersionKey.String(val) -} - -// A Kubernetes Cluster. -const ( - // K8SClusterNameKey is the attribute Key conforming to the - // "k8s.cluster.name" semantic conventions. It represents the name of the - // cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-cluster' - K8SClusterNameKey = attribute.Key("k8s.cluster.name") -) - -// K8SClusterName returns an attribute KeyValue conforming to the -// "k8s.cluster.name" semantic conventions. It represents the name of the -// cluster. -func K8SClusterName(val string) attribute.KeyValue { - return K8SClusterNameKey.String(val) -} - -// A Kubernetes Node object. -const ( - // K8SNodeNameKey is the attribute Key conforming to the "k8s.node.name" - // semantic conventions. It represents the name of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'node-1' - K8SNodeNameKey = attribute.Key("k8s.node.name") - - // K8SNodeUIDKey is the attribute Key conforming to the "k8s.node.uid" - // semantic conventions. It represents the UID of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2' - K8SNodeUIDKey = attribute.Key("k8s.node.uid") -) - -// K8SNodeName returns an attribute KeyValue conforming to the -// "k8s.node.name" semantic conventions. It represents the name of the Node. -func K8SNodeName(val string) attribute.KeyValue { - return K8SNodeNameKey.String(val) -} - -// K8SNodeUID returns an attribute KeyValue conforming to the "k8s.node.uid" -// semantic conventions. It represents the UID of the Node. -func K8SNodeUID(val string) attribute.KeyValue { - return K8SNodeUIDKey.String(val) -} - -// A Kubernetes Namespace. -const ( - // K8SNamespaceNameKey is the attribute Key conforming to the - // "k8s.namespace.name" semantic conventions. It represents the name of the - // namespace that the pod is running in. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'default' - K8SNamespaceNameKey = attribute.Key("k8s.namespace.name") -) - -// K8SNamespaceName returns an attribute KeyValue conforming to the -// "k8s.namespace.name" semantic conventions. It represents the name of the -// namespace that the pod is running in. -func K8SNamespaceName(val string) attribute.KeyValue { - return K8SNamespaceNameKey.String(val) -} - -// A Kubernetes Pod object. -const ( - // K8SPodUIDKey is the attribute Key conforming to the "k8s.pod.uid" - // semantic conventions. It represents the UID of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SPodUIDKey = attribute.Key("k8s.pod.uid") - - // K8SPodNameKey is the attribute Key conforming to the "k8s.pod.name" - // semantic conventions. It represents the name of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-pod-autoconf' - K8SPodNameKey = attribute.Key("k8s.pod.name") -) - -// K8SPodUID returns an attribute KeyValue conforming to the "k8s.pod.uid" -// semantic conventions. It represents the UID of the Pod. -func K8SPodUID(val string) attribute.KeyValue { - return K8SPodUIDKey.String(val) -} - -// K8SPodName returns an attribute KeyValue conforming to the "k8s.pod.name" -// semantic conventions. It represents the name of the Pod. -func K8SPodName(val string) attribute.KeyValue { - return K8SPodNameKey.String(val) -} - -// A container in a -// [PodTemplate](https://kubernetes.io/docs/concepts/workloads/pods/#pod-templates). -const ( - // K8SContainerNameKey is the attribute Key conforming to the - // "k8s.container.name" semantic conventions. It represents the name of the - // Container from Pod specification, must be unique within a Pod. Container - // runtime usually uses different globally unique name (`container.name`). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'redis' - K8SContainerNameKey = attribute.Key("k8s.container.name") - - // K8SContainerRestartCountKey is the attribute Key conforming to the - // "k8s.container.restart_count" semantic conventions. It represents the - // number of times the container was restarted. This attribute can be used - // to identify a particular container (running or stopped) within a - // container spec. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 0, 2 - K8SContainerRestartCountKey = attribute.Key("k8s.container.restart_count") -) - -// K8SContainerName returns an attribute KeyValue conforming to the -// "k8s.container.name" semantic conventions. It represents the name of the -// Container from Pod specification, must be unique within a Pod. Container -// runtime usually uses different globally unique name (`container.name`). -func K8SContainerName(val string) attribute.KeyValue { - return K8SContainerNameKey.String(val) -} - -// K8SContainerRestartCount returns an attribute KeyValue conforming to the -// "k8s.container.restart_count" semantic conventions. It represents the number -// of times the container was restarted. This attribute can be used to identify -// a particular container (running or stopped) within a container spec. -func K8SContainerRestartCount(val int) attribute.KeyValue { - return K8SContainerRestartCountKey.Int(val) -} - -// A Kubernetes ReplicaSet object. -const ( - // K8SReplicaSetUIDKey is the attribute Key conforming to the - // "k8s.replicaset.uid" semantic conventions. It represents the UID of the - // ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SReplicaSetUIDKey = attribute.Key("k8s.replicaset.uid") - - // K8SReplicaSetNameKey is the attribute Key conforming to the - // "k8s.replicaset.name" semantic conventions. It represents the name of - // the ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SReplicaSetNameKey = attribute.Key("k8s.replicaset.name") -) - -// K8SReplicaSetUID returns an attribute KeyValue conforming to the -// "k8s.replicaset.uid" semantic conventions. It represents the UID of the -// ReplicaSet. -func K8SReplicaSetUID(val string) attribute.KeyValue { - return K8SReplicaSetUIDKey.String(val) -} - -// K8SReplicaSetName returns an attribute KeyValue conforming to the -// "k8s.replicaset.name" semantic conventions. It represents the name of the -// ReplicaSet. -func K8SReplicaSetName(val string) attribute.KeyValue { - return K8SReplicaSetNameKey.String(val) -} - -// A Kubernetes Deployment object. -const ( - // K8SDeploymentUIDKey is the attribute Key conforming to the - // "k8s.deployment.uid" semantic conventions. It represents the UID of the - // Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDeploymentUIDKey = attribute.Key("k8s.deployment.uid") - - // K8SDeploymentNameKey is the attribute Key conforming to the - // "k8s.deployment.name" semantic conventions. It represents the name of - // the Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SDeploymentNameKey = attribute.Key("k8s.deployment.name") -) - -// K8SDeploymentUID returns an attribute KeyValue conforming to the -// "k8s.deployment.uid" semantic conventions. It represents the UID of the -// Deployment. -func K8SDeploymentUID(val string) attribute.KeyValue { - return K8SDeploymentUIDKey.String(val) -} - -// K8SDeploymentName returns an attribute KeyValue conforming to the -// "k8s.deployment.name" semantic conventions. It represents the name of the -// Deployment. -func K8SDeploymentName(val string) attribute.KeyValue { - return K8SDeploymentNameKey.String(val) -} - -// A Kubernetes StatefulSet object. -const ( - // K8SStatefulSetUIDKey is the attribute Key conforming to the - // "k8s.statefulset.uid" semantic conventions. It represents the UID of the - // StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SStatefulSetUIDKey = attribute.Key("k8s.statefulset.uid") - - // K8SStatefulSetNameKey is the attribute Key conforming to the - // "k8s.statefulset.name" semantic conventions. It represents the name of - // the StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SStatefulSetNameKey = attribute.Key("k8s.statefulset.name") -) - -// K8SStatefulSetUID returns an attribute KeyValue conforming to the -// "k8s.statefulset.uid" semantic conventions. It represents the UID of the -// StatefulSet. -func K8SStatefulSetUID(val string) attribute.KeyValue { - return K8SStatefulSetUIDKey.String(val) -} - -// K8SStatefulSetName returns an attribute KeyValue conforming to the -// "k8s.statefulset.name" semantic conventions. It represents the name of the -// StatefulSet. -func K8SStatefulSetName(val string) attribute.KeyValue { - return K8SStatefulSetNameKey.String(val) -} - -// A Kubernetes DaemonSet object. -const ( - // K8SDaemonSetUIDKey is the attribute Key conforming to the - // "k8s.daemonset.uid" semantic conventions. It represents the UID of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDaemonSetUIDKey = attribute.Key("k8s.daemonset.uid") - - // K8SDaemonSetNameKey is the attribute Key conforming to the - // "k8s.daemonset.name" semantic conventions. It represents the name of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SDaemonSetNameKey = attribute.Key("k8s.daemonset.name") -) - -// K8SDaemonSetUID returns an attribute KeyValue conforming to the -// "k8s.daemonset.uid" semantic conventions. It represents the UID of the -// DaemonSet. -func K8SDaemonSetUID(val string) attribute.KeyValue { - return K8SDaemonSetUIDKey.String(val) -} - -// K8SDaemonSetName returns an attribute KeyValue conforming to the -// "k8s.daemonset.name" semantic conventions. It represents the name of the -// DaemonSet. -func K8SDaemonSetName(val string) attribute.KeyValue { - return K8SDaemonSetNameKey.String(val) -} - -// A Kubernetes Job object. -const ( - // K8SJobUIDKey is the attribute Key conforming to the "k8s.job.uid" - // semantic conventions. It represents the UID of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SJobUIDKey = attribute.Key("k8s.job.uid") - - // K8SJobNameKey is the attribute Key conforming to the "k8s.job.name" - // semantic conventions. It represents the name of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SJobNameKey = attribute.Key("k8s.job.name") -) - -// K8SJobUID returns an attribute KeyValue conforming to the "k8s.job.uid" -// semantic conventions. It represents the UID of the Job. -func K8SJobUID(val string) attribute.KeyValue { - return K8SJobUIDKey.String(val) -} - -// K8SJobName returns an attribute KeyValue conforming to the "k8s.job.name" -// semantic conventions. It represents the name of the Job. -func K8SJobName(val string) attribute.KeyValue { - return K8SJobNameKey.String(val) -} - -// A Kubernetes CronJob object. -const ( - // K8SCronJobUIDKey is the attribute Key conforming to the - // "k8s.cronjob.uid" semantic conventions. It represents the UID of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SCronJobUIDKey = attribute.Key("k8s.cronjob.uid") - - // K8SCronJobNameKey is the attribute Key conforming to the - // "k8s.cronjob.name" semantic conventions. It represents the name of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SCronJobNameKey = attribute.Key("k8s.cronjob.name") -) - -// K8SCronJobUID returns an attribute KeyValue conforming to the -// "k8s.cronjob.uid" semantic conventions. It represents the UID of the -// CronJob. -func K8SCronJobUID(val string) attribute.KeyValue { - return K8SCronJobUIDKey.String(val) -} - -// K8SCronJobName returns an attribute KeyValue conforming to the -// "k8s.cronjob.name" semantic conventions. It represents the name of the -// CronJob. -func K8SCronJobName(val string) attribute.KeyValue { - return K8SCronJobNameKey.String(val) -} - -// The operating system (OS) on which the process represented by this resource -// is running. -const ( - // OSTypeKey is the attribute Key conforming to the "os.type" semantic - // conventions. It represents the operating system type. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - OSTypeKey = attribute.Key("os.type") - - // OSDescriptionKey is the attribute Key conforming to the "os.description" - // semantic conventions. It represents the human readable (not intended to - // be parsed) OS version information, like e.g. reported by `ver` or - // `lsb_release -a` commands. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Microsoft Windows [Version 10.0.18363.778]', 'Ubuntu 18.04.1 - // LTS' - OSDescriptionKey = attribute.Key("os.description") - - // OSNameKey is the attribute Key conforming to the "os.name" semantic - // conventions. It represents the human readable operating system name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iOS', 'Android', 'Ubuntu' - OSNameKey = attribute.Key("os.name") - - // OSVersionKey is the attribute Key conforming to the "os.version" - // semantic conventions. It represents the version string of the operating - // system as defined in [Version - // Attributes](../../resource/semantic_conventions/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '14.2.1', '18.04.1' - OSVersionKey = attribute.Key("os.version") -) - -var ( - // Microsoft Windows - OSTypeWindows = OSTypeKey.String("windows") - // Linux - OSTypeLinux = OSTypeKey.String("linux") - // Apple Darwin - OSTypeDarwin = OSTypeKey.String("darwin") - // FreeBSD - OSTypeFreeBSD = OSTypeKey.String("freebsd") - // NetBSD - OSTypeNetBSD = OSTypeKey.String("netbsd") - // OpenBSD - OSTypeOpenBSD = OSTypeKey.String("openbsd") - // DragonFly BSD - OSTypeDragonflyBSD = OSTypeKey.String("dragonflybsd") - // HP-UX (Hewlett Packard Unix) - OSTypeHPUX = OSTypeKey.String("hpux") - // AIX (Advanced Interactive eXecutive) - OSTypeAIX = OSTypeKey.String("aix") - // SunOS, Oracle Solaris - OSTypeSolaris = OSTypeKey.String("solaris") - // IBM z/OS - OSTypeZOS = OSTypeKey.String("z_os") -) - -// OSDescription returns an attribute KeyValue conforming to the -// "os.description" semantic conventions. It represents the human readable (not -// intended to be parsed) OS version information, like e.g. reported by `ver` -// or `lsb_release -a` commands. -func OSDescription(val string) attribute.KeyValue { - return OSDescriptionKey.String(val) -} - -// OSName returns an attribute KeyValue conforming to the "os.name" semantic -// conventions. It represents the human readable operating system name. -func OSName(val string) attribute.KeyValue { - return OSNameKey.String(val) -} - -// OSVersion returns an attribute KeyValue conforming to the "os.version" -// semantic conventions. It represents the version string of the operating -// system as defined in [Version -// Attributes](../../resource/semantic_conventions/README.md#version-attributes). -func OSVersion(val string) attribute.KeyValue { - return OSVersionKey.String(val) -} - -// An operating system process. -const ( - // ProcessPIDKey is the attribute Key conforming to the "process.pid" - // semantic conventions. It represents the process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 1234 - ProcessPIDKey = attribute.Key("process.pid") - - // ProcessParentPIDKey is the attribute Key conforming to the - // "process.parent_pid" semantic conventions. It represents the parent - // Process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 111 - ProcessParentPIDKey = attribute.Key("process.parent_pid") - - // ProcessExecutableNameKey is the attribute Key conforming to the - // "process.executable.name" semantic conventions. It represents the name - // of the process executable. On Linux based systems, can be set to the - // `Name` in `proc/[pid]/status`. On Windows, can be set to the base name - // of `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'otelcol' - ProcessExecutableNameKey = attribute.Key("process.executable.name") - - // ProcessExecutablePathKey is the attribute Key conforming to the - // "process.executable.path" semantic conventions. It represents the full - // path to the process executable. On Linux based systems, can be set to - // the target of `proc/[pid]/exe`. On Windows, can be set to the result of - // `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: '/usr/bin/cmd/otelcol' - ProcessExecutablePathKey = attribute.Key("process.executable.path") - - // ProcessCommandKey is the attribute Key conforming to the - // "process.command" semantic conventions. It represents the command used - // to launch the process (i.e. the command name). On Linux based systems, - // can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can - // be set to the first parameter extracted from `GetCommandLineW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'cmd/otelcol' - ProcessCommandKey = attribute.Key("process.command") - - // ProcessCommandLineKey is the attribute Key conforming to the - // "process.command_line" semantic conventions. It represents the full - // command used to launch the process as a single string representing the - // full command. On Windows, can be set to the result of `GetCommandLineW`. - // Do not set this if you have to assemble it just for monitoring; use - // `process.command_args` instead. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'C:\\cmd\\otecol --config="my directory\\config.yaml"' - ProcessCommandLineKey = attribute.Key("process.command_line") - - // ProcessCommandArgsKey is the attribute Key conforming to the - // "process.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) as received - // by the process. On Linux-based systems (and some other Unixoid systems - // supporting procfs), can be set according to the list of null-delimited - // strings extracted from `proc/[pid]/cmdline`. For libc-based executables, - // this would be the full argv vector passed to `main`. - // - // Type: string[] - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'cmd/otecol', '--config=config.yaml' - ProcessCommandArgsKey = attribute.Key("process.command_args") - - // ProcessOwnerKey is the attribute Key conforming to the "process.owner" - // semantic conventions. It represents the username of the user that owns - // the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'root' - ProcessOwnerKey = attribute.Key("process.owner") -) - -// ProcessPID returns an attribute KeyValue conforming to the "process.pid" -// semantic conventions. It represents the process identifier (PID). -func ProcessPID(val int) attribute.KeyValue { - return ProcessPIDKey.Int(val) -} - -// ProcessParentPID returns an attribute KeyValue conforming to the -// "process.parent_pid" semantic conventions. It represents the parent Process -// identifier (PID). -func ProcessParentPID(val int) attribute.KeyValue { - return ProcessParentPIDKey.Int(val) -} - -// ProcessExecutableName returns an attribute KeyValue conforming to the -// "process.executable.name" semantic conventions. It represents the name of -// the process executable. On Linux based systems, can be set to the `Name` in -// `proc/[pid]/status`. On Windows, can be set to the base name of -// `GetProcessImageFileNameW`. -func ProcessExecutableName(val string) attribute.KeyValue { - return ProcessExecutableNameKey.String(val) -} - -// ProcessExecutablePath returns an attribute KeyValue conforming to the -// "process.executable.path" semantic conventions. It represents the full path -// to the process executable. On Linux based systems, can be set to the target -// of `proc/[pid]/exe`. On Windows, can be set to the result of -// `GetProcessImageFileNameW`. -func ProcessExecutablePath(val string) attribute.KeyValue { - return ProcessExecutablePathKey.String(val) -} - -// ProcessCommand returns an attribute KeyValue conforming to the -// "process.command" semantic conventions. It represents the command used to -// launch the process (i.e. the command name). On Linux based systems, can be -// set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to -// the first parameter extracted from `GetCommandLineW`. -func ProcessCommand(val string) attribute.KeyValue { - return ProcessCommandKey.String(val) -} - -// ProcessCommandLine returns an attribute KeyValue conforming to the -// "process.command_line" semantic conventions. It represents the full command -// used to launch the process as a single string representing the full command. -// On Windows, can be set to the result of `GetCommandLineW`. Do not set this -// if you have to assemble it just for monitoring; use `process.command_args` -// instead. -func ProcessCommandLine(val string) attribute.KeyValue { - return ProcessCommandLineKey.String(val) -} - -// ProcessCommandArgs returns an attribute KeyValue conforming to the -// "process.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) as received by -// the process. On Linux-based systems (and some other Unixoid systems -// supporting procfs), can be set according to the list of null-delimited -// strings extracted from `proc/[pid]/cmdline`. For libc-based executables, -// this would be the full argv vector passed to `main`. -func ProcessCommandArgs(val ...string) attribute.KeyValue { - return ProcessCommandArgsKey.StringSlice(val) -} - -// ProcessOwner returns an attribute KeyValue conforming to the -// "process.owner" semantic conventions. It represents the username of the user -// that owns the process. -func ProcessOwner(val string) attribute.KeyValue { - return ProcessOwnerKey.String(val) -} - -// The single (language) runtime instance which is monitored. -const ( - // ProcessRuntimeNameKey is the attribute Key conforming to the - // "process.runtime.name" semantic conventions. It represents the name of - // the runtime of this process. For compiled native binaries, this SHOULD - // be the name of the compiler. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'OpenJDK Runtime Environment' - ProcessRuntimeNameKey = attribute.Key("process.runtime.name") - - // ProcessRuntimeVersionKey is the attribute Key conforming to the - // "process.runtime.version" semantic conventions. It represents the - // version of the runtime of this process, as returned by the runtime - // without modification. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '14.0.2' - ProcessRuntimeVersionKey = attribute.Key("process.runtime.version") - - // ProcessRuntimeDescriptionKey is the attribute Key conforming to the - // "process.runtime.description" semantic conventions. It represents an - // additional description about the runtime of the process, for example a - // specific vendor customization of the runtime environment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0' - ProcessRuntimeDescriptionKey = attribute.Key("process.runtime.description") -) - -// ProcessRuntimeName returns an attribute KeyValue conforming to the -// "process.runtime.name" semantic conventions. It represents the name of the -// runtime of this process. For compiled native binaries, this SHOULD be the -// name of the compiler. -func ProcessRuntimeName(val string) attribute.KeyValue { - return ProcessRuntimeNameKey.String(val) -} - -// ProcessRuntimeVersion returns an attribute KeyValue conforming to the -// "process.runtime.version" semantic conventions. It represents the version of -// the runtime of this process, as returned by the runtime without -// modification. -func ProcessRuntimeVersion(val string) attribute.KeyValue { - return ProcessRuntimeVersionKey.String(val) -} - -// ProcessRuntimeDescription returns an attribute KeyValue conforming to the -// "process.runtime.description" semantic conventions. It represents an -// additional description about the runtime of the process, for example a -// specific vendor customization of the runtime environment. -func ProcessRuntimeDescription(val string) attribute.KeyValue { - return ProcessRuntimeDescriptionKey.String(val) -} - -// A service instance. -const ( - // ServiceNameKey is the attribute Key conforming to the "service.name" - // semantic conventions. It represents the logical name of the service. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'shoppingcart' - // Note: MUST be the same for all instances of horizontally scaled - // services. If the value was not specified, SDKs MUST fallback to - // `unknown_service:` concatenated with - // [`process.executable.name`](process.md#process), e.g. - // `unknown_service:bash`. If `process.executable.name` is not available, - // the value MUST be set to `unknown_service`. - ServiceNameKey = attribute.Key("service.name") -) - -// ServiceName returns an attribute KeyValue conforming to the -// "service.name" semantic conventions. It represents the logical name of the -// service. -func ServiceName(val string) attribute.KeyValue { - return ServiceNameKey.String(val) -} - -// A service instance. -const ( - // ServiceNamespaceKey is the attribute Key conforming to the - // "service.namespace" semantic conventions. It represents a namespace for - // `service.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Shop' - // Note: A string value having a meaning that helps to distinguish a group - // of services, for example the team name that owns a group of services. - // `service.name` is expected to be unique within the same namespace. If - // `service.namespace` is not specified in the Resource then `service.name` - // is expected to be unique for all services that have no explicit - // namespace defined (so the empty/unspecified namespace is simply one more - // valid namespace). Zero-length namespace string is assumed equal to - // unspecified namespace. - ServiceNamespaceKey = attribute.Key("service.namespace") - - // ServiceInstanceIDKey is the attribute Key conforming to the - // "service.instance.id" semantic conventions. It represents the string ID - // of the service instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'my-k8s-pod-deployment-1', - // '627cc493-f310-47de-96bd-71410b7dec09' - // Note: MUST be unique for each instance of the same - // `service.namespace,service.name` pair (in other words - // `service.namespace,service.name,service.instance.id` triplet MUST be - // globally unique). The ID helps to distinguish instances of the same - // service that exist at the same time (e.g. instances of a horizontally - // scaled service). It is preferable for the ID to be persistent and stay - // the same for the lifetime of the service instance, however it is - // acceptable that the ID is ephemeral and changes during important - // lifetime events for the service (e.g. service restarts). If the service - // has no inherent unique ID that can be used as the value of this - // attribute it is recommended to generate a random Version 1 or Version 4 - // RFC 4122 UUID (services aiming for reproducible UUIDs may also use - // Version 5, see RFC 4122 for more recommendations). - ServiceInstanceIDKey = attribute.Key("service.instance.id") - - // ServiceVersionKey is the attribute Key conforming to the - // "service.version" semantic conventions. It represents the version string - // of the service API or implementation. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2.0.0' - ServiceVersionKey = attribute.Key("service.version") -) - -// ServiceNamespace returns an attribute KeyValue conforming to the -// "service.namespace" semantic conventions. It represents a namespace for -// `service.name`. -func ServiceNamespace(val string) attribute.KeyValue { - return ServiceNamespaceKey.String(val) -} - -// ServiceInstanceID returns an attribute KeyValue conforming to the -// "service.instance.id" semantic conventions. It represents the string ID of -// the service instance. -func ServiceInstanceID(val string) attribute.KeyValue { - return ServiceInstanceIDKey.String(val) -} - -// ServiceVersion returns an attribute KeyValue conforming to the -// "service.version" semantic conventions. It represents the version string of -// the service API or implementation. -func ServiceVersion(val string) attribute.KeyValue { - return ServiceVersionKey.String(val) -} - -// The telemetry SDK used to capture data recorded by the instrumentation -// libraries. -const ( - // TelemetrySDKNameKey is the attribute Key conforming to the - // "telemetry.sdk.name" semantic conventions. It represents the name of the - // telemetry SDK as defined above. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'opentelemetry' - TelemetrySDKNameKey = attribute.Key("telemetry.sdk.name") - - // TelemetrySDKLanguageKey is the attribute Key conforming to the - // "telemetry.sdk.language" semantic conventions. It represents the - // language of the telemetry SDK. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - TelemetrySDKLanguageKey = attribute.Key("telemetry.sdk.language") - - // TelemetrySDKVersionKey is the attribute Key conforming to the - // "telemetry.sdk.version" semantic conventions. It represents the version - // string of the telemetry SDK. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '1.2.3' - TelemetrySDKVersionKey = attribute.Key("telemetry.sdk.version") -) - -var ( - // cpp - TelemetrySDKLanguageCPP = TelemetrySDKLanguageKey.String("cpp") - // dotnet - TelemetrySDKLanguageDotnet = TelemetrySDKLanguageKey.String("dotnet") - // erlang - TelemetrySDKLanguageErlang = TelemetrySDKLanguageKey.String("erlang") - // go - TelemetrySDKLanguageGo = TelemetrySDKLanguageKey.String("go") - // java - TelemetrySDKLanguageJava = TelemetrySDKLanguageKey.String("java") - // nodejs - TelemetrySDKLanguageNodejs = TelemetrySDKLanguageKey.String("nodejs") - // php - TelemetrySDKLanguagePHP = TelemetrySDKLanguageKey.String("php") - // python - TelemetrySDKLanguagePython = TelemetrySDKLanguageKey.String("python") - // ruby - TelemetrySDKLanguageRuby = TelemetrySDKLanguageKey.String("ruby") - // webjs - TelemetrySDKLanguageWebjs = TelemetrySDKLanguageKey.String("webjs") - // swift - TelemetrySDKLanguageSwift = TelemetrySDKLanguageKey.String("swift") -) - -// TelemetrySDKName returns an attribute KeyValue conforming to the -// "telemetry.sdk.name" semantic conventions. It represents the name of the -// telemetry SDK as defined above. -func TelemetrySDKName(val string) attribute.KeyValue { - return TelemetrySDKNameKey.String(val) -} - -// TelemetrySDKVersion returns an attribute KeyValue conforming to the -// "telemetry.sdk.version" semantic conventions. It represents the version -// string of the telemetry SDK. -func TelemetrySDKVersion(val string) attribute.KeyValue { - return TelemetrySDKVersionKey.String(val) -} - -// The telemetry SDK used to capture data recorded by the instrumentation -// libraries. -const ( - // TelemetryAutoVersionKey is the attribute Key conforming to the - // "telemetry.auto.version" semantic conventions. It represents the version - // string of the auto instrumentation agent, if used. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.2.3' - TelemetryAutoVersionKey = attribute.Key("telemetry.auto.version") -) - -// TelemetryAutoVersion returns an attribute KeyValue conforming to the -// "telemetry.auto.version" semantic conventions. It represents the version -// string of the auto instrumentation agent, if used. -func TelemetryAutoVersion(val string) attribute.KeyValue { - return TelemetryAutoVersionKey.String(val) -} - -// Resource describing the packaged software running the application code. Web -// engines are typically executed using process.runtime. -const ( - // WebEngineNameKey is the attribute Key conforming to the "webengine.name" - // semantic conventions. It represents the name of the web engine. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'WildFly' - WebEngineNameKey = attribute.Key("webengine.name") - - // WebEngineVersionKey is the attribute Key conforming to the - // "webengine.version" semantic conventions. It represents the version of - // the web engine. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '21.0.0' - WebEngineVersionKey = attribute.Key("webengine.version") - - // WebEngineDescriptionKey is the attribute Key conforming to the - // "webengine.description" semantic conventions. It represents the - // additional description of the web engine (e.g. detailed version and - // edition information). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - - // 2.2.2.Final' - WebEngineDescriptionKey = attribute.Key("webengine.description") -) - -// WebEngineName returns an attribute KeyValue conforming to the -// "webengine.name" semantic conventions. It represents the name of the web -// engine. -func WebEngineName(val string) attribute.KeyValue { - return WebEngineNameKey.String(val) -} - -// WebEngineVersion returns an attribute KeyValue conforming to the -// "webengine.version" semantic conventions. It represents the version of the -// web engine. -func WebEngineVersion(val string) attribute.KeyValue { - return WebEngineVersionKey.String(val) -} - -// WebEngineDescription returns an attribute KeyValue conforming to the -// "webengine.description" semantic conventions. It represents the additional -// description of the web engine (e.g. detailed version and edition -// information). -func WebEngineDescription(val string) attribute.KeyValue { - return WebEngineDescriptionKey.String(val) -} - -// Attributes used by non-OTLP exporters to represent OpenTelemetry Scope's -// concepts. -const ( - // OTelScopeNameKey is the attribute Key conforming to the - // "otel.scope.name" semantic conventions. It represents the name of the - // instrumentation scope - (`InstrumentationScope.Name` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'io.opentelemetry.contrib.mongodb' - OTelScopeNameKey = attribute.Key("otel.scope.name") - - // OTelScopeVersionKey is the attribute Key conforming to the - // "otel.scope.version" semantic conventions. It represents the version of - // the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.0.0' - OTelScopeVersionKey = attribute.Key("otel.scope.version") -) - -// OTelScopeName returns an attribute KeyValue conforming to the -// "otel.scope.name" semantic conventions. It represents the name of the -// instrumentation scope - (`InstrumentationScope.Name` in OTLP). -func OTelScopeName(val string) attribute.KeyValue { - return OTelScopeNameKey.String(val) -} - -// OTelScopeVersion returns an attribute KeyValue conforming to the -// "otel.scope.version" semantic conventions. It represents the version of the -// instrumentation scope - (`InstrumentationScope.Version` in OTLP). -func OTelScopeVersion(val string) attribute.KeyValue { - return OTelScopeVersionKey.String(val) -} - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry -// Scope's concepts. -const ( - // OTelLibraryNameKey is the attribute Key conforming to the - // "otel.library.name" semantic conventions. It represents the deprecated, - // use the `otel.scope.name` attribute. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'io.opentelemetry.contrib.mongodb' - OTelLibraryNameKey = attribute.Key("otel.library.name") - - // OTelLibraryVersionKey is the attribute Key conforming to the - // "otel.library.version" semantic conventions. It represents the - // deprecated, use the `otel.scope.version` attribute. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '1.0.0' - OTelLibraryVersionKey = attribute.Key("otel.library.version") -) - -// OTelLibraryName returns an attribute KeyValue conforming to the -// "otel.library.name" semantic conventions. It represents the deprecated, use -// the `otel.scope.name` attribute. -func OTelLibraryName(val string) attribute.KeyValue { - return OTelLibraryNameKey.String(val) -} - -// OTelLibraryVersion returns an attribute KeyValue conforming to the -// "otel.library.version" semantic conventions. It represents the deprecated, -// use the `otel.scope.version` attribute. -func OTelLibraryVersion(val string) attribute.KeyValue { - return OTelLibraryVersionKey.String(val) -} diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go deleted file mode 100644 index 95d0210e3..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -// SchemaURL is the schema URL that matches the version of the semantic conventions -// that this package defines. Semconv packages starting from v1.4.0 must declare -// non-empty schema URL in the form https://opentelemetry.io/schemas/ -const SchemaURL = "https://opentelemetry.io/schemas/1.20.0" diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go b/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go deleted file mode 100644 index 90b1b0452..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go +++ /dev/null @@ -1,2599 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" - -import "go.opentelemetry.io/otel/attribute" - -// The shared attributes used to report a single exception associated with a -// span or log. -const ( - // ExceptionTypeKey is the attribute Key conforming to the "exception.type" - // semantic conventions. It represents the type of the exception (its - // fully-qualified class name, if applicable). The dynamic type of the - // exception should be preferred over the static type in languages that - // support it. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'java.net.ConnectException', 'OSError' - ExceptionTypeKey = attribute.Key("exception.type") - - // ExceptionMessageKey is the attribute Key conforming to the - // "exception.message" semantic conventions. It represents the exception - // message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Division by zero', "Can't convert 'int' object to str - // implicitly" - ExceptionMessageKey = attribute.Key("exception.message") - - // ExceptionStacktraceKey is the attribute Key conforming to the - // "exception.stacktrace" semantic conventions. It represents a stacktrace - // as a string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Exception in thread "main" java.lang.RuntimeException: Test - // exception\\n at ' - // 'com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - ExceptionStacktraceKey = attribute.Key("exception.stacktrace") -) - -// ExceptionType returns an attribute KeyValue conforming to the -// "exception.type" semantic conventions. It represents the type of the -// exception (its fully-qualified class name, if applicable). The dynamic type -// of the exception should be preferred over the static type in languages that -// support it. -func ExceptionType(val string) attribute.KeyValue { - return ExceptionTypeKey.String(val) -} - -// ExceptionMessage returns an attribute KeyValue conforming to the -// "exception.message" semantic conventions. It represents the exception -// message. -func ExceptionMessage(val string) attribute.KeyValue { - return ExceptionMessageKey.String(val) -} - -// ExceptionStacktrace returns an attribute KeyValue conforming to the -// "exception.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func ExceptionStacktrace(val string) attribute.KeyValue { - return ExceptionStacktraceKey.String(val) -} - -// The attributes described in this section are rather generic. They may be -// used in any Log Record they apply to. -const ( - // LogRecordUIDKey is the attribute Key conforming to the "log.record.uid" - // semantic conventions. It represents a unique identifier for the Log - // Record. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '01ARZ3NDEKTSV4RRFFQ69G5FAV' - // Note: If an id is provided, other log records with the same id will be - // considered duplicates and can be removed safely. This means, that two - // distinguishable log records MUST have different values. - // The id MAY be an [Universally Unique Lexicographically Sortable - // Identifier (ULID)](https://github.com/ulid/spec), but other identifiers - // (e.g. UUID) may be used as needed. - LogRecordUIDKey = attribute.Key("log.record.uid") -) - -// LogRecordUID returns an attribute KeyValue conforming to the -// "log.record.uid" semantic conventions. It represents a unique identifier for -// the Log Record. -func LogRecordUID(val string) attribute.KeyValue { - return LogRecordUIDKey.String(val) -} - -// Span attributes used by AWS Lambda (in addition to general `faas` -// attributes). -const ( - // AWSLambdaInvokedARNKey is the attribute Key conforming to the - // "aws.lambda.invoked_arn" semantic conventions. It represents the full - // invoked ARN as provided on the `Context` passed to the function - // (`Lambda-Runtime-Invoked-Function-ARN` header on the - // `/runtime/invocation/next` applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' - // Note: This may be different from `cloud.resource_id` if an alias is - // involved. - AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") -) - -// AWSLambdaInvokedARN returns an attribute KeyValue conforming to the -// "aws.lambda.invoked_arn" semantic conventions. It represents the full -// invoked ARN as provided on the `Context` passed to the function -// (`Lambda-Runtime-Invoked-Function-ARN` header on the -// `/runtime/invocation/next` applicable). -func AWSLambdaInvokedARN(val string) attribute.KeyValue { - return AWSLambdaInvokedARNKey.String(val) -} - -// Attributes for CloudEvents. CloudEvents is a specification on how to define -// event data in a standard way. These attributes can be attached to spans when -// performing operations with CloudEvents, regardless of the protocol being -// used. -const ( - // CloudeventsEventIDKey is the attribute Key conforming to the - // "cloudevents.event_id" semantic conventions. It represents the - // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) - // uniquely identifies the event. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' - CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") - - // CloudeventsEventSourceKey is the attribute Key conforming to the - // "cloudevents.event_source" semantic conventions. It represents the - // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) - // identifies the context in which an event happened. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'https://github.com/cloudevents', - // '/cloudevents/spec/pull/123', 'my-service' - CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") - - // CloudeventsEventSpecVersionKey is the attribute Key conforming to the - // "cloudevents.event_spec_version" semantic conventions. It represents the - // [version of the CloudEvents - // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) - // which the event uses. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.0' - CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") - - // CloudeventsEventTypeKey is the attribute Key conforming to the - // "cloudevents.event_type" semantic conventions. It represents the - // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) - // contains a value describing the type of event related to the originating - // occurrence. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'com.github.pull_request.opened', - // 'com.example.object.deleted.v2' - CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") - - // CloudeventsEventSubjectKey is the attribute Key conforming to the - // "cloudevents.event_subject" semantic conventions. It represents the - // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) - // of the event in the context of the event producer (identified by - // source). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'mynewfile.jpg' - CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") -) - -// CloudeventsEventID returns an attribute KeyValue conforming to the -// "cloudevents.event_id" semantic conventions. It represents the -// [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) -// uniquely identifies the event. -func CloudeventsEventID(val string) attribute.KeyValue { - return CloudeventsEventIDKey.String(val) -} - -// CloudeventsEventSource returns an attribute KeyValue conforming to the -// "cloudevents.event_source" semantic conventions. It represents the -// [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) -// identifies the context in which an event happened. -func CloudeventsEventSource(val string) attribute.KeyValue { - return CloudeventsEventSourceKey.String(val) -} - -// CloudeventsEventSpecVersion returns an attribute KeyValue conforming to -// the "cloudevents.event_spec_version" semantic conventions. It represents the -// [version of the CloudEvents -// specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) -// which the event uses. -func CloudeventsEventSpecVersion(val string) attribute.KeyValue { - return CloudeventsEventSpecVersionKey.String(val) -} - -// CloudeventsEventType returns an attribute KeyValue conforming to the -// "cloudevents.event_type" semantic conventions. It represents the -// [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) -// contains a value describing the type of event related to the originating -// occurrence. -func CloudeventsEventType(val string) attribute.KeyValue { - return CloudeventsEventTypeKey.String(val) -} - -// CloudeventsEventSubject returns an attribute KeyValue conforming to the -// "cloudevents.event_subject" semantic conventions. It represents the -// [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) -// of the event in the context of the event producer (identified by source). -func CloudeventsEventSubject(val string) attribute.KeyValue { - return CloudeventsEventSubjectKey.String(val) -} - -// Semantic conventions for the OpenTracing Shim -const ( - // OpentracingRefTypeKey is the attribute Key conforming to the - // "opentracing.ref_type" semantic conventions. It represents the - // parent-child Reference type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: The causal relationship between a child Span and a parent Span. - OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") -) - -var ( - // The parent Span depends on the child Span in some capacity - OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") - // The parent Span does not depend in any way on the result of the child Span - OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") -) - -// The attributes used to perform database client calls. -const ( - // DBSystemKey is the attribute Key conforming to the "db.system" semantic - // conventions. It represents an identifier for the database management - // system (DBMS) product being used. See below for a list of well-known - // identifiers. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - DBSystemKey = attribute.Key("db.system") - - // DBConnectionStringKey is the attribute Key conforming to the - // "db.connection_string" semantic conventions. It represents the - // connection string used to connect to the database. It is recommended to - // remove embedded credentials. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Server=(localdb)\\v11.0;Integrated Security=true;' - DBConnectionStringKey = attribute.Key("db.connection_string") - - // DBUserKey is the attribute Key conforming to the "db.user" semantic - // conventions. It represents the username for accessing the database. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'readonly_user', 'reporting_user' - DBUserKey = attribute.Key("db.user") - - // DBJDBCDriverClassnameKey is the attribute Key conforming to the - // "db.jdbc.driver_classname" semantic conventions. It represents the - // fully-qualified class name of the [Java Database Connectivity - // (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) - // driver used to connect. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'org.postgresql.Driver', - // 'com.microsoft.sqlserver.jdbc.SQLServerDriver' - DBJDBCDriverClassnameKey = attribute.Key("db.jdbc.driver_classname") - - // DBNameKey is the attribute Key conforming to the "db.name" semantic - // conventions. It represents the this attribute is used to report the name - // of the database being accessed. For commands that switch the database, - // this should be set to the target database (even if the command fails). - // - // Type: string - // RequirementLevel: ConditionallyRequired (If applicable.) - // Stability: stable - // Examples: 'customers', 'main' - // Note: In some SQL databases, the database name to be used is called - // "schema name". In case there are multiple layers that could be - // considered for database name (e.g. Oracle instance name and schema - // name), the database name to be used is the more specific layer (e.g. - // Oracle schema name). - DBNameKey = attribute.Key("db.name") - - // DBStatementKey is the attribute Key conforming to the "db.statement" - // semantic conventions. It represents the database statement being - // executed. - // - // Type: string - // RequirementLevel: Recommended (Should be collected by default only if - // there is sanitization that excludes sensitive information.) - // Stability: stable - // Examples: 'SELECT * FROM wuser_table', 'SET mykey "WuValue"' - DBStatementKey = attribute.Key("db.statement") - - // DBOperationKey is the attribute Key conforming to the "db.operation" - // semantic conventions. It represents the name of the operation being - // executed, e.g. the [MongoDB command - // name](https://docs.mongodb.com/manual/reference/command/#database-operations) - // such as `findAndModify`, or the SQL keyword. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If `db.statement` is not - // applicable.) - // Stability: stable - // Examples: 'findAndModify', 'HMSET', 'SELECT' - // Note: When setting this to an SQL keyword, it is not recommended to - // attempt any client-side parsing of `db.statement` just to get this - // property, but it should be set if the operation name is provided by the - // library being instrumented. If the SQL statement has an ambiguous - // operation, or performs more than one operation, this value may be - // omitted. - DBOperationKey = attribute.Key("db.operation") -) - -var ( - // Some other SQL database. Fallback only. See notes - DBSystemOtherSQL = DBSystemKey.String("other_sql") - // Microsoft SQL Server - DBSystemMSSQL = DBSystemKey.String("mssql") - // Microsoft SQL Server Compact - DBSystemMssqlcompact = DBSystemKey.String("mssqlcompact") - // MySQL - DBSystemMySQL = DBSystemKey.String("mysql") - // Oracle Database - DBSystemOracle = DBSystemKey.String("oracle") - // IBM DB2 - DBSystemDB2 = DBSystemKey.String("db2") - // PostgreSQL - DBSystemPostgreSQL = DBSystemKey.String("postgresql") - // Amazon Redshift - DBSystemRedshift = DBSystemKey.String("redshift") - // Apache Hive - DBSystemHive = DBSystemKey.String("hive") - // Cloudscape - DBSystemCloudscape = DBSystemKey.String("cloudscape") - // HyperSQL DataBase - DBSystemHSQLDB = DBSystemKey.String("hsqldb") - // Progress Database - DBSystemProgress = DBSystemKey.String("progress") - // SAP MaxDB - DBSystemMaxDB = DBSystemKey.String("maxdb") - // SAP HANA - DBSystemHanaDB = DBSystemKey.String("hanadb") - // Ingres - DBSystemIngres = DBSystemKey.String("ingres") - // FirstSQL - DBSystemFirstSQL = DBSystemKey.String("firstsql") - // EnterpriseDB - DBSystemEDB = DBSystemKey.String("edb") - // InterSystems Caché - DBSystemCache = DBSystemKey.String("cache") - // Adabas (Adaptable Database System) - DBSystemAdabas = DBSystemKey.String("adabas") - // Firebird - DBSystemFirebird = DBSystemKey.String("firebird") - // Apache Derby - DBSystemDerby = DBSystemKey.String("derby") - // FileMaker - DBSystemFilemaker = DBSystemKey.String("filemaker") - // Informix - DBSystemInformix = DBSystemKey.String("informix") - // InstantDB - DBSystemInstantDB = DBSystemKey.String("instantdb") - // InterBase - DBSystemInterbase = DBSystemKey.String("interbase") - // MariaDB - DBSystemMariaDB = DBSystemKey.String("mariadb") - // Netezza - DBSystemNetezza = DBSystemKey.String("netezza") - // Pervasive PSQL - DBSystemPervasive = DBSystemKey.String("pervasive") - // PointBase - DBSystemPointbase = DBSystemKey.String("pointbase") - // SQLite - DBSystemSqlite = DBSystemKey.String("sqlite") - // Sybase - DBSystemSybase = DBSystemKey.String("sybase") - // Teradata - DBSystemTeradata = DBSystemKey.String("teradata") - // Vertica - DBSystemVertica = DBSystemKey.String("vertica") - // H2 - DBSystemH2 = DBSystemKey.String("h2") - // ColdFusion IMQ - DBSystemColdfusion = DBSystemKey.String("coldfusion") - // Apache Cassandra - DBSystemCassandra = DBSystemKey.String("cassandra") - // Apache HBase - DBSystemHBase = DBSystemKey.String("hbase") - // MongoDB - DBSystemMongoDB = DBSystemKey.String("mongodb") - // Redis - DBSystemRedis = DBSystemKey.String("redis") - // Couchbase - DBSystemCouchbase = DBSystemKey.String("couchbase") - // CouchDB - DBSystemCouchDB = DBSystemKey.String("couchdb") - // Microsoft Azure Cosmos DB - DBSystemCosmosDB = DBSystemKey.String("cosmosdb") - // Amazon DynamoDB - DBSystemDynamoDB = DBSystemKey.String("dynamodb") - // Neo4j - DBSystemNeo4j = DBSystemKey.String("neo4j") - // Apache Geode - DBSystemGeode = DBSystemKey.String("geode") - // Elasticsearch - DBSystemElasticsearch = DBSystemKey.String("elasticsearch") - // Memcached - DBSystemMemcached = DBSystemKey.String("memcached") - // CockroachDB - DBSystemCockroachdb = DBSystemKey.String("cockroachdb") - // OpenSearch - DBSystemOpensearch = DBSystemKey.String("opensearch") - // ClickHouse - DBSystemClickhouse = DBSystemKey.String("clickhouse") - // Cloud Spanner - DBSystemSpanner = DBSystemKey.String("spanner") - // Trino - DBSystemTrino = DBSystemKey.String("trino") -) - -// DBConnectionString returns an attribute KeyValue conforming to the -// "db.connection_string" semantic conventions. It represents the connection -// string used to connect to the database. It is recommended to remove embedded -// credentials. -func DBConnectionString(val string) attribute.KeyValue { - return DBConnectionStringKey.String(val) -} - -// DBUser returns an attribute KeyValue conforming to the "db.user" semantic -// conventions. It represents the username for accessing the database. -func DBUser(val string) attribute.KeyValue { - return DBUserKey.String(val) -} - -// DBJDBCDriverClassname returns an attribute KeyValue conforming to the -// "db.jdbc.driver_classname" semantic conventions. It represents the -// fully-qualified class name of the [Java Database Connectivity -// (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver -// used to connect. -func DBJDBCDriverClassname(val string) attribute.KeyValue { - return DBJDBCDriverClassnameKey.String(val) -} - -// DBName returns an attribute KeyValue conforming to the "db.name" semantic -// conventions. It represents the this attribute is used to report the name of -// the database being accessed. For commands that switch the database, this -// should be set to the target database (even if the command fails). -func DBName(val string) attribute.KeyValue { - return DBNameKey.String(val) -} - -// DBStatement returns an attribute KeyValue conforming to the -// "db.statement" semantic conventions. It represents the database statement -// being executed. -func DBStatement(val string) attribute.KeyValue { - return DBStatementKey.String(val) -} - -// DBOperation returns an attribute KeyValue conforming to the -// "db.operation" semantic conventions. It represents the name of the operation -// being executed, e.g. the [MongoDB command -// name](https://docs.mongodb.com/manual/reference/command/#database-operations) -// such as `findAndModify`, or the SQL keyword. -func DBOperation(val string) attribute.KeyValue { - return DBOperationKey.String(val) -} - -// Connection-level attributes for Microsoft SQL Server -const ( - // DBMSSQLInstanceNameKey is the attribute Key conforming to the - // "db.mssql.instance_name" semantic conventions. It represents the - // Microsoft SQL Server [instance - // name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) - // connecting to. This name is used to determine the port of a named - // instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MSSQLSERVER' - // Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no - // longer required (but still recommended if non-standard). - DBMSSQLInstanceNameKey = attribute.Key("db.mssql.instance_name") -) - -// DBMSSQLInstanceName returns an attribute KeyValue conforming to the -// "db.mssql.instance_name" semantic conventions. It represents the Microsoft -// SQL Server [instance -// name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) -// connecting to. This name is used to determine the port of a named instance. -func DBMSSQLInstanceName(val string) attribute.KeyValue { - return DBMSSQLInstanceNameKey.String(val) -} - -// Call-level attributes for Cassandra -const ( - // DBCassandraPageSizeKey is the attribute Key conforming to the - // "db.cassandra.page_size" semantic conventions. It represents the fetch - // size used for paging, i.e. how many rows will be returned at once. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 5000 - DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") - - // DBCassandraConsistencyLevelKey is the attribute Key conforming to the - // "db.cassandra.consistency_level" semantic conventions. It represents the - // consistency level of the query. Based on consistency values from - // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") - - // DBCassandraTableKey is the attribute Key conforming to the - // "db.cassandra.table" semantic conventions. It represents the name of the - // primary table that the operation is acting upon, including the keyspace - // name (if applicable). - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'mytable' - // Note: This mirrors the db.sql.table attribute but references cassandra - // rather than sql. It is not recommended to attempt any client-side - // parsing of `db.statement` just to get this property, but it should be - // set if it is provided by the library being instrumented. If the - // operation is acting upon an anonymous table, or more than one table, - // this value MUST NOT be set. - DBCassandraTableKey = attribute.Key("db.cassandra.table") - - // DBCassandraIdempotenceKey is the attribute Key conforming to the - // "db.cassandra.idempotence" semantic conventions. It represents the - // whether or not the query is idempotent. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") - - // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming - // to the "db.cassandra.speculative_execution_count" semantic conventions. - // It represents the number of times a query was speculatively executed. - // Not set or `0` if the query was not executed speculatively. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 0, 2 - DBCassandraSpeculativeExecutionCountKey = attribute.Key("db.cassandra.speculative_execution_count") - - // DBCassandraCoordinatorIDKey is the attribute Key conforming to the - // "db.cassandra.coordinator.id" semantic conventions. It represents the ID - // of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' - DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") - - // DBCassandraCoordinatorDCKey is the attribute Key conforming to the - // "db.cassandra.coordinator.dc" semantic conventions. It represents the - // data center of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-west-2' - DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") -) - -var ( - // all - DBCassandraConsistencyLevelAll = DBCassandraConsistencyLevelKey.String("all") - // each_quorum - DBCassandraConsistencyLevelEachQuorum = DBCassandraConsistencyLevelKey.String("each_quorum") - // quorum - DBCassandraConsistencyLevelQuorum = DBCassandraConsistencyLevelKey.String("quorum") - // local_quorum - DBCassandraConsistencyLevelLocalQuorum = DBCassandraConsistencyLevelKey.String("local_quorum") - // one - DBCassandraConsistencyLevelOne = DBCassandraConsistencyLevelKey.String("one") - // two - DBCassandraConsistencyLevelTwo = DBCassandraConsistencyLevelKey.String("two") - // three - DBCassandraConsistencyLevelThree = DBCassandraConsistencyLevelKey.String("three") - // local_one - DBCassandraConsistencyLevelLocalOne = DBCassandraConsistencyLevelKey.String("local_one") - // any - DBCassandraConsistencyLevelAny = DBCassandraConsistencyLevelKey.String("any") - // serial - DBCassandraConsistencyLevelSerial = DBCassandraConsistencyLevelKey.String("serial") - // local_serial - DBCassandraConsistencyLevelLocalSerial = DBCassandraConsistencyLevelKey.String("local_serial") -) - -// DBCassandraPageSize returns an attribute KeyValue conforming to the -// "db.cassandra.page_size" semantic conventions. It represents the fetch size -// used for paging, i.e. how many rows will be returned at once. -func DBCassandraPageSize(val int) attribute.KeyValue { - return DBCassandraPageSizeKey.Int(val) -} - -// DBCassandraTable returns an attribute KeyValue conforming to the -// "db.cassandra.table" semantic conventions. It represents the name of the -// primary table that the operation is acting upon, including the keyspace name -// (if applicable). -func DBCassandraTable(val string) attribute.KeyValue { - return DBCassandraTableKey.String(val) -} - -// DBCassandraIdempotence returns an attribute KeyValue conforming to the -// "db.cassandra.idempotence" semantic conventions. It represents the whether -// or not the query is idempotent. -func DBCassandraIdempotence(val bool) attribute.KeyValue { - return DBCassandraIdempotenceKey.Bool(val) -} - -// DBCassandraSpeculativeExecutionCount returns an attribute KeyValue -// conforming to the "db.cassandra.speculative_execution_count" semantic -// conventions. It represents the number of times a query was speculatively -// executed. Not set or `0` if the query was not executed speculatively. -func DBCassandraSpeculativeExecutionCount(val int) attribute.KeyValue { - return DBCassandraSpeculativeExecutionCountKey.Int(val) -} - -// DBCassandraCoordinatorID returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.id" semantic conventions. It represents the ID of -// the coordinating node for a query. -func DBCassandraCoordinatorID(val string) attribute.KeyValue { - return DBCassandraCoordinatorIDKey.String(val) -} - -// DBCassandraCoordinatorDC returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.dc" semantic conventions. It represents the data -// center of the coordinating node for a query. -func DBCassandraCoordinatorDC(val string) attribute.KeyValue { - return DBCassandraCoordinatorDCKey.String(val) -} - -// Call-level attributes for Redis -const ( - // DBRedisDBIndexKey is the attribute Key conforming to the - // "db.redis.database_index" semantic conventions. It represents the index - // of the database being accessed as used in the [`SELECT` - // command](https://redis.io/commands/select), provided as an integer. To - // be used instead of the generic `db.name` attribute. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If other than the default - // database (`0`).) - // Stability: stable - // Examples: 0, 1, 15 - DBRedisDBIndexKey = attribute.Key("db.redis.database_index") -) - -// DBRedisDBIndex returns an attribute KeyValue conforming to the -// "db.redis.database_index" semantic conventions. It represents the index of -// the database being accessed as used in the [`SELECT` -// command](https://redis.io/commands/select), provided as an integer. To be -// used instead of the generic `db.name` attribute. -func DBRedisDBIndex(val int) attribute.KeyValue { - return DBRedisDBIndexKey.Int(val) -} - -// Call-level attributes for MongoDB -const ( - // DBMongoDBCollectionKey is the attribute Key conforming to the - // "db.mongodb.collection" semantic conventions. It represents the - // collection being accessed within the database stated in `db.name`. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'customers', 'products' - DBMongoDBCollectionKey = attribute.Key("db.mongodb.collection") -) - -// DBMongoDBCollection returns an attribute KeyValue conforming to the -// "db.mongodb.collection" semantic conventions. It represents the collection -// being accessed within the database stated in `db.name`. -func DBMongoDBCollection(val string) attribute.KeyValue { - return DBMongoDBCollectionKey.String(val) -} - -// Call-level attributes for SQL databases -const ( - // DBSQLTableKey is the attribute Key conforming to the "db.sql.table" - // semantic conventions. It represents the name of the primary table that - // the operation is acting upon, including the database name (if - // applicable). - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'public.users', 'customers' - // Note: It is not recommended to attempt any client-side parsing of - // `db.statement` just to get this property, but it should be set if it is - // provided by the library being instrumented. If the operation is acting - // upon an anonymous table, or more than one table, this value MUST NOT be - // set. - DBSQLTableKey = attribute.Key("db.sql.table") -) - -// DBSQLTable returns an attribute KeyValue conforming to the "db.sql.table" -// semantic conventions. It represents the name of the primary table that the -// operation is acting upon, including the database name (if applicable). -func DBSQLTable(val string) attribute.KeyValue { - return DBSQLTableKey.String(val) -} - -// Call-level attributes for Cosmos DB. -const ( - // DBCosmosDBClientIDKey is the attribute Key conforming to the - // "db.cosmosdb.client_id" semantic conventions. It represents the unique - // Cosmos client instance id. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '3ba4827d-4422-483f-b59f-85b74211c11d' - DBCosmosDBClientIDKey = attribute.Key("db.cosmosdb.client_id") - - // DBCosmosDBOperationTypeKey is the attribute Key conforming to the - // "db.cosmosdb.operation_type" semantic conventions. It represents the - // cosmosDB Operation Type. - // - // Type: Enum - // RequirementLevel: ConditionallyRequired (when performing one of the - // operations in this list) - // Stability: stable - DBCosmosDBOperationTypeKey = attribute.Key("db.cosmosdb.operation_type") - - // DBCosmosDBConnectionModeKey is the attribute Key conforming to the - // "db.cosmosdb.connection_mode" semantic conventions. It represents the - // cosmos client connection mode. - // - // Type: Enum - // RequirementLevel: ConditionallyRequired (if not `direct` (or pick gw as - // default)) - // Stability: stable - DBCosmosDBConnectionModeKey = attribute.Key("db.cosmosdb.connection_mode") - - // DBCosmosDBContainerKey is the attribute Key conforming to the - // "db.cosmosdb.container" semantic conventions. It represents the cosmos - // DB container name. - // - // Type: string - // RequirementLevel: ConditionallyRequired (if available) - // Stability: stable - // Examples: 'anystring' - DBCosmosDBContainerKey = attribute.Key("db.cosmosdb.container") - - // DBCosmosDBRequestContentLengthKey is the attribute Key conforming to the - // "db.cosmosdb.request_content_length" semantic conventions. It represents - // the request payload size in bytes - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - DBCosmosDBRequestContentLengthKey = attribute.Key("db.cosmosdb.request_content_length") - - // DBCosmosDBStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.status_code" semantic conventions. It represents the cosmos - // DB status code. - // - // Type: int - // RequirementLevel: ConditionallyRequired (if response was received) - // Stability: stable - // Examples: 200, 201 - DBCosmosDBStatusCodeKey = attribute.Key("db.cosmosdb.status_code") - - // DBCosmosDBSubStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.sub_status_code" semantic conventions. It represents the - // cosmos DB sub status code. - // - // Type: int - // RequirementLevel: ConditionallyRequired (when response was received and - // contained sub-code.) - // Stability: stable - // Examples: 1000, 1002 - DBCosmosDBSubStatusCodeKey = attribute.Key("db.cosmosdb.sub_status_code") - - // DBCosmosDBRequestChargeKey is the attribute Key conforming to the - // "db.cosmosdb.request_charge" semantic conventions. It represents the rU - // consumed for that operation - // - // Type: double - // RequirementLevel: ConditionallyRequired (when available) - // Stability: stable - // Examples: 46.18, 1.0 - DBCosmosDBRequestChargeKey = attribute.Key("db.cosmosdb.request_charge") -) - -var ( - // invalid - DBCosmosDBOperationTypeInvalid = DBCosmosDBOperationTypeKey.String("Invalid") - // create - DBCosmosDBOperationTypeCreate = DBCosmosDBOperationTypeKey.String("Create") - // patch - DBCosmosDBOperationTypePatch = DBCosmosDBOperationTypeKey.String("Patch") - // read - DBCosmosDBOperationTypeRead = DBCosmosDBOperationTypeKey.String("Read") - // read_feed - DBCosmosDBOperationTypeReadFeed = DBCosmosDBOperationTypeKey.String("ReadFeed") - // delete - DBCosmosDBOperationTypeDelete = DBCosmosDBOperationTypeKey.String("Delete") - // replace - DBCosmosDBOperationTypeReplace = DBCosmosDBOperationTypeKey.String("Replace") - // execute - DBCosmosDBOperationTypeExecute = DBCosmosDBOperationTypeKey.String("Execute") - // query - DBCosmosDBOperationTypeQuery = DBCosmosDBOperationTypeKey.String("Query") - // head - DBCosmosDBOperationTypeHead = DBCosmosDBOperationTypeKey.String("Head") - // head_feed - DBCosmosDBOperationTypeHeadFeed = DBCosmosDBOperationTypeKey.String("HeadFeed") - // upsert - DBCosmosDBOperationTypeUpsert = DBCosmosDBOperationTypeKey.String("Upsert") - // batch - DBCosmosDBOperationTypeBatch = DBCosmosDBOperationTypeKey.String("Batch") - // query_plan - DBCosmosDBOperationTypeQueryPlan = DBCosmosDBOperationTypeKey.String("QueryPlan") - // execute_javascript - DBCosmosDBOperationTypeExecuteJavascript = DBCosmosDBOperationTypeKey.String("ExecuteJavaScript") -) - -var ( - // Gateway (HTTP) connections mode - DBCosmosDBConnectionModeGateway = DBCosmosDBConnectionModeKey.String("gateway") - // Direct connection - DBCosmosDBConnectionModeDirect = DBCosmosDBConnectionModeKey.String("direct") -) - -// DBCosmosDBClientID returns an attribute KeyValue conforming to the -// "db.cosmosdb.client_id" semantic conventions. It represents the unique -// Cosmos client instance id. -func DBCosmosDBClientID(val string) attribute.KeyValue { - return DBCosmosDBClientIDKey.String(val) -} - -// DBCosmosDBContainer returns an attribute KeyValue conforming to the -// "db.cosmosdb.container" semantic conventions. It represents the cosmos DB -// container name. -func DBCosmosDBContainer(val string) attribute.KeyValue { - return DBCosmosDBContainerKey.String(val) -} - -// DBCosmosDBRequestContentLength returns an attribute KeyValue conforming -// to the "db.cosmosdb.request_content_length" semantic conventions. It -// represents the request payload size in bytes -func DBCosmosDBRequestContentLength(val int) attribute.KeyValue { - return DBCosmosDBRequestContentLengthKey.Int(val) -} - -// DBCosmosDBStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.status_code" semantic conventions. It represents the cosmos DB -// status code. -func DBCosmosDBStatusCode(val int) attribute.KeyValue { - return DBCosmosDBStatusCodeKey.Int(val) -} - -// DBCosmosDBSubStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.sub_status_code" semantic conventions. It represents the cosmos -// DB sub status code. -func DBCosmosDBSubStatusCode(val int) attribute.KeyValue { - return DBCosmosDBSubStatusCodeKey.Int(val) -} - -// DBCosmosDBRequestCharge returns an attribute KeyValue conforming to the -// "db.cosmosdb.request_charge" semantic conventions. It represents the rU -// consumed for that operation -func DBCosmosDBRequestCharge(val float64) attribute.KeyValue { - return DBCosmosDBRequestChargeKey.Float64(val) -} - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry Span's -// concepts. -const ( - // OTelStatusCodeKey is the attribute Key conforming to the - // "otel.status_code" semantic conventions. It represents the name of the - // code, either "OK" or "ERROR". MUST NOT be set if the status code is - // UNSET. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - OTelStatusCodeKey = attribute.Key("otel.status_code") - - // OTelStatusDescriptionKey is the attribute Key conforming to the - // "otel.status_description" semantic conventions. It represents the - // description of the Status if it has a value, otherwise not set. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'resource not found' - OTelStatusDescriptionKey = attribute.Key("otel.status_description") -) - -var ( - // The operation has been validated by an Application developer or Operator to have completed successfully - OTelStatusCodeOk = OTelStatusCodeKey.String("OK") - // The operation contains an error - OTelStatusCodeError = OTelStatusCodeKey.String("ERROR") -) - -// OTelStatusDescription returns an attribute KeyValue conforming to the -// "otel.status_description" semantic conventions. It represents the -// description of the Status if it has a value, otherwise not set. -func OTelStatusDescription(val string) attribute.KeyValue { - return OTelStatusDescriptionKey.String(val) -} - -// This semantic convention describes an instance of a function that runs -// without provisioning or managing of servers (also known as serverless -// functions or Function as a Service (FaaS)) with spans. -const ( - // FaaSTriggerKey is the attribute Key conforming to the "faas.trigger" - // semantic conventions. It represents the type of the trigger which caused - // this function invocation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: For the server/consumer span on the incoming side, - // `faas.trigger` MUST be set. - // - // Clients invoking FaaS instances usually cannot set `faas.trigger`, - // since they would typically need to look in the payload to determine - // the event type. If clients set it, it should be the same as the - // trigger that corresponding incoming would have (i.e., this has - // nothing to do with the underlying transport used to make the API - // call to invoke the lambda, which is often HTTP). - FaaSTriggerKey = attribute.Key("faas.trigger") - - // FaaSInvocationIDKey is the attribute Key conforming to the - // "faas.invocation_id" semantic conventions. It represents the invocation - // ID of the current function invocation. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'af9d5aa4-a685-4c5f-a22b-444f80b3cc28' - FaaSInvocationIDKey = attribute.Key("faas.invocation_id") -) - -var ( - // A response to some data source operation such as a database or filesystem read/write - FaaSTriggerDatasource = FaaSTriggerKey.String("datasource") - // To provide an answer to an inbound HTTP request - FaaSTriggerHTTP = FaaSTriggerKey.String("http") - // A function is set to be executed when messages are sent to a messaging system - FaaSTriggerPubsub = FaaSTriggerKey.String("pubsub") - // A function is scheduled to be executed regularly - FaaSTriggerTimer = FaaSTriggerKey.String("timer") - // If none of the others apply - FaaSTriggerOther = FaaSTriggerKey.String("other") -) - -// FaaSInvocationID returns an attribute KeyValue conforming to the -// "faas.invocation_id" semantic conventions. It represents the invocation ID -// of the current function invocation. -func FaaSInvocationID(val string) attribute.KeyValue { - return FaaSInvocationIDKey.String(val) -} - -// Semantic Convention for FaaS triggered as a response to some data source -// operation such as a database or filesystem read/write. -const ( - // FaaSDocumentCollectionKey is the attribute Key conforming to the - // "faas.document.collection" semantic conventions. It represents the name - // of the source on which the triggering operation was performed. For - // example, in Cloud Storage or S3 corresponds to the bucket name, and in - // Cosmos DB to the database name. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myBucketName', 'myDBName' - FaaSDocumentCollectionKey = attribute.Key("faas.document.collection") - - // FaaSDocumentOperationKey is the attribute Key conforming to the - // "faas.document.operation" semantic conventions. It represents the - // describes the type of the operation that was performed on the data. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - FaaSDocumentOperationKey = attribute.Key("faas.document.operation") - - // FaaSDocumentTimeKey is the attribute Key conforming to the - // "faas.document.time" semantic conventions. It represents a string - // containing the time when the data was accessed in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2020-01-23T13:47:06Z' - FaaSDocumentTimeKey = attribute.Key("faas.document.time") - - // FaaSDocumentNameKey is the attribute Key conforming to the - // "faas.document.name" semantic conventions. It represents the document - // name/table subjected to the operation. For example, in Cloud Storage or - // S3 is the name of the file, and in Cosmos DB the table name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'myFile.txt', 'myTableName' - FaaSDocumentNameKey = attribute.Key("faas.document.name") -) - -var ( - // When a new object is created - FaaSDocumentOperationInsert = FaaSDocumentOperationKey.String("insert") - // When an object is modified - FaaSDocumentOperationEdit = FaaSDocumentOperationKey.String("edit") - // When an object is deleted - FaaSDocumentOperationDelete = FaaSDocumentOperationKey.String("delete") -) - -// FaaSDocumentCollection returns an attribute KeyValue conforming to the -// "faas.document.collection" semantic conventions. It represents the name of -// the source on which the triggering operation was performed. For example, in -// Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the -// database name. -func FaaSDocumentCollection(val string) attribute.KeyValue { - return FaaSDocumentCollectionKey.String(val) -} - -// FaaSDocumentTime returns an attribute KeyValue conforming to the -// "faas.document.time" semantic conventions. It represents a string containing -// the time when the data was accessed in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSDocumentTime(val string) attribute.KeyValue { - return FaaSDocumentTimeKey.String(val) -} - -// FaaSDocumentName returns an attribute KeyValue conforming to the -// "faas.document.name" semantic conventions. It represents the document -// name/table subjected to the operation. For example, in Cloud Storage or S3 -// is the name of the file, and in Cosmos DB the table name. -func FaaSDocumentName(val string) attribute.KeyValue { - return FaaSDocumentNameKey.String(val) -} - -// Semantic Convention for FaaS scheduled to be executed regularly. -const ( - // FaaSTimeKey is the attribute Key conforming to the "faas.time" semantic - // conventions. It represents a string containing the function invocation - // time in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2020-01-23T13:47:06Z' - FaaSTimeKey = attribute.Key("faas.time") - - // FaaSCronKey is the attribute Key conforming to the "faas.cron" semantic - // conventions. It represents a string containing the schedule period as - // [Cron - // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0/5 * * * ? *' - FaaSCronKey = attribute.Key("faas.cron") -) - -// FaaSTime returns an attribute KeyValue conforming to the "faas.time" -// semantic conventions. It represents a string containing the function -// invocation time in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSTime(val string) attribute.KeyValue { - return FaaSTimeKey.String(val) -} - -// FaaSCron returns an attribute KeyValue conforming to the "faas.cron" -// semantic conventions. It represents a string containing the schedule period -// as [Cron -// Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). -func FaaSCron(val string) attribute.KeyValue { - return FaaSCronKey.String(val) -} - -// Contains additional attributes for incoming FaaS spans. -const ( - // FaaSColdstartKey is the attribute Key conforming to the "faas.coldstart" - // semantic conventions. It represents a boolean that is true if the - // serverless function is executed for the first time (aka cold-start). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - FaaSColdstartKey = attribute.Key("faas.coldstart") -) - -// FaaSColdstart returns an attribute KeyValue conforming to the -// "faas.coldstart" semantic conventions. It represents a boolean that is true -// if the serverless function is executed for the first time (aka cold-start). -func FaaSColdstart(val bool) attribute.KeyValue { - return FaaSColdstartKey.Bool(val) -} - -// Contains additional attributes for outgoing FaaS spans. -const ( - // FaaSInvokedNameKey is the attribute Key conforming to the - // "faas.invoked_name" semantic conventions. It represents the name of the - // invoked function. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'my-function' - // Note: SHOULD be equal to the `faas.name` resource attribute of the - // invoked function. - FaaSInvokedNameKey = attribute.Key("faas.invoked_name") - - // FaaSInvokedProviderKey is the attribute Key conforming to the - // "faas.invoked_provider" semantic conventions. It represents the cloud - // provider of the invoked function. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: SHOULD be equal to the `cloud.provider` resource attribute of the - // invoked function. - FaaSInvokedProviderKey = attribute.Key("faas.invoked_provider") - - // FaaSInvokedRegionKey is the attribute Key conforming to the - // "faas.invoked_region" semantic conventions. It represents the cloud - // region of the invoked function. - // - // Type: string - // RequirementLevel: ConditionallyRequired (For some cloud providers, like - // AWS or GCP, the region in which a function is hosted is essential to - // uniquely identify the function and also part of its endpoint. Since it's - // part of the endpoint being called, the region is always known to - // clients. In these cases, `faas.invoked_region` MUST be set accordingly. - // If the region is unknown to the client or not required for identifying - // the invoked function, setting `faas.invoked_region` is optional.) - // Stability: stable - // Examples: 'eu-central-1' - // Note: SHOULD be equal to the `cloud.region` resource attribute of the - // invoked function. - FaaSInvokedRegionKey = attribute.Key("faas.invoked_region") -) - -var ( - // Alibaba Cloud - FaaSInvokedProviderAlibabaCloud = FaaSInvokedProviderKey.String("alibaba_cloud") - // Amazon Web Services - FaaSInvokedProviderAWS = FaaSInvokedProviderKey.String("aws") - // Microsoft Azure - FaaSInvokedProviderAzure = FaaSInvokedProviderKey.String("azure") - // Google Cloud Platform - FaaSInvokedProviderGCP = FaaSInvokedProviderKey.String("gcp") - // Tencent Cloud - FaaSInvokedProviderTencentCloud = FaaSInvokedProviderKey.String("tencent_cloud") -) - -// FaaSInvokedName returns an attribute KeyValue conforming to the -// "faas.invoked_name" semantic conventions. It represents the name of the -// invoked function. -func FaaSInvokedName(val string) attribute.KeyValue { - return FaaSInvokedNameKey.String(val) -} - -// FaaSInvokedRegion returns an attribute KeyValue conforming to the -// "faas.invoked_region" semantic conventions. It represents the cloud region -// of the invoked function. -func FaaSInvokedRegion(val string) attribute.KeyValue { - return FaaSInvokedRegionKey.String(val) -} - -// Operations that access some remote service. -const ( - // PeerServiceKey is the attribute Key conforming to the "peer.service" - // semantic conventions. It represents the - // [`service.name`](../../resource/semantic_conventions/README.md#service) - // of the remote service. SHOULD be equal to the actual `service.name` - // resource attribute of the remote service if any. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'AuthTokenCache' - PeerServiceKey = attribute.Key("peer.service") -) - -// PeerService returns an attribute KeyValue conforming to the -// "peer.service" semantic conventions. It represents the -// [`service.name`](../../resource/semantic_conventions/README.md#service) of -// the remote service. SHOULD be equal to the actual `service.name` resource -// attribute of the remote service if any. -func PeerService(val string) attribute.KeyValue { - return PeerServiceKey.String(val) -} - -// These attributes may be used for any operation with an authenticated and/or -// authorized enduser. -const ( - // EnduserIDKey is the attribute Key conforming to the "enduser.id" - // semantic conventions. It represents the username or client_id extracted - // from the access token or - // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header - // in the inbound request from outside the system. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'username' - EnduserIDKey = attribute.Key("enduser.id") - - // EnduserRoleKey is the attribute Key conforming to the "enduser.role" - // semantic conventions. It represents the actual/assumed role the client - // is making the request under extracted from token or application security - // context. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'admin' - EnduserRoleKey = attribute.Key("enduser.role") - - // EnduserScopeKey is the attribute Key conforming to the "enduser.scope" - // semantic conventions. It represents the scopes or granted authorities - // the client currently possesses extracted from token or application - // security context. The value would come from the scope associated with an - // [OAuth 2.0 Access - // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute - // value in a [SAML 2.0 - // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'read:message, write:files' - EnduserScopeKey = attribute.Key("enduser.scope") -) - -// EnduserID returns an attribute KeyValue conforming to the "enduser.id" -// semantic conventions. It represents the username or client_id extracted from -// the access token or -// [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in -// the inbound request from outside the system. -func EnduserID(val string) attribute.KeyValue { - return EnduserIDKey.String(val) -} - -// EnduserRole returns an attribute KeyValue conforming to the -// "enduser.role" semantic conventions. It represents the actual/assumed role -// the client is making the request under extracted from token or application -// security context. -func EnduserRole(val string) attribute.KeyValue { - return EnduserRoleKey.String(val) -} - -// EnduserScope returns an attribute KeyValue conforming to the -// "enduser.scope" semantic conventions. It represents the scopes or granted -// authorities the client currently possesses extracted from token or -// application security context. The value would come from the scope associated -// with an [OAuth 2.0 Access -// Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute -// value in a [SAML 2.0 -// Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). -func EnduserScope(val string) attribute.KeyValue { - return EnduserScopeKey.String(val) -} - -// These attributes may be used for any operation to store information about a -// thread that started a span. -const ( - // ThreadIDKey is the attribute Key conforming to the "thread.id" semantic - // conventions. It represents the current "managed" thread ID (as opposed - // to OS thread ID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - ThreadIDKey = attribute.Key("thread.id") - - // ThreadNameKey is the attribute Key conforming to the "thread.name" - // semantic conventions. It represents the current thread name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'main' - ThreadNameKey = attribute.Key("thread.name") -) - -// ThreadID returns an attribute KeyValue conforming to the "thread.id" -// semantic conventions. It represents the current "managed" thread ID (as -// opposed to OS thread ID). -func ThreadID(val int) attribute.KeyValue { - return ThreadIDKey.Int(val) -} - -// ThreadName returns an attribute KeyValue conforming to the "thread.name" -// semantic conventions. It represents the current thread name. -func ThreadName(val string) attribute.KeyValue { - return ThreadNameKey.String(val) -} - -// These attributes allow to report this unit of code and therefore to provide -// more context about the span. -const ( - // CodeFunctionKey is the attribute Key conforming to the "code.function" - // semantic conventions. It represents the method or function name, or - // equivalent (usually rightmost part of the code unit's name). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'serveRequest' - CodeFunctionKey = attribute.Key("code.function") - - // CodeNamespaceKey is the attribute Key conforming to the "code.namespace" - // semantic conventions. It represents the "namespace" within which - // `code.function` is defined. Usually the qualified class or module name, - // such that `code.namespace` + some separator + `code.function` form a - // unique identifier for the code unit. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'com.example.MyHTTPService' - CodeNamespaceKey = attribute.Key("code.namespace") - - // CodeFilepathKey is the attribute Key conforming to the "code.filepath" - // semantic conventions. It represents the source code file name that - // identifies the code unit as uniquely as possible (preferably an absolute - // file path). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/usr/local/MyApplication/content_root/app/index.php' - CodeFilepathKey = attribute.Key("code.filepath") - - // CodeLineNumberKey is the attribute Key conforming to the "code.lineno" - // semantic conventions. It represents the line number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - CodeLineNumberKey = attribute.Key("code.lineno") - - // CodeColumnKey is the attribute Key conforming to the "code.column" - // semantic conventions. It represents the column number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 16 - CodeColumnKey = attribute.Key("code.column") -) - -// CodeFunction returns an attribute KeyValue conforming to the -// "code.function" semantic conventions. It represents the method or function -// name, or equivalent (usually rightmost part of the code unit's name). -func CodeFunction(val string) attribute.KeyValue { - return CodeFunctionKey.String(val) -} - -// CodeNamespace returns an attribute KeyValue conforming to the -// "code.namespace" semantic conventions. It represents the "namespace" within -// which `code.function` is defined. Usually the qualified class or module -// name, such that `code.namespace` + some separator + `code.function` form a -// unique identifier for the code unit. -func CodeNamespace(val string) attribute.KeyValue { - return CodeNamespaceKey.String(val) -} - -// CodeFilepath returns an attribute KeyValue conforming to the -// "code.filepath" semantic conventions. It represents the source code file -// name that identifies the code unit as uniquely as possible (preferably an -// absolute file path). -func CodeFilepath(val string) attribute.KeyValue { - return CodeFilepathKey.String(val) -} - -// CodeLineNumber returns an attribute KeyValue conforming to the "code.lineno" -// semantic conventions. It represents the line number in `code.filepath` best -// representing the operation. It SHOULD point within the code unit named in -// `code.function`. -func CodeLineNumber(val int) attribute.KeyValue { - return CodeLineNumberKey.Int(val) -} - -// CodeColumn returns an attribute KeyValue conforming to the "code.column" -// semantic conventions. It represents the column number in `code.filepath` -// best representing the operation. It SHOULD point within the code unit named -// in `code.function`. -func CodeColumn(val int) attribute.KeyValue { - return CodeColumnKey.Int(val) -} - -// Semantic Convention for HTTP Client -const ( - // HTTPURLKey is the attribute Key conforming to the "http.url" semantic - // conventions. It represents the full HTTP request URL in the form - // `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is - // not transmitted over HTTP, but if it is known, it should be included - // nevertheless. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv' - // Note: `http.url` MUST NOT contain credentials passed via URL in form of - // `https://username:password@www.example.com/`. In such case the - // attribute's value should be `https://www.example.com/`. - HTTPURLKey = attribute.Key("http.url") - - // HTTPResendCountKey is the attribute Key conforming to the - // "http.resend_count" semantic conventions. It represents the ordinal - // number of request resending attempt (for any reason, including - // redirects). - // - // Type: int - // RequirementLevel: Recommended (if and only if request was retried.) - // Stability: stable - // Examples: 3 - // Note: The resend count SHOULD be updated each time an HTTP request gets - // resent by the client, regardless of what was the cause of the resending - // (e.g. redirection, authorization failure, 503 Server Unavailable, - // network issues, or any other). - HTTPResendCountKey = attribute.Key("http.resend_count") -) - -// HTTPURL returns an attribute KeyValue conforming to the "http.url" -// semantic conventions. It represents the full HTTP request URL in the form -// `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not -// transmitted over HTTP, but if it is known, it should be included -// nevertheless. -func HTTPURL(val string) attribute.KeyValue { - return HTTPURLKey.String(val) -} - -// HTTPResendCount returns an attribute KeyValue conforming to the -// "http.resend_count" semantic conventions. It represents the ordinal number -// of request resending attempt (for any reason, including redirects). -func HTTPResendCount(val int) attribute.KeyValue { - return HTTPResendCountKey.Int(val) -} - -// Semantic Convention for HTTP Server -const ( - // HTTPTargetKey is the attribute Key conforming to the "http.target" - // semantic conventions. It represents the full request target as passed in - // a HTTP request line or equivalent. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '/users/12314/?q=ddds' - HTTPTargetKey = attribute.Key("http.target") - - // HTTPClientIPKey is the attribute Key conforming to the "http.client_ip" - // semantic conventions. It represents the IP address of the original - // client behind all proxies, if known (e.g. from - // [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '83.164.160.102' - // Note: This is not necessarily the same as `net.sock.peer.addr`, which - // would - // identify the network-level peer, which may be a proxy. - // - // This attribute should be set when a source of information different - // from the one used for `net.sock.peer.addr`, is available even if that - // other - // source just confirms the same value as `net.sock.peer.addr`. - // Rationale: For `net.sock.peer.addr`, one typically does not know if it - // comes from a proxy, reverse proxy, or the actual client. Setting - // `http.client_ip` when it's the same as `net.sock.peer.addr` means that - // one is at least somewhat confident that the address is not that of - // the closest proxy. - HTTPClientIPKey = attribute.Key("http.client_ip") -) - -// HTTPTarget returns an attribute KeyValue conforming to the "http.target" -// semantic conventions. It represents the full request target as passed in a -// HTTP request line or equivalent. -func HTTPTarget(val string) attribute.KeyValue { - return HTTPTargetKey.String(val) -} - -// HTTPClientIP returns an attribute KeyValue conforming to the -// "http.client_ip" semantic conventions. It represents the IP address of the -// original client behind all proxies, if known (e.g. from -// [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). -func HTTPClientIP(val string) attribute.KeyValue { - return HTTPClientIPKey.String(val) -} - -// The `aws` conventions apply to operations using the AWS SDK. They map -// request or response parameters in AWS SDK API calls to attributes on a Span. -// The conventions have been collected over time based on feedback from AWS -// users of tracing and will continue to evolve as new interesting conventions -// are found. -// Some descriptions are also provided for populating general OpenTelemetry -// semantic conventions based on these APIs. -const ( - // AWSRequestIDKey is the attribute Key conforming to the "aws.request_id" - // semantic conventions. It represents the AWS request ID as returned in - // the response headers `x-amz-request-id` or `x-amz-requestid`. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '79b9da39-b7ae-508a-a6bc-864b2829c622', 'C9ER4AJX75574TDJ' - AWSRequestIDKey = attribute.Key("aws.request_id") -) - -// AWSRequestID returns an attribute KeyValue conforming to the -// "aws.request_id" semantic conventions. It represents the AWS request ID as -// returned in the response headers `x-amz-request-id` or `x-amz-requestid`. -func AWSRequestID(val string) attribute.KeyValue { - return AWSRequestIDKey.String(val) -} - -// Attributes that exist for multiple DynamoDB request types. -const ( - // AWSDynamoDBTableNamesKey is the attribute Key conforming to the - // "aws.dynamodb.table_names" semantic conventions. It represents the keys - // in the `RequestItems` object field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Users', 'Cats' - AWSDynamoDBTableNamesKey = attribute.Key("aws.dynamodb.table_names") - - // AWSDynamoDBConsumedCapacityKey is the attribute Key conforming to the - // "aws.dynamodb.consumed_capacity" semantic conventions. It represents the - // JSON-serialized value of each item in the `ConsumedCapacity` response - // field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "CapacityUnits": number, "GlobalSecondaryIndexes": { - // "string" : { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "LocalSecondaryIndexes": { "string" : - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "ReadCapacityUnits": number, "Table": - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number }, "TableName": "string", - // "WriteCapacityUnits": number }' - AWSDynamoDBConsumedCapacityKey = attribute.Key("aws.dynamodb.consumed_capacity") - - // AWSDynamoDBItemCollectionMetricsKey is the attribute Key conforming to - // the "aws.dynamodb.item_collection_metrics" semantic conventions. It - // represents the JSON-serialized value of the `ItemCollectionMetrics` - // response field. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "string" : [ { "ItemCollectionKey": { "string" : { "B": - // blob, "BOOL": boolean, "BS": [ blob ], "L": [ "AttributeValue" ], "M": { - // "string" : "AttributeValue" }, "N": "string", "NS": [ "string" ], - // "NULL": boolean, "S": "string", "SS": [ "string" ] } }, - // "SizeEstimateRangeGB": [ number ] } ] }' - AWSDynamoDBItemCollectionMetricsKey = attribute.Key("aws.dynamodb.item_collection_metrics") - - // AWSDynamoDBProvisionedReadCapacityKey is the attribute Key conforming to - // the "aws.dynamodb.provisioned_read_capacity" semantic conventions. It - // represents the value of the `ProvisionedThroughput.ReadCapacityUnits` - // request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: stable - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedReadCapacityKey = attribute.Key("aws.dynamodb.provisioned_read_capacity") - - // AWSDynamoDBProvisionedWriteCapacityKey is the attribute Key conforming - // to the "aws.dynamodb.provisioned_write_capacity" semantic conventions. - // It represents the value of the - // `ProvisionedThroughput.WriteCapacityUnits` request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: stable - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedWriteCapacityKey = attribute.Key("aws.dynamodb.provisioned_write_capacity") - - // AWSDynamoDBConsistentReadKey is the attribute Key conforming to the - // "aws.dynamodb.consistent_read" semantic conventions. It represents the - // value of the `ConsistentRead` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - AWSDynamoDBConsistentReadKey = attribute.Key("aws.dynamodb.consistent_read") - - // AWSDynamoDBProjectionKey is the attribute Key conforming to the - // "aws.dynamodb.projection" semantic conventions. It represents the value - // of the `ProjectionExpression` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Title', 'Title, Price, Color', 'Title, Description, - // RelatedItems, ProductReviews' - AWSDynamoDBProjectionKey = attribute.Key("aws.dynamodb.projection") - - // AWSDynamoDBLimitKey is the attribute Key conforming to the - // "aws.dynamodb.limit" semantic conventions. It represents the value of - // the `Limit` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBLimitKey = attribute.Key("aws.dynamodb.limit") - - // AWSDynamoDBAttributesToGetKey is the attribute Key conforming to the - // "aws.dynamodb.attributes_to_get" semantic conventions. It represents the - // value of the `AttributesToGet` request parameter. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'lives', 'id' - AWSDynamoDBAttributesToGetKey = attribute.Key("aws.dynamodb.attributes_to_get") - - // AWSDynamoDBIndexNameKey is the attribute Key conforming to the - // "aws.dynamodb.index_name" semantic conventions. It represents the value - // of the `IndexName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'name_to_group' - AWSDynamoDBIndexNameKey = attribute.Key("aws.dynamodb.index_name") - - // AWSDynamoDBSelectKey is the attribute Key conforming to the - // "aws.dynamodb.select" semantic conventions. It represents the value of - // the `Select` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ALL_ATTRIBUTES', 'COUNT' - AWSDynamoDBSelectKey = attribute.Key("aws.dynamodb.select") -) - -// AWSDynamoDBTableNames returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_names" semantic conventions. It represents the keys in -// the `RequestItems` object field. -func AWSDynamoDBTableNames(val ...string) attribute.KeyValue { - return AWSDynamoDBTableNamesKey.StringSlice(val) -} - -// AWSDynamoDBConsumedCapacity returns an attribute KeyValue conforming to -// the "aws.dynamodb.consumed_capacity" semantic conventions. It represents the -// JSON-serialized value of each item in the `ConsumedCapacity` response field. -func AWSDynamoDBConsumedCapacity(val ...string) attribute.KeyValue { - return AWSDynamoDBConsumedCapacityKey.StringSlice(val) -} - -// AWSDynamoDBItemCollectionMetrics returns an attribute KeyValue conforming -// to the "aws.dynamodb.item_collection_metrics" semantic conventions. It -// represents the JSON-serialized value of the `ItemCollectionMetrics` response -// field. -func AWSDynamoDBItemCollectionMetrics(val string) attribute.KeyValue { - return AWSDynamoDBItemCollectionMetricsKey.String(val) -} - -// AWSDynamoDBProvisionedReadCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_read_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.ReadCapacityUnits` request parameter. -func AWSDynamoDBProvisionedReadCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedReadCapacityKey.Float64(val) -} - -// AWSDynamoDBProvisionedWriteCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_write_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.WriteCapacityUnits` request parameter. -func AWSDynamoDBProvisionedWriteCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedWriteCapacityKey.Float64(val) -} - -// AWSDynamoDBConsistentRead returns an attribute KeyValue conforming to the -// "aws.dynamodb.consistent_read" semantic conventions. It represents the value -// of the `ConsistentRead` request parameter. -func AWSDynamoDBConsistentRead(val bool) attribute.KeyValue { - return AWSDynamoDBConsistentReadKey.Bool(val) -} - -// AWSDynamoDBProjection returns an attribute KeyValue conforming to the -// "aws.dynamodb.projection" semantic conventions. It represents the value of -// the `ProjectionExpression` request parameter. -func AWSDynamoDBProjection(val string) attribute.KeyValue { - return AWSDynamoDBProjectionKey.String(val) -} - -// AWSDynamoDBLimit returns an attribute KeyValue conforming to the -// "aws.dynamodb.limit" semantic conventions. It represents the value of the -// `Limit` request parameter. -func AWSDynamoDBLimit(val int) attribute.KeyValue { - return AWSDynamoDBLimitKey.Int(val) -} - -// AWSDynamoDBAttributesToGet returns an attribute KeyValue conforming to -// the "aws.dynamodb.attributes_to_get" semantic conventions. It represents the -// value of the `AttributesToGet` request parameter. -func AWSDynamoDBAttributesToGet(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributesToGetKey.StringSlice(val) -} - -// AWSDynamoDBIndexName returns an attribute KeyValue conforming to the -// "aws.dynamodb.index_name" semantic conventions. It represents the value of -// the `IndexName` request parameter. -func AWSDynamoDBIndexName(val string) attribute.KeyValue { - return AWSDynamoDBIndexNameKey.String(val) -} - -// AWSDynamoDBSelect returns an attribute KeyValue conforming to the -// "aws.dynamodb.select" semantic conventions. It represents the value of the -// `Select` request parameter. -func AWSDynamoDBSelect(val string) attribute.KeyValue { - return AWSDynamoDBSelectKey.String(val) -} - -// DynamoDB.CreateTable -const ( - // AWSDynamoDBGlobalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.global_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `GlobalSecondaryIndexes` request field - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "IndexName": "string", "KeySchema": [ { "AttributeName": - // "string", "KeyType": "string" } ], "Projection": { "NonKeyAttributes": [ - // "string" ], "ProjectionType": "string" }, "ProvisionedThroughput": { - // "ReadCapacityUnits": number, "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexesKey = attribute.Key("aws.dynamodb.global_secondary_indexes") - - // AWSDynamoDBLocalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.local_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `LocalSecondaryIndexes` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "IndexARN": "string", "IndexName": "string", - // "IndexSizeBytes": number, "ItemCount": number, "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" } }' - AWSDynamoDBLocalSecondaryIndexesKey = attribute.Key("aws.dynamodb.local_secondary_indexes") -) - -// AWSDynamoDBGlobalSecondaryIndexes returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_indexes" semantic -// conventions. It represents the JSON-serialized value of each item of the -// `GlobalSecondaryIndexes` request field -func AWSDynamoDBGlobalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexesKey.StringSlice(val) -} - -// AWSDynamoDBLocalSecondaryIndexes returns an attribute KeyValue conforming -// to the "aws.dynamodb.local_secondary_indexes" semantic conventions. It -// represents the JSON-serialized value of each item of the -// `LocalSecondaryIndexes` request field. -func AWSDynamoDBLocalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBLocalSecondaryIndexesKey.StringSlice(val) -} - -// DynamoDB.ListTables -const ( - // AWSDynamoDBExclusiveStartTableKey is the attribute Key conforming to the - // "aws.dynamodb.exclusive_start_table" semantic conventions. It represents - // the value of the `ExclusiveStartTableName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Users', 'CatsTable' - AWSDynamoDBExclusiveStartTableKey = attribute.Key("aws.dynamodb.exclusive_start_table") - - // AWSDynamoDBTableCountKey is the attribute Key conforming to the - // "aws.dynamodb.table_count" semantic conventions. It represents the the - // number of items in the `TableNames` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 20 - AWSDynamoDBTableCountKey = attribute.Key("aws.dynamodb.table_count") -) - -// AWSDynamoDBExclusiveStartTable returns an attribute KeyValue conforming -// to the "aws.dynamodb.exclusive_start_table" semantic conventions. It -// represents the value of the `ExclusiveStartTableName` request parameter. -func AWSDynamoDBExclusiveStartTable(val string) attribute.KeyValue { - return AWSDynamoDBExclusiveStartTableKey.String(val) -} - -// AWSDynamoDBTableCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_count" semantic conventions. It represents the the -// number of items in the `TableNames` response parameter. -func AWSDynamoDBTableCount(val int) attribute.KeyValue { - return AWSDynamoDBTableCountKey.Int(val) -} - -// DynamoDB.Query -const ( - // AWSDynamoDBScanForwardKey is the attribute Key conforming to the - // "aws.dynamodb.scan_forward" semantic conventions. It represents the - // value of the `ScanIndexForward` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - AWSDynamoDBScanForwardKey = attribute.Key("aws.dynamodb.scan_forward") -) - -// AWSDynamoDBScanForward returns an attribute KeyValue conforming to the -// "aws.dynamodb.scan_forward" semantic conventions. It represents the value of -// the `ScanIndexForward` request parameter. -func AWSDynamoDBScanForward(val bool) attribute.KeyValue { - return AWSDynamoDBScanForwardKey.Bool(val) -} - -// DynamoDB.Scan -const ( - // AWSDynamoDBSegmentKey is the attribute Key conforming to the - // "aws.dynamodb.segment" semantic conventions. It represents the value of - // the `Segment` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBSegmentKey = attribute.Key("aws.dynamodb.segment") - - // AWSDynamoDBTotalSegmentsKey is the attribute Key conforming to the - // "aws.dynamodb.total_segments" semantic conventions. It represents the - // value of the `TotalSegments` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 100 - AWSDynamoDBTotalSegmentsKey = attribute.Key("aws.dynamodb.total_segments") - - // AWSDynamoDBCountKey is the attribute Key conforming to the - // "aws.dynamodb.count" semantic conventions. It represents the value of - // the `Count` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBCountKey = attribute.Key("aws.dynamodb.count") - - // AWSDynamoDBScannedCountKey is the attribute Key conforming to the - // "aws.dynamodb.scanned_count" semantic conventions. It represents the - // value of the `ScannedCount` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 50 - AWSDynamoDBScannedCountKey = attribute.Key("aws.dynamodb.scanned_count") -) - -// AWSDynamoDBSegment returns an attribute KeyValue conforming to the -// "aws.dynamodb.segment" semantic conventions. It represents the value of the -// `Segment` request parameter. -func AWSDynamoDBSegment(val int) attribute.KeyValue { - return AWSDynamoDBSegmentKey.Int(val) -} - -// AWSDynamoDBTotalSegments returns an attribute KeyValue conforming to the -// "aws.dynamodb.total_segments" semantic conventions. It represents the value -// of the `TotalSegments` request parameter. -func AWSDynamoDBTotalSegments(val int) attribute.KeyValue { - return AWSDynamoDBTotalSegmentsKey.Int(val) -} - -// AWSDynamoDBCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.count" semantic conventions. It represents the value of the -// `Count` response parameter. -func AWSDynamoDBCount(val int) attribute.KeyValue { - return AWSDynamoDBCountKey.Int(val) -} - -// AWSDynamoDBScannedCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.scanned_count" semantic conventions. It represents the value -// of the `ScannedCount` response parameter. -func AWSDynamoDBScannedCount(val int) attribute.KeyValue { - return AWSDynamoDBScannedCountKey.Int(val) -} - -// DynamoDB.UpdateTable -const ( - // AWSDynamoDBAttributeDefinitionsKey is the attribute Key conforming to - // the "aws.dynamodb.attribute_definitions" semantic conventions. It - // represents the JSON-serialized value of each item in the - // `AttributeDefinitions` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "AttributeName": "string", "AttributeType": "string" }' - AWSDynamoDBAttributeDefinitionsKey = attribute.Key("aws.dynamodb.attribute_definitions") - - // AWSDynamoDBGlobalSecondaryIndexUpdatesKey is the attribute Key - // conforming to the "aws.dynamodb.global_secondary_index_updates" semantic - // conventions. It represents the JSON-serialized value of each item in the - // the `GlobalSecondaryIndexUpdates` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "Create": { "IndexName": "string", "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" }, - // "ProvisionedThroughput": { "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexUpdatesKey = attribute.Key("aws.dynamodb.global_secondary_index_updates") -) - -// AWSDynamoDBAttributeDefinitions returns an attribute KeyValue conforming -// to the "aws.dynamodb.attribute_definitions" semantic conventions. It -// represents the JSON-serialized value of each item in the -// `AttributeDefinitions` request field. -func AWSDynamoDBAttributeDefinitions(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributeDefinitionsKey.StringSlice(val) -} - -// AWSDynamoDBGlobalSecondaryIndexUpdates returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_index_updates" semantic -// conventions. It represents the JSON-serialized value of each item in the the -// `GlobalSecondaryIndexUpdates` request field. -func AWSDynamoDBGlobalSecondaryIndexUpdates(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexUpdatesKey.StringSlice(val) -} - -// Attributes that exist for S3 request types. -const ( - // AWSS3BucketKey is the attribute Key conforming to the "aws.s3.bucket" - // semantic conventions. It represents the S3 bucket name the request - // refers to. Corresponds to the `--bucket` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'some-bucket-name' - // Note: The `bucket` attribute is applicable to all S3 operations that - // reference a bucket, i.e. that require the bucket name as a mandatory - // parameter. - // This applies to almost all S3 operations except `list-buckets`. - AWSS3BucketKey = attribute.Key("aws.s3.bucket") - - // AWSS3KeyKey is the attribute Key conforming to the "aws.s3.key" semantic - // conventions. It represents the S3 object key the request refers to. - // Corresponds to the `--key` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'someFile.yml' - // Note: The `key` attribute is applicable to all object-related S3 - // operations, i.e. that require the object key as a mandatory parameter. - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // - - // [get-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html) - // - - // [head-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/head-object.html) - // - - // [put-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html) - // - - // [restore-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/restore-object.html) - // - - // [select-object-content](https://docs.aws.amazon.com/cli/latest/reference/s3api/select-object-content.html) - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [create-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/create-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3KeyKey = attribute.Key("aws.s3.key") - - // AWSS3CopySourceKey is the attribute Key conforming to the - // "aws.s3.copy_source" semantic conventions. It represents the source - // object (in the form `bucket`/`key`) for the copy operation. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'someFile.yml' - // Note: The `copy_source` attribute applies to S3 copy operations and - // corresponds to the `--copy-source` parameter - // of the [copy-object operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html). - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3CopySourceKey = attribute.Key("aws.s3.copy_source") - - // AWSS3UploadIDKey is the attribute Key conforming to the - // "aws.s3.upload_id" semantic conventions. It represents the upload ID - // that identifies the multipart upload. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'dfRtDYWFbkRONycy.Yxwh66Yjlx.cph0gtNBtJ' - // Note: The `upload_id` attribute applies to S3 multipart-upload - // operations and corresponds to the `--upload-id` parameter - // of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // multipart operations. - // This applies in particular to the following operations: - // - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3UploadIDKey = attribute.Key("aws.s3.upload_id") - - // AWSS3DeleteKey is the attribute Key conforming to the "aws.s3.delete" - // semantic conventions. It represents the delete request container that - // specifies the objects to be deleted. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'Objects=[{Key=string,VersionID=string},{Key=string,VersionID=string}],Quiet=boolean' - // Note: The `delete` attribute is only applicable to the - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // operation. - // The `delete` attribute corresponds to the `--delete` parameter of the - // [delete-objects operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-objects.html). - AWSS3DeleteKey = attribute.Key("aws.s3.delete") - - // AWSS3PartNumberKey is the attribute Key conforming to the - // "aws.s3.part_number" semantic conventions. It represents the part number - // of the part being uploaded in a multipart-upload operation. This is a - // positive integer between 1 and 10,000. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3456 - // Note: The `part_number` attribute is only applicable to the - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // and - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - // operations. - // The `part_number` attribute corresponds to the `--part-number` parameter - // of the - // [upload-part operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html). - AWSS3PartNumberKey = attribute.Key("aws.s3.part_number") -) - -// AWSS3Bucket returns an attribute KeyValue conforming to the -// "aws.s3.bucket" semantic conventions. It represents the S3 bucket name the -// request refers to. Corresponds to the `--bucket` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Bucket(val string) attribute.KeyValue { - return AWSS3BucketKey.String(val) -} - -// AWSS3Key returns an attribute KeyValue conforming to the "aws.s3.key" -// semantic conventions. It represents the S3 object key the request refers to. -// Corresponds to the `--key` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Key(val string) attribute.KeyValue { - return AWSS3KeyKey.String(val) -} - -// AWSS3CopySource returns an attribute KeyValue conforming to the -// "aws.s3.copy_source" semantic conventions. It represents the source object -// (in the form `bucket`/`key`) for the copy operation. -func AWSS3CopySource(val string) attribute.KeyValue { - return AWSS3CopySourceKey.String(val) -} - -// AWSS3UploadID returns an attribute KeyValue conforming to the -// "aws.s3.upload_id" semantic conventions. It represents the upload ID that -// identifies the multipart upload. -func AWSS3UploadID(val string) attribute.KeyValue { - return AWSS3UploadIDKey.String(val) -} - -// AWSS3Delete returns an attribute KeyValue conforming to the -// "aws.s3.delete" semantic conventions. It represents the delete request -// container that specifies the objects to be deleted. -func AWSS3Delete(val string) attribute.KeyValue { - return AWSS3DeleteKey.String(val) -} - -// AWSS3PartNumber returns an attribute KeyValue conforming to the -// "aws.s3.part_number" semantic conventions. It represents the part number of -// the part being uploaded in a multipart-upload operation. This is a positive -// integer between 1 and 10,000. -func AWSS3PartNumber(val int) attribute.KeyValue { - return AWSS3PartNumberKey.Int(val) -} - -// Semantic conventions to apply when instrumenting the GraphQL implementation. -// They map GraphQL operations to attributes on a Span. -const ( - // GraphqlOperationNameKey is the attribute Key conforming to the - // "graphql.operation.name" semantic conventions. It represents the name of - // the operation being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'findBookByID' - GraphqlOperationNameKey = attribute.Key("graphql.operation.name") - - // GraphqlOperationTypeKey is the attribute Key conforming to the - // "graphql.operation.type" semantic conventions. It represents the type of - // the operation being executed. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'query', 'mutation', 'subscription' - GraphqlOperationTypeKey = attribute.Key("graphql.operation.type") - - // GraphqlDocumentKey is the attribute Key conforming to the - // "graphql.document" semantic conventions. It represents the GraphQL - // document being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'query findBookByID { bookByID(id: ?) { name } }' - // Note: The value may be sanitized to exclude sensitive information. - GraphqlDocumentKey = attribute.Key("graphql.document") -) - -var ( - // GraphQL query - GraphqlOperationTypeQuery = GraphqlOperationTypeKey.String("query") - // GraphQL mutation - GraphqlOperationTypeMutation = GraphqlOperationTypeKey.String("mutation") - // GraphQL subscription - GraphqlOperationTypeSubscription = GraphqlOperationTypeKey.String("subscription") -) - -// GraphqlOperationName returns an attribute KeyValue conforming to the -// "graphql.operation.name" semantic conventions. It represents the name of the -// operation being executed. -func GraphqlOperationName(val string) attribute.KeyValue { - return GraphqlOperationNameKey.String(val) -} - -// GraphqlDocument returns an attribute KeyValue conforming to the -// "graphql.document" semantic conventions. It represents the GraphQL document -// being executed. -func GraphqlDocument(val string) attribute.KeyValue { - return GraphqlDocumentKey.String(val) -} - -// General attributes used in messaging systems. -const ( - // MessagingSystemKey is the attribute Key conforming to the - // "messaging.system" semantic conventions. It represents a string - // identifying the messaging system. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'kafka', 'rabbitmq', 'rocketmq', 'activemq', 'AmazonSQS' - MessagingSystemKey = attribute.Key("messaging.system") - - // MessagingOperationKey is the attribute Key conforming to the - // "messaging.operation" semantic conventions. It represents a string - // identifying the kind of messaging operation as defined in the [Operation - // names](#operation-names) section above. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: If a custom value is used, it MUST be of low cardinality. - MessagingOperationKey = attribute.Key("messaging.operation") - - // MessagingBatchMessageCountKey is the attribute Key conforming to the - // "messaging.batch.message_count" semantic conventions. It represents the - // number of messages sent, received, or processed in the scope of the - // batching operation. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the span describes an - // operation on a batch of messages.) - // Stability: stable - // Examples: 0, 1, 2 - // Note: Instrumentations SHOULD NOT set `messaging.batch.message_count` on - // spans that operate with a single message. When a messaging client - // library supports both batch and single-message API for the same - // operation, instrumentations SHOULD use `messaging.batch.message_count` - // for batching APIs and SHOULD NOT use it for single-message APIs. - MessagingBatchMessageCountKey = attribute.Key("messaging.batch.message_count") -) - -var ( - // publish - MessagingOperationPublish = MessagingOperationKey.String("publish") - // receive - MessagingOperationReceive = MessagingOperationKey.String("receive") - // process - MessagingOperationProcess = MessagingOperationKey.String("process") -) - -// MessagingSystem returns an attribute KeyValue conforming to the -// "messaging.system" semantic conventions. It represents a string identifying -// the messaging system. -func MessagingSystem(val string) attribute.KeyValue { - return MessagingSystemKey.String(val) -} - -// MessagingBatchMessageCount returns an attribute KeyValue conforming to -// the "messaging.batch.message_count" semantic conventions. It represents the -// number of messages sent, received, or processed in the scope of the batching -// operation. -func MessagingBatchMessageCount(val int) attribute.KeyValue { - return MessagingBatchMessageCountKey.Int(val) -} - -// Semantic convention for a consumer of messages received from a messaging -// system -const ( - // MessagingConsumerIDKey is the attribute Key conforming to the - // "messaging.consumer.id" semantic conventions. It represents the - // identifier for the consumer receiving a message. For Kafka, set it to - // `{messaging.kafka.consumer.group} - {messaging.kafka.client_id}`, if - // both are present, or only `messaging.kafka.consumer.group`. For brokers, - // such as RabbitMQ and Artemis, set it to the `client_id` of the client - // consuming the message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'mygroup - client-6' - MessagingConsumerIDKey = attribute.Key("messaging.consumer.id") -) - -// MessagingConsumerID returns an attribute KeyValue conforming to the -// "messaging.consumer.id" semantic conventions. It represents the identifier -// for the consumer receiving a message. For Kafka, set it to -// `{messaging.kafka.consumer.group} - {messaging.kafka.client_id}`, if both -// are present, or only `messaging.kafka.consumer.group`. For brokers, such as -// RabbitMQ and Artemis, set it to the `client_id` of the client consuming the -// message. -func MessagingConsumerID(val string) attribute.KeyValue { - return MessagingConsumerIDKey.String(val) -} - -// Semantic conventions for remote procedure calls. -const ( - // RPCSystemKey is the attribute Key conforming to the "rpc.system" - // semantic conventions. It represents a string identifying the remoting - // system. See below for a list of well-known identifiers. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - RPCSystemKey = attribute.Key("rpc.system") - - // RPCServiceKey is the attribute Key conforming to the "rpc.service" - // semantic conventions. It represents the full (logical) name of the - // service being called, including its package name, if applicable. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'myservice.EchoService' - // Note: This is the logical name of the service from the RPC interface - // perspective, which can be different from the name of any implementing - // class. The `code.namespace` attribute may be used to store the latter - // (despite the attribute name, it may include a class name; e.g., class - // with method actually executing the call on the server side, RPC client - // stub class on the client side). - RPCServiceKey = attribute.Key("rpc.service") - - // RPCMethodKey is the attribute Key conforming to the "rpc.method" - // semantic conventions. It represents the name of the (logical) method - // being called, must be equal to the $method part in the span name. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'exampleMethod' - // Note: This is the logical name of the method from the RPC interface - // perspective, which can be different from the name of any implementing - // method/function. The `code.function` attribute may be used to store the - // latter (e.g., method actually executing the call on the server side, RPC - // client stub method on the client side). - RPCMethodKey = attribute.Key("rpc.method") -) - -var ( - // gRPC - RPCSystemGRPC = RPCSystemKey.String("grpc") - // Java RMI - RPCSystemJavaRmi = RPCSystemKey.String("java_rmi") - // .NET WCF - RPCSystemDotnetWcf = RPCSystemKey.String("dotnet_wcf") - // Apache Dubbo - RPCSystemApacheDubbo = RPCSystemKey.String("apache_dubbo") - // Connect RPC - RPCSystemConnectRPC = RPCSystemKey.String("connect_rpc") -) - -// RPCService returns an attribute KeyValue conforming to the "rpc.service" -// semantic conventions. It represents the full (logical) name of the service -// being called, including its package name, if applicable. -func RPCService(val string) attribute.KeyValue { - return RPCServiceKey.String(val) -} - -// RPCMethod returns an attribute KeyValue conforming to the "rpc.method" -// semantic conventions. It represents the name of the (logical) method being -// called, must be equal to the $method part in the span name. -func RPCMethod(val string) attribute.KeyValue { - return RPCMethodKey.String(val) -} - -// Tech-specific attributes for gRPC. -const ( - // RPCGRPCStatusCodeKey is the attribute Key conforming to the - // "rpc.grpc.status_code" semantic conventions. It represents the [numeric - // status - // code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of - // the gRPC request. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - RPCGRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") -) - -var ( - // OK - RPCGRPCStatusCodeOk = RPCGRPCStatusCodeKey.Int(0) - // CANCELLED - RPCGRPCStatusCodeCancelled = RPCGRPCStatusCodeKey.Int(1) - // UNKNOWN - RPCGRPCStatusCodeUnknown = RPCGRPCStatusCodeKey.Int(2) - // INVALID_ARGUMENT - RPCGRPCStatusCodeInvalidArgument = RPCGRPCStatusCodeKey.Int(3) - // DEADLINE_EXCEEDED - RPCGRPCStatusCodeDeadlineExceeded = RPCGRPCStatusCodeKey.Int(4) - // NOT_FOUND - RPCGRPCStatusCodeNotFound = RPCGRPCStatusCodeKey.Int(5) - // ALREADY_EXISTS - RPCGRPCStatusCodeAlreadyExists = RPCGRPCStatusCodeKey.Int(6) - // PERMISSION_DENIED - RPCGRPCStatusCodePermissionDenied = RPCGRPCStatusCodeKey.Int(7) - // RESOURCE_EXHAUSTED - RPCGRPCStatusCodeResourceExhausted = RPCGRPCStatusCodeKey.Int(8) - // FAILED_PRECONDITION - RPCGRPCStatusCodeFailedPrecondition = RPCGRPCStatusCodeKey.Int(9) - // ABORTED - RPCGRPCStatusCodeAborted = RPCGRPCStatusCodeKey.Int(10) - // OUT_OF_RANGE - RPCGRPCStatusCodeOutOfRange = RPCGRPCStatusCodeKey.Int(11) - // UNIMPLEMENTED - RPCGRPCStatusCodeUnimplemented = RPCGRPCStatusCodeKey.Int(12) - // INTERNAL - RPCGRPCStatusCodeInternal = RPCGRPCStatusCodeKey.Int(13) - // UNAVAILABLE - RPCGRPCStatusCodeUnavailable = RPCGRPCStatusCodeKey.Int(14) - // DATA_LOSS - RPCGRPCStatusCodeDataLoss = RPCGRPCStatusCodeKey.Int(15) - // UNAUTHENTICATED - RPCGRPCStatusCodeUnauthenticated = RPCGRPCStatusCodeKey.Int(16) -) - -// Tech-specific attributes for [JSON RPC](https://www.jsonrpc.org/). -const ( - // RPCJsonrpcVersionKey is the attribute Key conforming to the - // "rpc.jsonrpc.version" semantic conventions. It represents the protocol - // version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 - // does not specify this, the value can be omitted. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If other than the default - // version (`1.0`)) - // Stability: stable - // Examples: '2.0', '1.0' - RPCJsonrpcVersionKey = attribute.Key("rpc.jsonrpc.version") - - // RPCJsonrpcRequestIDKey is the attribute Key conforming to the - // "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` - // property of request or response. Since protocol allows id to be int, - // string, `null` or missing (for notifications), value is expected to be - // cast to string for simplicity. Use empty string in case of `null` value. - // Omit entirely if this is a notification. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10', 'request-7', '' - RPCJsonrpcRequestIDKey = attribute.Key("rpc.jsonrpc.request_id") - - // RPCJsonrpcErrorCodeKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_code" semantic conventions. It represents the - // `error.code` property of response if it is an error response. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If response is not successful.) - // Stability: stable - // Examples: -32700, 100 - RPCJsonrpcErrorCodeKey = attribute.Key("rpc.jsonrpc.error_code") - - // RPCJsonrpcErrorMessageKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_message" semantic conventions. It represents the - // `error.message` property of response if it is an error response. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Parse error', 'User already exists' - RPCJsonrpcErrorMessageKey = attribute.Key("rpc.jsonrpc.error_message") -) - -// RPCJsonrpcVersion returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.version" semantic conventions. It represents the protocol -// version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 -// does not specify this, the value can be omitted. -func RPCJsonrpcVersion(val string) attribute.KeyValue { - return RPCJsonrpcVersionKey.String(val) -} - -// RPCJsonrpcRequestID returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` -// property of request or response. Since protocol allows id to be int, string, -// `null` or missing (for notifications), value is expected to be cast to -// string for simplicity. Use empty string in case of `null` value. Omit -// entirely if this is a notification. -func RPCJsonrpcRequestID(val string) attribute.KeyValue { - return RPCJsonrpcRequestIDKey.String(val) -} - -// RPCJsonrpcErrorCode returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_code" semantic conventions. It represents the -// `error.code` property of response if it is an error response. -func RPCJsonrpcErrorCode(val int) attribute.KeyValue { - return RPCJsonrpcErrorCodeKey.Int(val) -} - -// RPCJsonrpcErrorMessage returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_message" semantic conventions. It represents the -// `error.message` property of response if it is an error response. -func RPCJsonrpcErrorMessage(val string) attribute.KeyValue { - return RPCJsonrpcErrorMessageKey.String(val) -} - -// Tech-specific attributes for Connect RPC. -const ( - // RPCConnectRPCErrorCodeKey is the attribute Key conforming to the - // "rpc.connect_rpc.error_code" semantic conventions. It represents the - // [error codes](https://connect.build/docs/protocol/#error-codes) of the - // Connect request. Error codes are always string values. - // - // Type: Enum - // RequirementLevel: ConditionallyRequired (If response is not successful - // and if error code available.) - // Stability: stable - RPCConnectRPCErrorCodeKey = attribute.Key("rpc.connect_rpc.error_code") -) - -var ( - // cancelled - RPCConnectRPCErrorCodeCancelled = RPCConnectRPCErrorCodeKey.String("cancelled") - // unknown - RPCConnectRPCErrorCodeUnknown = RPCConnectRPCErrorCodeKey.String("unknown") - // invalid_argument - RPCConnectRPCErrorCodeInvalidArgument = RPCConnectRPCErrorCodeKey.String("invalid_argument") - // deadline_exceeded - RPCConnectRPCErrorCodeDeadlineExceeded = RPCConnectRPCErrorCodeKey.String("deadline_exceeded") - // not_found - RPCConnectRPCErrorCodeNotFound = RPCConnectRPCErrorCodeKey.String("not_found") - // already_exists - RPCConnectRPCErrorCodeAlreadyExists = RPCConnectRPCErrorCodeKey.String("already_exists") - // permission_denied - RPCConnectRPCErrorCodePermissionDenied = RPCConnectRPCErrorCodeKey.String("permission_denied") - // resource_exhausted - RPCConnectRPCErrorCodeResourceExhausted = RPCConnectRPCErrorCodeKey.String("resource_exhausted") - // failed_precondition - RPCConnectRPCErrorCodeFailedPrecondition = RPCConnectRPCErrorCodeKey.String("failed_precondition") - // aborted - RPCConnectRPCErrorCodeAborted = RPCConnectRPCErrorCodeKey.String("aborted") - // out_of_range - RPCConnectRPCErrorCodeOutOfRange = RPCConnectRPCErrorCodeKey.String("out_of_range") - // unimplemented - RPCConnectRPCErrorCodeUnimplemented = RPCConnectRPCErrorCodeKey.String("unimplemented") - // internal - RPCConnectRPCErrorCodeInternal = RPCConnectRPCErrorCodeKey.String("internal") - // unavailable - RPCConnectRPCErrorCodeUnavailable = RPCConnectRPCErrorCodeKey.String("unavailable") - // data_loss - RPCConnectRPCErrorCodeDataLoss = RPCConnectRPCErrorCodeKey.String("data_loss") - // unauthenticated - RPCConnectRPCErrorCodeUnauthenticated = RPCConnectRPCErrorCodeKey.String("unauthenticated") -) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/README.md b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/README.md deleted file mode 100644 index 2de1fc3c6..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Semconv v1.26.0 - -[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/semconv/v1.26.0)](https://pkg.go.dev/go.opentelemetry.io/otel/semconv/v1.26.0) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/attribute_group.go b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/attribute_group.go deleted file mode 100644 index d8dc822b2..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/attribute_group.go +++ /dev/null @@ -1,8996 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.26.0" - -import "go.opentelemetry.io/otel/attribute" - -// The Android platform on which the Android application is running. -const ( - // AndroidOSAPILevelKey is the attribute Key conforming to the - // "android.os.api_level" semantic conventions. It represents the uniquely - // identifies the framework API revision offered by a version - // (`os.version`) of the android operating system. More information can be - // found - // [here](https://developer.android.com/guide/topics/manifest/uses-sdk-element#APILevels). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '33', '32' - AndroidOSAPILevelKey = attribute.Key("android.os.api_level") -) - -// AndroidOSAPILevel returns an attribute KeyValue conforming to the -// "android.os.api_level" semantic conventions. It represents the uniquely -// identifies the framework API revision offered by a version (`os.version`) of -// the android operating system. More information can be found -// [here](https://developer.android.com/guide/topics/manifest/uses-sdk-element#APILevels). -func AndroidOSAPILevel(val string) attribute.KeyValue { - return AndroidOSAPILevelKey.String(val) -} - -// ASP.NET Core attributes -const ( - // AspnetcoreRateLimitingResultKey is the attribute Key conforming to the - // "aspnetcore.rate_limiting.result" semantic conventions. It represents - // the rate-limiting result, shows whether the lease was acquired or - // contains a rejection reason - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Examples: 'acquired', 'request_canceled' - AspnetcoreRateLimitingResultKey = attribute.Key("aspnetcore.rate_limiting.result") - - // AspnetcoreDiagnosticsHandlerTypeKey is the attribute Key conforming to - // the "aspnetcore.diagnostics.handler.type" semantic conventions. It - // represents the full type name of the - // [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) - // implementation that handled the exception. - // - // Type: string - // RequirementLevel: ConditionallyRequired (if and only if the exception - // was handled by this handler.) - // Stability: stable - // Examples: 'Contoso.MyHandler' - AspnetcoreDiagnosticsHandlerTypeKey = attribute.Key("aspnetcore.diagnostics.handler.type") - - // AspnetcoreDiagnosticsExceptionResultKey is the attribute Key conforming - // to the "aspnetcore.diagnostics.exception.result" semantic conventions. - // It represents the aSP.NET Core exception middleware handling result - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'handled', 'unhandled' - AspnetcoreDiagnosticsExceptionResultKey = attribute.Key("aspnetcore.diagnostics.exception.result") - - // AspnetcoreRateLimitingPolicyKey is the attribute Key conforming to the - // "aspnetcore.rate_limiting.policy" semantic conventions. It represents - // the rate limiting policy name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'fixed', 'sliding', 'token' - AspnetcoreRateLimitingPolicyKey = attribute.Key("aspnetcore.rate_limiting.policy") - - // AspnetcoreRequestIsUnhandledKey is the attribute Key conforming to the - // "aspnetcore.request.is_unhandled" semantic conventions. It represents - // the flag indicating if request was handled by the application pipeline. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Examples: True - AspnetcoreRequestIsUnhandledKey = attribute.Key("aspnetcore.request.is_unhandled") - - // AspnetcoreRoutingIsFallbackKey is the attribute Key conforming to the - // "aspnetcore.routing.is_fallback" semantic conventions. It represents a - // value that indicates whether the matched route is a fallback route. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Examples: True - AspnetcoreRoutingIsFallbackKey = attribute.Key("aspnetcore.routing.is_fallback") - - // AspnetcoreRoutingMatchStatusKey is the attribute Key conforming to the - // "aspnetcore.routing.match_status" semantic conventions. It represents - // the match result - success or failure - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'success', 'failure' - AspnetcoreRoutingMatchStatusKey = attribute.Key("aspnetcore.routing.match_status") -) - -var ( - // Lease was acquired - AspnetcoreRateLimitingResultAcquired = AspnetcoreRateLimitingResultKey.String("acquired") - // Lease request was rejected by the endpoint limiter - AspnetcoreRateLimitingResultEndpointLimiter = AspnetcoreRateLimitingResultKey.String("endpoint_limiter") - // Lease request was rejected by the global limiter - AspnetcoreRateLimitingResultGlobalLimiter = AspnetcoreRateLimitingResultKey.String("global_limiter") - // Lease request was canceled - AspnetcoreRateLimitingResultRequestCanceled = AspnetcoreRateLimitingResultKey.String("request_canceled") -) - -var ( - // Exception was handled by the exception handling middleware - AspnetcoreDiagnosticsExceptionResultHandled = AspnetcoreDiagnosticsExceptionResultKey.String("handled") - // Exception was not handled by the exception handling middleware - AspnetcoreDiagnosticsExceptionResultUnhandled = AspnetcoreDiagnosticsExceptionResultKey.String("unhandled") - // Exception handling was skipped because the response had started - AspnetcoreDiagnosticsExceptionResultSkipped = AspnetcoreDiagnosticsExceptionResultKey.String("skipped") - // Exception handling didn't run because the request was aborted - AspnetcoreDiagnosticsExceptionResultAborted = AspnetcoreDiagnosticsExceptionResultKey.String("aborted") -) - -var ( - // Match succeeded - AspnetcoreRoutingMatchStatusSuccess = AspnetcoreRoutingMatchStatusKey.String("success") - // Match failed - AspnetcoreRoutingMatchStatusFailure = AspnetcoreRoutingMatchStatusKey.String("failure") -) - -// AspnetcoreDiagnosticsHandlerType returns an attribute KeyValue conforming -// to the "aspnetcore.diagnostics.handler.type" semantic conventions. It -// represents the full type name of the -// [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) -// implementation that handled the exception. -func AspnetcoreDiagnosticsHandlerType(val string) attribute.KeyValue { - return AspnetcoreDiagnosticsHandlerTypeKey.String(val) -} - -// AspnetcoreRateLimitingPolicy returns an attribute KeyValue conforming to -// the "aspnetcore.rate_limiting.policy" semantic conventions. It represents -// the rate limiting policy name. -func AspnetcoreRateLimitingPolicy(val string) attribute.KeyValue { - return AspnetcoreRateLimitingPolicyKey.String(val) -} - -// AspnetcoreRequestIsUnhandled returns an attribute KeyValue conforming to -// the "aspnetcore.request.is_unhandled" semantic conventions. It represents -// the flag indicating if request was handled by the application pipeline. -func AspnetcoreRequestIsUnhandled(val bool) attribute.KeyValue { - return AspnetcoreRequestIsUnhandledKey.Bool(val) -} - -// AspnetcoreRoutingIsFallback returns an attribute KeyValue conforming to -// the "aspnetcore.routing.is_fallback" semantic conventions. It represents a -// value that indicates whether the matched route is a fallback route. -func AspnetcoreRoutingIsFallback(val bool) attribute.KeyValue { - return AspnetcoreRoutingIsFallbackKey.Bool(val) -} - -// Generic attributes for AWS services. -const ( - // AWSRequestIDKey is the attribute Key conforming to the "aws.request_id" - // semantic conventions. It represents the AWS request ID as returned in - // the response headers `x-amz-request-id` or `x-amz-requestid`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '79b9da39-b7ae-508a-a6bc-864b2829c622', 'C9ER4AJX75574TDJ' - AWSRequestIDKey = attribute.Key("aws.request_id") -) - -// AWSRequestID returns an attribute KeyValue conforming to the -// "aws.request_id" semantic conventions. It represents the AWS request ID as -// returned in the response headers `x-amz-request-id` or `x-amz-requestid`. -func AWSRequestID(val string) attribute.KeyValue { - return AWSRequestIDKey.String(val) -} - -// Attributes for AWS DynamoDB. -const ( - // AWSDynamoDBAttributeDefinitionsKey is the attribute Key conforming to - // the "aws.dynamodb.attribute_definitions" semantic conventions. It - // represents the JSON-serialized value of each item in the - // `AttributeDefinitions` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "AttributeName": "string", "AttributeType": "string" }' - AWSDynamoDBAttributeDefinitionsKey = attribute.Key("aws.dynamodb.attribute_definitions") - - // AWSDynamoDBAttributesToGetKey is the attribute Key conforming to the - // "aws.dynamodb.attributes_to_get" semantic conventions. It represents the - // value of the `AttributesToGet` request parameter. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'lives', 'id' - AWSDynamoDBAttributesToGetKey = attribute.Key("aws.dynamodb.attributes_to_get") - - // AWSDynamoDBConsistentReadKey is the attribute Key conforming to the - // "aws.dynamodb.consistent_read" semantic conventions. It represents the - // value of the `ConsistentRead` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - AWSDynamoDBConsistentReadKey = attribute.Key("aws.dynamodb.consistent_read") - - // AWSDynamoDBConsumedCapacityKey is the attribute Key conforming to the - // "aws.dynamodb.consumed_capacity" semantic conventions. It represents the - // JSON-serialized value of each item in the `ConsumedCapacity` response - // field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "CapacityUnits": number, "GlobalSecondaryIndexes": { - // "string" : { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "LocalSecondaryIndexes": { "string" : - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "ReadCapacityUnits": number, "Table": - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number }, "TableName": "string", - // "WriteCapacityUnits": number }' - AWSDynamoDBConsumedCapacityKey = attribute.Key("aws.dynamodb.consumed_capacity") - - // AWSDynamoDBCountKey is the attribute Key conforming to the - // "aws.dynamodb.count" semantic conventions. It represents the value of - // the `Count` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBCountKey = attribute.Key("aws.dynamodb.count") - - // AWSDynamoDBExclusiveStartTableKey is the attribute Key conforming to the - // "aws.dynamodb.exclusive_start_table" semantic conventions. It represents - // the value of the `ExclusiveStartTableName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Users', 'CatsTable' - AWSDynamoDBExclusiveStartTableKey = attribute.Key("aws.dynamodb.exclusive_start_table") - - // AWSDynamoDBGlobalSecondaryIndexUpdatesKey is the attribute Key - // conforming to the "aws.dynamodb.global_secondary_index_updates" semantic - // conventions. It represents the JSON-serialized value of each item in the - // `GlobalSecondaryIndexUpdates` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "Create": { "IndexName": "string", "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" }, - // "ProvisionedThroughput": { "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexUpdatesKey = attribute.Key("aws.dynamodb.global_secondary_index_updates") - - // AWSDynamoDBGlobalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.global_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `GlobalSecondaryIndexes` request field - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "IndexName": "string", "KeySchema": [ { "AttributeName": - // "string", "KeyType": "string" } ], "Projection": { "NonKeyAttributes": [ - // "string" ], "ProjectionType": "string" }, "ProvisionedThroughput": { - // "ReadCapacityUnits": number, "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexesKey = attribute.Key("aws.dynamodb.global_secondary_indexes") - - // AWSDynamoDBIndexNameKey is the attribute Key conforming to the - // "aws.dynamodb.index_name" semantic conventions. It represents the value - // of the `IndexName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'name_to_group' - AWSDynamoDBIndexNameKey = attribute.Key("aws.dynamodb.index_name") - - // AWSDynamoDBItemCollectionMetricsKey is the attribute Key conforming to - // the "aws.dynamodb.item_collection_metrics" semantic conventions. It - // represents the JSON-serialized value of the `ItemCollectionMetrics` - // response field. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "string" : [ { "ItemCollectionKey": { "string" : { "B": - // blob, "BOOL": boolean, "BS": [ blob ], "L": [ "AttributeValue" ], "M": { - // "string" : "AttributeValue" }, "N": "string", "NS": [ "string" ], - // "NULL": boolean, "S": "string", "SS": [ "string" ] } }, - // "SizeEstimateRangeGB": [ number ] } ] }' - AWSDynamoDBItemCollectionMetricsKey = attribute.Key("aws.dynamodb.item_collection_metrics") - - // AWSDynamoDBLimitKey is the attribute Key conforming to the - // "aws.dynamodb.limit" semantic conventions. It represents the value of - // the `Limit` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBLimitKey = attribute.Key("aws.dynamodb.limit") - - // AWSDynamoDBLocalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.local_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `LocalSecondaryIndexes` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "IndexARN": "string", "IndexName": "string", - // "IndexSizeBytes": number, "ItemCount": number, "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" } }' - AWSDynamoDBLocalSecondaryIndexesKey = attribute.Key("aws.dynamodb.local_secondary_indexes") - - // AWSDynamoDBProjectionKey is the attribute Key conforming to the - // "aws.dynamodb.projection" semantic conventions. It represents the value - // of the `ProjectionExpression` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Title', 'Title, Price, Color', 'Title, Description, - // RelatedItems, ProductReviews' - AWSDynamoDBProjectionKey = attribute.Key("aws.dynamodb.projection") - - // AWSDynamoDBProvisionedReadCapacityKey is the attribute Key conforming to - // the "aws.dynamodb.provisioned_read_capacity" semantic conventions. It - // represents the value of the `ProvisionedThroughput.ReadCapacityUnits` - // request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedReadCapacityKey = attribute.Key("aws.dynamodb.provisioned_read_capacity") - - // AWSDynamoDBProvisionedWriteCapacityKey is the attribute Key conforming - // to the "aws.dynamodb.provisioned_write_capacity" semantic conventions. - // It represents the value of the - // `ProvisionedThroughput.WriteCapacityUnits` request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedWriteCapacityKey = attribute.Key("aws.dynamodb.provisioned_write_capacity") - - // AWSDynamoDBScanForwardKey is the attribute Key conforming to the - // "aws.dynamodb.scan_forward" semantic conventions. It represents the - // value of the `ScanIndexForward` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - AWSDynamoDBScanForwardKey = attribute.Key("aws.dynamodb.scan_forward") - - // AWSDynamoDBScannedCountKey is the attribute Key conforming to the - // "aws.dynamodb.scanned_count" semantic conventions. It represents the - // value of the `ScannedCount` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 50 - AWSDynamoDBScannedCountKey = attribute.Key("aws.dynamodb.scanned_count") - - // AWSDynamoDBSegmentKey is the attribute Key conforming to the - // "aws.dynamodb.segment" semantic conventions. It represents the value of - // the `Segment` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBSegmentKey = attribute.Key("aws.dynamodb.segment") - - // AWSDynamoDBSelectKey is the attribute Key conforming to the - // "aws.dynamodb.select" semantic conventions. It represents the value of - // the `Select` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ALL_ATTRIBUTES', 'COUNT' - AWSDynamoDBSelectKey = attribute.Key("aws.dynamodb.select") - - // AWSDynamoDBTableCountKey is the attribute Key conforming to the - // "aws.dynamodb.table_count" semantic conventions. It represents the - // number of items in the `TableNames` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 20 - AWSDynamoDBTableCountKey = attribute.Key("aws.dynamodb.table_count") - - // AWSDynamoDBTableNamesKey is the attribute Key conforming to the - // "aws.dynamodb.table_names" semantic conventions. It represents the keys - // in the `RequestItems` object field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Users', 'Cats' - AWSDynamoDBTableNamesKey = attribute.Key("aws.dynamodb.table_names") - - // AWSDynamoDBTotalSegmentsKey is the attribute Key conforming to the - // "aws.dynamodb.total_segments" semantic conventions. It represents the - // value of the `TotalSegments` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 100 - AWSDynamoDBTotalSegmentsKey = attribute.Key("aws.dynamodb.total_segments") -) - -// AWSDynamoDBAttributeDefinitions returns an attribute KeyValue conforming -// to the "aws.dynamodb.attribute_definitions" semantic conventions. It -// represents the JSON-serialized value of each item in the -// `AttributeDefinitions` request field. -func AWSDynamoDBAttributeDefinitions(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributeDefinitionsKey.StringSlice(val) -} - -// AWSDynamoDBAttributesToGet returns an attribute KeyValue conforming to -// the "aws.dynamodb.attributes_to_get" semantic conventions. It represents the -// value of the `AttributesToGet` request parameter. -func AWSDynamoDBAttributesToGet(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributesToGetKey.StringSlice(val) -} - -// AWSDynamoDBConsistentRead returns an attribute KeyValue conforming to the -// "aws.dynamodb.consistent_read" semantic conventions. It represents the value -// of the `ConsistentRead` request parameter. -func AWSDynamoDBConsistentRead(val bool) attribute.KeyValue { - return AWSDynamoDBConsistentReadKey.Bool(val) -} - -// AWSDynamoDBConsumedCapacity returns an attribute KeyValue conforming to -// the "aws.dynamodb.consumed_capacity" semantic conventions. It represents the -// JSON-serialized value of each item in the `ConsumedCapacity` response field. -func AWSDynamoDBConsumedCapacity(val ...string) attribute.KeyValue { - return AWSDynamoDBConsumedCapacityKey.StringSlice(val) -} - -// AWSDynamoDBCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.count" semantic conventions. It represents the value of the -// `Count` response parameter. -func AWSDynamoDBCount(val int) attribute.KeyValue { - return AWSDynamoDBCountKey.Int(val) -} - -// AWSDynamoDBExclusiveStartTable returns an attribute KeyValue conforming -// to the "aws.dynamodb.exclusive_start_table" semantic conventions. It -// represents the value of the `ExclusiveStartTableName` request parameter. -func AWSDynamoDBExclusiveStartTable(val string) attribute.KeyValue { - return AWSDynamoDBExclusiveStartTableKey.String(val) -} - -// AWSDynamoDBGlobalSecondaryIndexUpdates returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_index_updates" semantic -// conventions. It represents the JSON-serialized value of each item in the -// `GlobalSecondaryIndexUpdates` request field. -func AWSDynamoDBGlobalSecondaryIndexUpdates(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexUpdatesKey.StringSlice(val) -} - -// AWSDynamoDBGlobalSecondaryIndexes returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_indexes" semantic -// conventions. It represents the JSON-serialized value of each item of the -// `GlobalSecondaryIndexes` request field -func AWSDynamoDBGlobalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexesKey.StringSlice(val) -} - -// AWSDynamoDBIndexName returns an attribute KeyValue conforming to the -// "aws.dynamodb.index_name" semantic conventions. It represents the value of -// the `IndexName` request parameter. -func AWSDynamoDBIndexName(val string) attribute.KeyValue { - return AWSDynamoDBIndexNameKey.String(val) -} - -// AWSDynamoDBItemCollectionMetrics returns an attribute KeyValue conforming -// to the "aws.dynamodb.item_collection_metrics" semantic conventions. It -// represents the JSON-serialized value of the `ItemCollectionMetrics` response -// field. -func AWSDynamoDBItemCollectionMetrics(val string) attribute.KeyValue { - return AWSDynamoDBItemCollectionMetricsKey.String(val) -} - -// AWSDynamoDBLimit returns an attribute KeyValue conforming to the -// "aws.dynamodb.limit" semantic conventions. It represents the value of the -// `Limit` request parameter. -func AWSDynamoDBLimit(val int) attribute.KeyValue { - return AWSDynamoDBLimitKey.Int(val) -} - -// AWSDynamoDBLocalSecondaryIndexes returns an attribute KeyValue conforming -// to the "aws.dynamodb.local_secondary_indexes" semantic conventions. It -// represents the JSON-serialized value of each item of the -// `LocalSecondaryIndexes` request field. -func AWSDynamoDBLocalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBLocalSecondaryIndexesKey.StringSlice(val) -} - -// AWSDynamoDBProjection returns an attribute KeyValue conforming to the -// "aws.dynamodb.projection" semantic conventions. It represents the value of -// the `ProjectionExpression` request parameter. -func AWSDynamoDBProjection(val string) attribute.KeyValue { - return AWSDynamoDBProjectionKey.String(val) -} - -// AWSDynamoDBProvisionedReadCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_read_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.ReadCapacityUnits` request parameter. -func AWSDynamoDBProvisionedReadCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedReadCapacityKey.Float64(val) -} - -// AWSDynamoDBProvisionedWriteCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_write_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.WriteCapacityUnits` request parameter. -func AWSDynamoDBProvisionedWriteCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedWriteCapacityKey.Float64(val) -} - -// AWSDynamoDBScanForward returns an attribute KeyValue conforming to the -// "aws.dynamodb.scan_forward" semantic conventions. It represents the value of -// the `ScanIndexForward` request parameter. -func AWSDynamoDBScanForward(val bool) attribute.KeyValue { - return AWSDynamoDBScanForwardKey.Bool(val) -} - -// AWSDynamoDBScannedCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.scanned_count" semantic conventions. It represents the value -// of the `ScannedCount` response parameter. -func AWSDynamoDBScannedCount(val int) attribute.KeyValue { - return AWSDynamoDBScannedCountKey.Int(val) -} - -// AWSDynamoDBSegment returns an attribute KeyValue conforming to the -// "aws.dynamodb.segment" semantic conventions. It represents the value of the -// `Segment` request parameter. -func AWSDynamoDBSegment(val int) attribute.KeyValue { - return AWSDynamoDBSegmentKey.Int(val) -} - -// AWSDynamoDBSelect returns an attribute KeyValue conforming to the -// "aws.dynamodb.select" semantic conventions. It represents the value of the -// `Select` request parameter. -func AWSDynamoDBSelect(val string) attribute.KeyValue { - return AWSDynamoDBSelectKey.String(val) -} - -// AWSDynamoDBTableCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_count" semantic conventions. It represents the number of -// items in the `TableNames` response parameter. -func AWSDynamoDBTableCount(val int) attribute.KeyValue { - return AWSDynamoDBTableCountKey.Int(val) -} - -// AWSDynamoDBTableNames returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_names" semantic conventions. It represents the keys in -// the `RequestItems` object field. -func AWSDynamoDBTableNames(val ...string) attribute.KeyValue { - return AWSDynamoDBTableNamesKey.StringSlice(val) -} - -// AWSDynamoDBTotalSegments returns an attribute KeyValue conforming to the -// "aws.dynamodb.total_segments" semantic conventions. It represents the value -// of the `TotalSegments` request parameter. -func AWSDynamoDBTotalSegments(val int) attribute.KeyValue { - return AWSDynamoDBTotalSegmentsKey.Int(val) -} - -// Attributes for AWS Elastic Container Service (ECS). -const ( - // AWSECSTaskIDKey is the attribute Key conforming to the "aws.ecs.task.id" - // semantic conventions. It represents the ID of a running ECS task. The ID - // MUST be extracted from `task.arn`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If and only if `task.arn` is - // populated.) - // Stability: experimental - // Examples: '10838bed-421f-43ef-870a-f43feacbbb5b', - // '23ebb8ac-c18f-46c6-8bbe-d55d0e37cfbd' - AWSECSTaskIDKey = attribute.Key("aws.ecs.task.id") - - // AWSECSClusterARNKey is the attribute Key conforming to the - // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an - // [ECS - // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSECSClusterARNKey = attribute.Key("aws.ecs.cluster.arn") - - // AWSECSContainerARNKey is the attribute Key conforming to the - // "aws.ecs.container.arn" semantic conventions. It represents the Amazon - // Resource Name (ARN) of an [ECS container - // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:container/32624152-9086-4f0e-acae-1a75b14fe4d9' - AWSECSContainerARNKey = attribute.Key("aws.ecs.container.arn") - - // AWSECSLaunchtypeKey is the attribute Key conforming to the - // "aws.ecs.launchtype" semantic conventions. It represents the [launch - // type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) - // for an ECS task. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - AWSECSLaunchtypeKey = attribute.Key("aws.ecs.launchtype") - - // AWSECSTaskARNKey is the attribute Key conforming to the - // "aws.ecs.task.arn" semantic conventions. It represents the ARN of a - // running [ECS - // task](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:task/10838bed-421f-43ef-870a-f43feacbbb5b', - // 'arn:aws:ecs:us-west-1:123456789123:task/my-cluster/task-id/23ebb8ac-c18f-46c6-8bbe-d55d0e37cfbd' - AWSECSTaskARNKey = attribute.Key("aws.ecs.task.arn") - - // AWSECSTaskFamilyKey is the attribute Key conforming to the - // "aws.ecs.task.family" semantic conventions. It represents the family - // name of the [ECS task - // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html) - // used to create the ECS task. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-family' - AWSECSTaskFamilyKey = attribute.Key("aws.ecs.task.family") - - // AWSECSTaskRevisionKey is the attribute Key conforming to the - // "aws.ecs.task.revision" semantic conventions. It represents the revision - // for the task definition used to create the ECS task. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '8', '26' - AWSECSTaskRevisionKey = attribute.Key("aws.ecs.task.revision") -) - -var ( - // ec2 - AWSECSLaunchtypeEC2 = AWSECSLaunchtypeKey.String("ec2") - // fargate - AWSECSLaunchtypeFargate = AWSECSLaunchtypeKey.String("fargate") -) - -// AWSECSTaskID returns an attribute KeyValue conforming to the -// "aws.ecs.task.id" semantic conventions. It represents the ID of a running -// ECS task. The ID MUST be extracted from `task.arn`. -func AWSECSTaskID(val string) attribute.KeyValue { - return AWSECSTaskIDKey.String(val) -} - -// AWSECSClusterARN returns an attribute KeyValue conforming to the -// "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an [ECS -// cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). -func AWSECSClusterARN(val string) attribute.KeyValue { - return AWSECSClusterARNKey.String(val) -} - -// AWSECSContainerARN returns an attribute KeyValue conforming to the -// "aws.ecs.container.arn" semantic conventions. It represents the Amazon -// Resource Name (ARN) of an [ECS container -// instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). -func AWSECSContainerARN(val string) attribute.KeyValue { - return AWSECSContainerARNKey.String(val) -} - -// AWSECSTaskARN returns an attribute KeyValue conforming to the -// "aws.ecs.task.arn" semantic conventions. It represents the ARN of a running -// [ECS -// task](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids). -func AWSECSTaskARN(val string) attribute.KeyValue { - return AWSECSTaskARNKey.String(val) -} - -// AWSECSTaskFamily returns an attribute KeyValue conforming to the -// "aws.ecs.task.family" semantic conventions. It represents the family name of -// the [ECS task -// definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html) -// used to create the ECS task. -func AWSECSTaskFamily(val string) attribute.KeyValue { - return AWSECSTaskFamilyKey.String(val) -} - -// AWSECSTaskRevision returns an attribute KeyValue conforming to the -// "aws.ecs.task.revision" semantic conventions. It represents the revision for -// the task definition used to create the ECS task. -func AWSECSTaskRevision(val string) attribute.KeyValue { - return AWSECSTaskRevisionKey.String(val) -} - -// Attributes for AWS Elastic Kubernetes Service (EKS). -const ( - // AWSEKSClusterARNKey is the attribute Key conforming to the - // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an - // EKS cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSEKSClusterARNKey = attribute.Key("aws.eks.cluster.arn") -) - -// AWSEKSClusterARN returns an attribute KeyValue conforming to the -// "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an EKS -// cluster. -func AWSEKSClusterARN(val string) attribute.KeyValue { - return AWSEKSClusterARNKey.String(val) -} - -// Attributes for AWS Logs. -const ( - // AWSLogGroupARNsKey is the attribute Key conforming to the - // "aws.log.group.arns" semantic conventions. It represents the Amazon - // Resource Name(s) (ARN) of the AWS log group(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:*' - // Note: See the [log group ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - AWSLogGroupARNsKey = attribute.Key("aws.log.group.arns") - - // AWSLogGroupNamesKey is the attribute Key conforming to the - // "aws.log.group.names" semantic conventions. It represents the name(s) of - // the AWS log group(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/aws/lambda/my-function', 'opentelemetry-service' - // Note: Multiple log groups must be supported for cases like - // multi-container applications, where a single application has sidecar - // containers, and each write to their own log group. - AWSLogGroupNamesKey = attribute.Key("aws.log.group.names") - - // AWSLogStreamARNsKey is the attribute Key conforming to the - // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of - // the AWS log stream(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:log-stream:logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - // Note: See the [log stream ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - // One log group can contain several log streams, so these ARNs necessarily - // identify both a log group and a log stream. - AWSLogStreamARNsKey = attribute.Key("aws.log.stream.arns") - - // AWSLogStreamNamesKey is the attribute Key conforming to the - // "aws.log.stream.names" semantic conventions. It represents the name(s) - // of the AWS log stream(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSLogStreamNamesKey = attribute.Key("aws.log.stream.names") -) - -// AWSLogGroupARNs returns an attribute KeyValue conforming to the -// "aws.log.group.arns" semantic conventions. It represents the Amazon Resource -// Name(s) (ARN) of the AWS log group(s). -func AWSLogGroupARNs(val ...string) attribute.KeyValue { - return AWSLogGroupARNsKey.StringSlice(val) -} - -// AWSLogGroupNames returns an attribute KeyValue conforming to the -// "aws.log.group.names" semantic conventions. It represents the name(s) of the -// AWS log group(s) an application is writing to. -func AWSLogGroupNames(val ...string) attribute.KeyValue { - return AWSLogGroupNamesKey.StringSlice(val) -} - -// AWSLogStreamARNs returns an attribute KeyValue conforming to the -// "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of the -// AWS log stream(s). -func AWSLogStreamARNs(val ...string) attribute.KeyValue { - return AWSLogStreamARNsKey.StringSlice(val) -} - -// AWSLogStreamNames returns an attribute KeyValue conforming to the -// "aws.log.stream.names" semantic conventions. It represents the name(s) of -// the AWS log stream(s) an application is writing to. -func AWSLogStreamNames(val ...string) attribute.KeyValue { - return AWSLogStreamNamesKey.StringSlice(val) -} - -// Attributes for AWS Lambda. -const ( - // AWSLambdaInvokedARNKey is the attribute Key conforming to the - // "aws.lambda.invoked_arn" semantic conventions. It represents the full - // invoked ARN as provided on the `Context` passed to the function - // (`Lambda-Runtime-Invoked-Function-ARN` header on the - // `/runtime/invocation/next` applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' - // Note: This may be different from `cloud.resource_id` if an alias is - // involved. - AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") -) - -// AWSLambdaInvokedARN returns an attribute KeyValue conforming to the -// "aws.lambda.invoked_arn" semantic conventions. It represents the full -// invoked ARN as provided on the `Context` passed to the function -// (`Lambda-Runtime-Invoked-Function-ARN` header on the -// `/runtime/invocation/next` applicable). -func AWSLambdaInvokedARN(val string) attribute.KeyValue { - return AWSLambdaInvokedARNKey.String(val) -} - -// Attributes for AWS S3. -const ( - // AWSS3BucketKey is the attribute Key conforming to the "aws.s3.bucket" - // semantic conventions. It represents the S3 bucket name the request - // refers to. Corresponds to the `--bucket` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'some-bucket-name' - // Note: The `bucket` attribute is applicable to all S3 operations that - // reference a bucket, i.e. that require the bucket name as a mandatory - // parameter. - // This applies to almost all S3 operations except `list-buckets`. - AWSS3BucketKey = attribute.Key("aws.s3.bucket") - - // AWSS3CopySourceKey is the attribute Key conforming to the - // "aws.s3.copy_source" semantic conventions. It represents the source - // object (in the form `bucket`/`key`) for the copy operation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'someFile.yml' - // Note: The `copy_source` attribute applies to S3 copy operations and - // corresponds to the `--copy-source` parameter - // of the [copy-object operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html). - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3CopySourceKey = attribute.Key("aws.s3.copy_source") - - // AWSS3DeleteKey is the attribute Key conforming to the "aws.s3.delete" - // semantic conventions. It represents the delete request container that - // specifies the objects to be deleted. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'Objects=[{Key=string,VersionID=string},{Key=string,VersionID=string}],Quiet=boolean' - // Note: The `delete` attribute is only applicable to the - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // operation. - // The `delete` attribute corresponds to the `--delete` parameter of the - // [delete-objects operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-objects.html). - AWSS3DeleteKey = attribute.Key("aws.s3.delete") - - // AWSS3KeyKey is the attribute Key conforming to the "aws.s3.key" semantic - // conventions. It represents the S3 object key the request refers to. - // Corresponds to the `--key` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'someFile.yml' - // Note: The `key` attribute is applicable to all object-related S3 - // operations, i.e. that require the object key as a mandatory parameter. - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // - - // [get-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html) - // - - // [head-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/head-object.html) - // - - // [put-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html) - // - - // [restore-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/restore-object.html) - // - - // [select-object-content](https://docs.aws.amazon.com/cli/latest/reference/s3api/select-object-content.html) - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [create-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/create-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3KeyKey = attribute.Key("aws.s3.key") - - // AWSS3PartNumberKey is the attribute Key conforming to the - // "aws.s3.part_number" semantic conventions. It represents the part number - // of the part being uploaded in a multipart-upload operation. This is a - // positive integer between 1 and 10,000. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3456 - // Note: The `part_number` attribute is only applicable to the - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // and - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - // operations. - // The `part_number` attribute corresponds to the `--part-number` parameter - // of the - // [upload-part operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html). - AWSS3PartNumberKey = attribute.Key("aws.s3.part_number") - - // AWSS3UploadIDKey is the attribute Key conforming to the - // "aws.s3.upload_id" semantic conventions. It represents the upload ID - // that identifies the multipart upload. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'dfRtDYWFbkRONycy.Yxwh66Yjlx.cph0gtNBtJ' - // Note: The `upload_id` attribute applies to S3 multipart-upload - // operations and corresponds to the `--upload-id` parameter - // of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // multipart operations. - // This applies in particular to the following operations: - // - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3UploadIDKey = attribute.Key("aws.s3.upload_id") -) - -// AWSS3Bucket returns an attribute KeyValue conforming to the -// "aws.s3.bucket" semantic conventions. It represents the S3 bucket name the -// request refers to. Corresponds to the `--bucket` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Bucket(val string) attribute.KeyValue { - return AWSS3BucketKey.String(val) -} - -// AWSS3CopySource returns an attribute KeyValue conforming to the -// "aws.s3.copy_source" semantic conventions. It represents the source object -// (in the form `bucket`/`key`) for the copy operation. -func AWSS3CopySource(val string) attribute.KeyValue { - return AWSS3CopySourceKey.String(val) -} - -// AWSS3Delete returns an attribute KeyValue conforming to the -// "aws.s3.delete" semantic conventions. It represents the delete request -// container that specifies the objects to be deleted. -func AWSS3Delete(val string) attribute.KeyValue { - return AWSS3DeleteKey.String(val) -} - -// AWSS3Key returns an attribute KeyValue conforming to the "aws.s3.key" -// semantic conventions. It represents the S3 object key the request refers to. -// Corresponds to the `--key` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Key(val string) attribute.KeyValue { - return AWSS3KeyKey.String(val) -} - -// AWSS3PartNumber returns an attribute KeyValue conforming to the -// "aws.s3.part_number" semantic conventions. It represents the part number of -// the part being uploaded in a multipart-upload operation. This is a positive -// integer between 1 and 10,000. -func AWSS3PartNumber(val int) attribute.KeyValue { - return AWSS3PartNumberKey.Int(val) -} - -// AWSS3UploadID returns an attribute KeyValue conforming to the -// "aws.s3.upload_id" semantic conventions. It represents the upload ID that -// identifies the multipart upload. -func AWSS3UploadID(val string) attribute.KeyValue { - return AWSS3UploadIDKey.String(val) -} - -// The web browser attributes -const ( - // BrowserBrandsKey is the attribute Key conforming to the "browser.brands" - // semantic conventions. It represents the array of brand name and version - // separated by a space - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: ' Not A;Brand 99', 'Chromium 99', 'Chrome 99' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.brands`). - BrowserBrandsKey = attribute.Key("browser.brands") - - // BrowserLanguageKey is the attribute Key conforming to the - // "browser.language" semantic conventions. It represents the preferred - // language of the user using the browser - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'en', 'en-US', 'fr', 'fr-FR' - // Note: This value is intended to be taken from the Navigator API - // `navigator.language`. - BrowserLanguageKey = attribute.Key("browser.language") - - // BrowserMobileKey is the attribute Key conforming to the "browser.mobile" - // semantic conventions. It represents a boolean that is true if the - // browser is running on a mobile device - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.mobile`). If unavailable, this attribute - // SHOULD be left unset. - BrowserMobileKey = attribute.Key("browser.mobile") - - // BrowserPlatformKey is the attribute Key conforming to the - // "browser.platform" semantic conventions. It represents the platform on - // which the browser is running - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Windows', 'macOS', 'Android' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.platform`). If unavailable, the legacy - // `navigator.platform` API SHOULD NOT be used instead and this attribute - // SHOULD be left unset in order for the values to be consistent. - // The list of possible values is defined in the [W3C User-Agent Client - // Hints - // specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). - // Note that some (but not all) of these values can overlap with values in - // the [`os.type` and `os.name` attributes](./os.md). However, for - // consistency, the values in the `browser.platform` attribute should - // capture the exact value that the user agent provides. - BrowserPlatformKey = attribute.Key("browser.platform") -) - -// BrowserBrands returns an attribute KeyValue conforming to the -// "browser.brands" semantic conventions. It represents the array of brand name -// and version separated by a space -func BrowserBrands(val ...string) attribute.KeyValue { - return BrowserBrandsKey.StringSlice(val) -} - -// BrowserLanguage returns an attribute KeyValue conforming to the -// "browser.language" semantic conventions. It represents the preferred -// language of the user using the browser -func BrowserLanguage(val string) attribute.KeyValue { - return BrowserLanguageKey.String(val) -} - -// BrowserMobile returns an attribute KeyValue conforming to the -// "browser.mobile" semantic conventions. It represents a boolean that is true -// if the browser is running on a mobile device -func BrowserMobile(val bool) attribute.KeyValue { - return BrowserMobileKey.Bool(val) -} - -// BrowserPlatform returns an attribute KeyValue conforming to the -// "browser.platform" semantic conventions. It represents the platform on which -// the browser is running -func BrowserPlatform(val string) attribute.KeyValue { - return BrowserPlatformKey.String(val) -} - -// These attributes may be used to describe the client in a connection-based -// network interaction where there is one side that initiates the connection -// (the client is the side that initiates the connection). This covers all TCP -// network interactions since TCP is connection-based and one side initiates -// the connection (an exception is made for peer-to-peer communication over TCP -// where the "user-facing" surface of the protocol / API doesn't expose a clear -// notion of client and server). This also covers UDP network interactions -// where one side initiates the interaction, e.g. QUIC (HTTP/3) and DNS. -const ( - // ClientAddressKey is the attribute Key conforming to the "client.address" - // semantic conventions. It represents the client address - domain name if - // available without reverse DNS lookup; otherwise, IP address or Unix - // domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'client.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the server side, and when communicating through - // an intermediary, `client.address` SHOULD represent the client address - // behind any intermediaries, for example proxies, if it's available. - ClientAddressKey = attribute.Key("client.address") - - // ClientPortKey is the attribute Key conforming to the "client.port" - // semantic conventions. It represents the client port number. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - // Note: When observed from the server side, and when communicating through - // an intermediary, `client.port` SHOULD represent the client port behind - // any intermediaries, for example proxies, if it's available. - ClientPortKey = attribute.Key("client.port") -) - -// ClientAddress returns an attribute KeyValue conforming to the -// "client.address" semantic conventions. It represents the client address - -// domain name if available without reverse DNS lookup; otherwise, IP address -// or Unix domain socket name. -func ClientAddress(val string) attribute.KeyValue { - return ClientAddressKey.String(val) -} - -// ClientPort returns an attribute KeyValue conforming to the "client.port" -// semantic conventions. It represents the client port number. -func ClientPort(val int) attribute.KeyValue { - return ClientPortKey.Int(val) -} - -// A cloud environment (e.g. GCP, Azure, AWS). -const ( - // CloudAccountIDKey is the attribute Key conforming to the - // "cloud.account.id" semantic conventions. It represents the cloud account - // ID the resource is assigned to. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '111111111111', 'opentelemetry' - CloudAccountIDKey = attribute.Key("cloud.account.id") - - // CloudAvailabilityZoneKey is the attribute Key conforming to the - // "cloud.availability_zone" semantic conventions. It represents the cloud - // regions often have multiple, isolated locations known as zones to - // increase availability. Availability zone represents the zone where the - // resource is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-east-1c' - // Note: Availability zones are called "zones" on Alibaba Cloud and Google - // Cloud. - CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") - - // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" - // semantic conventions. It represents the cloud platform in use. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The prefix of the service SHOULD match the one specified in - // `cloud.provider`. - CloudPlatformKey = attribute.Key("cloud.platform") - - // CloudProviderKey is the attribute Key conforming to the "cloud.provider" - // semantic conventions. It represents the name of the cloud provider. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - CloudProviderKey = attribute.Key("cloud.provider") - - // CloudRegionKey is the attribute Key conforming to the "cloud.region" - // semantic conventions. It represents the geographical region the resource - // is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-central1', 'us-east-1' - // Note: Refer to your provider's docs to see the available regions, for - // example [Alibaba Cloud - // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS - // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), - // [Azure - // regions](https://azure.microsoft.com/global-infrastructure/geographies/), - // [Google Cloud regions](https://cloud.google.com/about/locations), or - // [Tencent Cloud - // regions](https://www.tencentcloud.com/document/product/213/6091). - CloudRegionKey = attribute.Key("cloud.region") - - // CloudResourceIDKey is the attribute Key conforming to the - // "cloud.resource_id" semantic conventions. It represents the cloud - // provider-specific native identifier of the monitored cloud resource - // (e.g. an - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // on AWS, a [fully qualified resource - // ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) - // on Azure, a [full resource - // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // on GCP) - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:lambda:REGION:ACCOUNT_ID:function:my-function', - // '//run.googleapis.com/projects/PROJECT_ID/locations/LOCATION_ID/services/SERVICE_ID', - // '/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/' - // Note: On some cloud providers, it may not be possible to determine the - // full ID at startup, - // so it may be necessary to set `cloud.resource_id` as a span attribute - // instead. - // - // The exact value to use for `cloud.resource_id` depends on the cloud - // provider. - // The following well-known definitions MUST be used if you set this - // attribute and they apply: - // - // * **AWS Lambda:** The function - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - // Take care not to use the "invoked ARN" directly but replace any - // [alias - // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) - // with the resolved function version, as the same runtime instance may - // be invokable with - // multiple different aliases. - // * **GCP:** The [URI of the - // resource](https://cloud.google.com/iam/docs/full-resource-names) - // * **Azure:** The [Fully Qualified Resource - // ID](https://docs.microsoft.com/rest/api/resources/resources/get-by-id) - // of the invoked function, - // *not* the function app, having the form - // `/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/`. - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider. - CloudResourceIDKey = attribute.Key("cloud.resource_id") -) - -var ( - // Alibaba Cloud Elastic Compute Service - CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") - // Alibaba Cloud Function Compute - CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") - // Red Hat OpenShift on Alibaba Cloud - CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") - // AWS Elastic Compute Cloud - CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") - // AWS Elastic Container Service - CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") - // AWS Elastic Kubernetes Service - CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") - // AWS Lambda - CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") - // AWS Elastic Beanstalk - CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") - // AWS App Runner - CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") - // Red Hat OpenShift on AWS (ROSA) - CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") - // Azure Virtual Machines - CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") - // Azure Container Apps - CloudPlatformAzureContainerApps = CloudPlatformKey.String("azure_container_apps") - // Azure Container Instances - CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") - // Azure Kubernetes Service - CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") - // Azure Functions - CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") - // Azure App Service - CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") - // Azure Red Hat OpenShift - CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") - // Google Bare Metal Solution (BMS) - CloudPlatformGCPBareMetalSolution = CloudPlatformKey.String("gcp_bare_metal_solution") - // Google Cloud Compute Engine (GCE) - CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") - // Google Cloud Run - CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") - // Google Cloud Kubernetes Engine (GKE) - CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") - // Google Cloud Functions (GCF) - CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") - // Google Cloud App Engine (GAE) - CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") - // Red Hat OpenShift on Google Cloud - CloudPlatformGCPOpenshift = CloudPlatformKey.String("gcp_openshift") - // Red Hat OpenShift on IBM Cloud - CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") - // Tencent Cloud Cloud Virtual Machine (CVM) - CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") - // Tencent Cloud Elastic Kubernetes Service (EKS) - CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") - // Tencent Cloud Serverless Cloud Function (SCF) - CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") -) - -var ( - // Alibaba Cloud - CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") - // Amazon Web Services - CloudProviderAWS = CloudProviderKey.String("aws") - // Microsoft Azure - CloudProviderAzure = CloudProviderKey.String("azure") - // Google Cloud Platform - CloudProviderGCP = CloudProviderKey.String("gcp") - // Heroku Platform as a Service - CloudProviderHeroku = CloudProviderKey.String("heroku") - // IBM Cloud - CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") - // Tencent Cloud - CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") -) - -// CloudAccountID returns an attribute KeyValue conforming to the -// "cloud.account.id" semantic conventions. It represents the cloud account ID -// the resource is assigned to. -func CloudAccountID(val string) attribute.KeyValue { - return CloudAccountIDKey.String(val) -} - -// CloudAvailabilityZone returns an attribute KeyValue conforming to the -// "cloud.availability_zone" semantic conventions. It represents the cloud -// regions often have multiple, isolated locations known as zones to increase -// availability. Availability zone represents the zone where the resource is -// running. -func CloudAvailabilityZone(val string) attribute.KeyValue { - return CloudAvailabilityZoneKey.String(val) -} - -// CloudRegion returns an attribute KeyValue conforming to the -// "cloud.region" semantic conventions. It represents the geographical region -// the resource is running. -func CloudRegion(val string) attribute.KeyValue { - return CloudRegionKey.String(val) -} - -// CloudResourceID returns an attribute KeyValue conforming to the -// "cloud.resource_id" semantic conventions. It represents the cloud -// provider-specific native identifier of the monitored cloud resource (e.g. an -// [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) -// on AWS, a [fully qualified resource -// ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) on -// Azure, a [full resource -// name](https://cloud.google.com/apis/design/resource_names#full_resource_name) -// on GCP) -func CloudResourceID(val string) attribute.KeyValue { - return CloudResourceIDKey.String(val) -} - -// Attributes for CloudEvents. -const ( - // CloudeventsEventIDKey is the attribute Key conforming to the - // "cloudevents.event_id" semantic conventions. It represents the - // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) - // uniquely identifies the event. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' - CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") - - // CloudeventsEventSourceKey is the attribute Key conforming to the - // "cloudevents.event_source" semantic conventions. It represents the - // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) - // identifies the context in which an event happened. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'https://github.com/cloudevents', - // '/cloudevents/spec/pull/123', 'my-service' - CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") - - // CloudeventsEventSpecVersionKey is the attribute Key conforming to the - // "cloudevents.event_spec_version" semantic conventions. It represents the - // [version of the CloudEvents - // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) - // which the event uses. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.0' - CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") - - // CloudeventsEventSubjectKey is the attribute Key conforming to the - // "cloudevents.event_subject" semantic conventions. It represents the - // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) - // of the event in the context of the event producer (identified by - // source). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mynewfile.jpg' - CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") - - // CloudeventsEventTypeKey is the attribute Key conforming to the - // "cloudevents.event_type" semantic conventions. It represents the - // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) - // contains a value describing the type of event related to the originating - // occurrence. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'com.github.pull_request.opened', - // 'com.example.object.deleted.v2' - CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") -) - -// CloudeventsEventID returns an attribute KeyValue conforming to the -// "cloudevents.event_id" semantic conventions. It represents the -// [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) -// uniquely identifies the event. -func CloudeventsEventID(val string) attribute.KeyValue { - return CloudeventsEventIDKey.String(val) -} - -// CloudeventsEventSource returns an attribute KeyValue conforming to the -// "cloudevents.event_source" semantic conventions. It represents the -// [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) -// identifies the context in which an event happened. -func CloudeventsEventSource(val string) attribute.KeyValue { - return CloudeventsEventSourceKey.String(val) -} - -// CloudeventsEventSpecVersion returns an attribute KeyValue conforming to -// the "cloudevents.event_spec_version" semantic conventions. It represents the -// [version of the CloudEvents -// specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) -// which the event uses. -func CloudeventsEventSpecVersion(val string) attribute.KeyValue { - return CloudeventsEventSpecVersionKey.String(val) -} - -// CloudeventsEventSubject returns an attribute KeyValue conforming to the -// "cloudevents.event_subject" semantic conventions. It represents the -// [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) -// of the event in the context of the event producer (identified by source). -func CloudeventsEventSubject(val string) attribute.KeyValue { - return CloudeventsEventSubjectKey.String(val) -} - -// CloudeventsEventType returns an attribute KeyValue conforming to the -// "cloudevents.event_type" semantic conventions. It represents the -// [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) -// contains a value describing the type of event related to the originating -// occurrence. -func CloudeventsEventType(val string) attribute.KeyValue { - return CloudeventsEventTypeKey.String(val) -} - -// These attributes allow to report this unit of code and therefore to provide -// more context about the span. -const ( - // CodeColumnKey is the attribute Key conforming to the "code.column" - // semantic conventions. It represents the column number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 16 - CodeColumnKey = attribute.Key("code.column") - - // CodeFilepathKey is the attribute Key conforming to the "code.filepath" - // semantic conventions. It represents the source code file name that - // identifies the code unit as uniquely as possible (preferably an absolute - // file path). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/usr/local/MyApplication/content_root/app/index.php' - CodeFilepathKey = attribute.Key("code.filepath") - - // CodeFunctionKey is the attribute Key conforming to the "code.function" - // semantic conventions. It represents the method or function name, or - // equivalent (usually rightmost part of the code unit's name). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'serveRequest' - CodeFunctionKey = attribute.Key("code.function") - - // CodeLineNumberKey is the attribute Key conforming to the "code.lineno" - // semantic conventions. It represents the line number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - CodeLineNumberKey = attribute.Key("code.lineno") - - // CodeNamespaceKey is the attribute Key conforming to the "code.namespace" - // semantic conventions. It represents the "namespace" within which - // `code.function` is defined. Usually the qualified class or module name, - // such that `code.namespace` + some separator + `code.function` form a - // unique identifier for the code unit. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'com.example.MyHTTPService' - CodeNamespaceKey = attribute.Key("code.namespace") - - // CodeStacktraceKey is the attribute Key conforming to the - // "code.stacktrace" semantic conventions. It represents a stacktrace as a - // string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'at - // com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - CodeStacktraceKey = attribute.Key("code.stacktrace") -) - -// CodeColumn returns an attribute KeyValue conforming to the "code.column" -// semantic conventions. It represents the column number in `code.filepath` -// best representing the operation. It SHOULD point within the code unit named -// in `code.function`. -func CodeColumn(val int) attribute.KeyValue { - return CodeColumnKey.Int(val) -} - -// CodeFilepath returns an attribute KeyValue conforming to the -// "code.filepath" semantic conventions. It represents the source code file -// name that identifies the code unit as uniquely as possible (preferably an -// absolute file path). -func CodeFilepath(val string) attribute.KeyValue { - return CodeFilepathKey.String(val) -} - -// CodeFunction returns an attribute KeyValue conforming to the -// "code.function" semantic conventions. It represents the method or function -// name, or equivalent (usually rightmost part of the code unit's name). -func CodeFunction(val string) attribute.KeyValue { - return CodeFunctionKey.String(val) -} - -// CodeLineNumber returns an attribute KeyValue conforming to the "code.lineno" -// semantic conventions. It represents the line number in `code.filepath` best -// representing the operation. It SHOULD point within the code unit named in -// `code.function`. -func CodeLineNumber(val int) attribute.KeyValue { - return CodeLineNumberKey.Int(val) -} - -// CodeNamespace returns an attribute KeyValue conforming to the -// "code.namespace" semantic conventions. It represents the "namespace" within -// which `code.function` is defined. Usually the qualified class or module -// name, such that `code.namespace` + some separator + `code.function` form a -// unique identifier for the code unit. -func CodeNamespace(val string) attribute.KeyValue { - return CodeNamespaceKey.String(val) -} - -// CodeStacktrace returns an attribute KeyValue conforming to the -// "code.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func CodeStacktrace(val string) attribute.KeyValue { - return CodeStacktraceKey.String(val) -} - -// A container instance. -const ( - // ContainerCommandKey is the attribute Key conforming to the - // "container.command" semantic conventions. It represents the command used - // to run the container (i.e. the command name). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol' - // Note: If using embedded credentials or sensitive data, it is recommended - // to remove them to prevent potential leakage. - ContainerCommandKey = attribute.Key("container.command") - - // ContainerCommandArgsKey is the attribute Key conforming to the - // "container.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) run by the - // container. [2] - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol, --config, config.yaml' - ContainerCommandArgsKey = attribute.Key("container.command_args") - - // ContainerCommandLineKey is the attribute Key conforming to the - // "container.command_line" semantic conventions. It represents the full - // command run by the container as a single string representing the full - // command. [2] - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol --config config.yaml' - ContainerCommandLineKey = attribute.Key("container.command_line") - - // ContainerCPUStateKey is the attribute Key conforming to the - // "container.cpu.state" semantic conventions. It represents the CPU state - // for this data point. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'user', 'kernel' - ContainerCPUStateKey = attribute.Key("container.cpu.state") - - // ContainerIDKey is the attribute Key conforming to the "container.id" - // semantic conventions. It represents the container ID. Usually a UUID, as - // for example used to [identify Docker - // containers](https://docs.docker.com/engine/reference/run/#container-identification). - // The UUID might be abbreviated. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'a3bf90e006b2' - ContainerIDKey = attribute.Key("container.id") - - // ContainerImageIDKey is the attribute Key conforming to the - // "container.image.id" semantic conventions. It represents the runtime - // specific image identifier. Usually a hash algorithm followed by a UUID. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'sha256:19c92d0a00d1b66d897bceaa7319bee0dd38a10a851c60bcec9474aa3f01e50f' - // Note: Docker defines a sha256 of the image id; `container.image.id` - // corresponds to the `Image` field from the Docker container inspect - // [API](https://docs.docker.com/engine/api/v1.43/#tag/Container/operation/ContainerInspect) - // endpoint. - // K8S defines a link to the container registry repository with digest - // `"imageID": "registry.azurecr.io - // /namespace/service/dockerfile@sha256:bdeabd40c3a8a492eaf9e8e44d0ebbb84bac7ee25ac0cf8a7159d25f62555625"`. - // The ID is assigned by the container runtime and can vary in different - // environments. Consider using `oci.manifest.digest` if it is important to - // identify the same image in different environments/runtimes. - ContainerImageIDKey = attribute.Key("container.image.id") - - // ContainerImageNameKey is the attribute Key conforming to the - // "container.image.name" semantic conventions. It represents the name of - // the image the container was built on. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'gcr.io/opentelemetry/operator' - ContainerImageNameKey = attribute.Key("container.image.name") - - // ContainerImageRepoDigestsKey is the attribute Key conforming to the - // "container.image.repo_digests" semantic conventions. It represents the - // repo digests of the container image as provided by the container - // runtime. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb', - // 'internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578' - // Note: - // [Docker](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect) - // and - // [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) - // report those under the `RepoDigests` field. - ContainerImageRepoDigestsKey = attribute.Key("container.image.repo_digests") - - // ContainerImageTagsKey is the attribute Key conforming to the - // "container.image.tags" semantic conventions. It represents the container - // image tags. An example can be found in [Docker Image - // Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). - // Should be only the `` section of the full name for example from - // `registry.example.com/my-org/my-image:`. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'v1.27.1', '3.5.7-0' - ContainerImageTagsKey = attribute.Key("container.image.tags") - - // ContainerNameKey is the attribute Key conforming to the "container.name" - // semantic conventions. It represents the container name used by container - // runtime. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-autoconf' - ContainerNameKey = attribute.Key("container.name") - - // ContainerRuntimeKey is the attribute Key conforming to the - // "container.runtime" semantic conventions. It represents the container - // runtime managing this container. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'docker', 'containerd', 'rkt' - ContainerRuntimeKey = attribute.Key("container.runtime") -) - -var ( - // When tasks of the cgroup are in user mode (Linux). When all container processes are in user mode (Windows) - ContainerCPUStateUser = ContainerCPUStateKey.String("user") - // When CPU is used by the system (host OS) - ContainerCPUStateSystem = ContainerCPUStateKey.String("system") - // When tasks of the cgroup are in kernel mode (Linux). When all container processes are in kernel mode (Windows) - ContainerCPUStateKernel = ContainerCPUStateKey.String("kernel") -) - -// ContainerCommand returns an attribute KeyValue conforming to the -// "container.command" semantic conventions. It represents the command used to -// run the container (i.e. the command name). -func ContainerCommand(val string) attribute.KeyValue { - return ContainerCommandKey.String(val) -} - -// ContainerCommandArgs returns an attribute KeyValue conforming to the -// "container.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) run by the -// container. [2] -func ContainerCommandArgs(val ...string) attribute.KeyValue { - return ContainerCommandArgsKey.StringSlice(val) -} - -// ContainerCommandLine returns an attribute KeyValue conforming to the -// "container.command_line" semantic conventions. It represents the full -// command run by the container as a single string representing the full -// command. [2] -func ContainerCommandLine(val string) attribute.KeyValue { - return ContainerCommandLineKey.String(val) -} - -// ContainerID returns an attribute KeyValue conforming to the -// "container.id" semantic conventions. It represents the container ID. Usually -// a UUID, as for example used to [identify Docker -// containers](https://docs.docker.com/engine/reference/run/#container-identification). -// The UUID might be abbreviated. -func ContainerID(val string) attribute.KeyValue { - return ContainerIDKey.String(val) -} - -// ContainerImageID returns an attribute KeyValue conforming to the -// "container.image.id" semantic conventions. It represents the runtime -// specific image identifier. Usually a hash algorithm followed by a UUID. -func ContainerImageID(val string) attribute.KeyValue { - return ContainerImageIDKey.String(val) -} - -// ContainerImageName returns an attribute KeyValue conforming to the -// "container.image.name" semantic conventions. It represents the name of the -// image the container was built on. -func ContainerImageName(val string) attribute.KeyValue { - return ContainerImageNameKey.String(val) -} - -// ContainerImageRepoDigests returns an attribute KeyValue conforming to the -// "container.image.repo_digests" semantic conventions. It represents the repo -// digests of the container image as provided by the container runtime. -func ContainerImageRepoDigests(val ...string) attribute.KeyValue { - return ContainerImageRepoDigestsKey.StringSlice(val) -} - -// ContainerImageTags returns an attribute KeyValue conforming to the -// "container.image.tags" semantic conventions. It represents the container -// image tags. An example can be found in [Docker Image -// Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). -// Should be only the `` section of the full name for example from -// `registry.example.com/my-org/my-image:`. -func ContainerImageTags(val ...string) attribute.KeyValue { - return ContainerImageTagsKey.StringSlice(val) -} - -// ContainerName returns an attribute KeyValue conforming to the -// "container.name" semantic conventions. It represents the container name used -// by container runtime. -func ContainerName(val string) attribute.KeyValue { - return ContainerNameKey.String(val) -} - -// ContainerRuntime returns an attribute KeyValue conforming to the -// "container.runtime" semantic conventions. It represents the container -// runtime managing this container. -func ContainerRuntime(val string) attribute.KeyValue { - return ContainerRuntimeKey.String(val) -} - -// This group defines the attributes used to describe telemetry in the context -// of databases. -const ( - // DBClientConnectionsPoolNameKey is the attribute Key conforming to the - // "db.client.connections.pool.name" semantic conventions. It represents - // the name of the connection pool; unique within the instrumented - // application. In case the connection pool implementation doesn't provide - // a name, instrumentation should use a combination of `server.address` and - // `server.port` attributes formatted as `server.address:server.port`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myDataSource' - DBClientConnectionsPoolNameKey = attribute.Key("db.client.connections.pool.name") - - // DBClientConnectionsStateKey is the attribute Key conforming to the - // "db.client.connections.state" semantic conventions. It represents the - // state of a connection in the pool - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'idle' - DBClientConnectionsStateKey = attribute.Key("db.client.connections.state") - - // DBCollectionNameKey is the attribute Key conforming to the - // "db.collection.name" semantic conventions. It represents the name of a - // collection (table, container) within the database. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'public.users', 'customers' - // Note: If the collection name is parsed from the query, it SHOULD match - // the value provided in the query and may be qualified with the schema and - // database name. - // It is RECOMMENDED to capture the value as provided by the application - // without attempting to do any case normalization. - DBCollectionNameKey = attribute.Key("db.collection.name") - - // DBNamespaceKey is the attribute Key conforming to the "db.namespace" - // semantic conventions. It represents the name of the database, fully - // qualified within the server address and port. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'customers', 'test.users' - // Note: If a database system has multiple namespace components, they - // SHOULD be concatenated (potentially using database system specific - // conventions) from most general to most specific namespace component, and - // more specific namespaces SHOULD NOT be captured without the more general - // namespaces, to ensure that "startswith" queries for the more general - // namespaces will be valid. - // Semantic conventions for individual database systems SHOULD document - // what `db.namespace` means in the context of that system. - // It is RECOMMENDED to capture the value as provided by the application - // without attempting to do any case normalization. - DBNamespaceKey = attribute.Key("db.namespace") - - // DBOperationNameKey is the attribute Key conforming to the - // "db.operation.name" semantic conventions. It represents the name of the - // operation or command being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'findAndModify', 'HMSET', 'SELECT' - // Note: It is RECOMMENDED to capture the value as provided by the - // application without attempting to do any case normalization. - DBOperationNameKey = attribute.Key("db.operation.name") - - // DBQueryTextKey is the attribute Key conforming to the "db.query.text" - // semantic conventions. It represents the database query being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'SELECT * FROM wuser_table where username = ?', 'SET mykey - // "WuValue"' - DBQueryTextKey = attribute.Key("db.query.text") - - // DBSystemKey is the attribute Key conforming to the "db.system" semantic - // conventions. It represents the database management system (DBMS) product - // as identified by the client instrumentation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The actual DBMS may differ from the one identified by the client. - // For example, when using PostgreSQL client libraries to connect to a - // CockroachDB, the `db.system` is set to `postgresql` based on the - // instrumentation's best knowledge. - DBSystemKey = attribute.Key("db.system") -) - -var ( - // idle - DBClientConnectionsStateIdle = DBClientConnectionsStateKey.String("idle") - // used - DBClientConnectionsStateUsed = DBClientConnectionsStateKey.String("used") -) - -var ( - // Some other SQL database. Fallback only. See notes - DBSystemOtherSQL = DBSystemKey.String("other_sql") - // Microsoft SQL Server - DBSystemMSSQL = DBSystemKey.String("mssql") - // Microsoft SQL Server Compact - DBSystemMssqlcompact = DBSystemKey.String("mssqlcompact") - // MySQL - DBSystemMySQL = DBSystemKey.String("mysql") - // Oracle Database - DBSystemOracle = DBSystemKey.String("oracle") - // IBM DB2 - DBSystemDB2 = DBSystemKey.String("db2") - // PostgreSQL - DBSystemPostgreSQL = DBSystemKey.String("postgresql") - // Amazon Redshift - DBSystemRedshift = DBSystemKey.String("redshift") - // Apache Hive - DBSystemHive = DBSystemKey.String("hive") - // Cloudscape - DBSystemCloudscape = DBSystemKey.String("cloudscape") - // HyperSQL DataBase - DBSystemHSQLDB = DBSystemKey.String("hsqldb") - // Progress Database - DBSystemProgress = DBSystemKey.String("progress") - // SAP MaxDB - DBSystemMaxDB = DBSystemKey.String("maxdb") - // SAP HANA - DBSystemHanaDB = DBSystemKey.String("hanadb") - // Ingres - DBSystemIngres = DBSystemKey.String("ingres") - // FirstSQL - DBSystemFirstSQL = DBSystemKey.String("firstsql") - // EnterpriseDB - DBSystemEDB = DBSystemKey.String("edb") - // InterSystems Caché - DBSystemCache = DBSystemKey.String("cache") - // Adabas (Adaptable Database System) - DBSystemAdabas = DBSystemKey.String("adabas") - // Firebird - DBSystemFirebird = DBSystemKey.String("firebird") - // Apache Derby - DBSystemDerby = DBSystemKey.String("derby") - // FileMaker - DBSystemFilemaker = DBSystemKey.String("filemaker") - // Informix - DBSystemInformix = DBSystemKey.String("informix") - // InstantDB - DBSystemInstantDB = DBSystemKey.String("instantdb") - // InterBase - DBSystemInterbase = DBSystemKey.String("interbase") - // MariaDB - DBSystemMariaDB = DBSystemKey.String("mariadb") - // Netezza - DBSystemNetezza = DBSystemKey.String("netezza") - // Pervasive PSQL - DBSystemPervasive = DBSystemKey.String("pervasive") - // PointBase - DBSystemPointbase = DBSystemKey.String("pointbase") - // SQLite - DBSystemSqlite = DBSystemKey.String("sqlite") - // Sybase - DBSystemSybase = DBSystemKey.String("sybase") - // Teradata - DBSystemTeradata = DBSystemKey.String("teradata") - // Vertica - DBSystemVertica = DBSystemKey.String("vertica") - // H2 - DBSystemH2 = DBSystemKey.String("h2") - // ColdFusion IMQ - DBSystemColdfusion = DBSystemKey.String("coldfusion") - // Apache Cassandra - DBSystemCassandra = DBSystemKey.String("cassandra") - // Apache HBase - DBSystemHBase = DBSystemKey.String("hbase") - // MongoDB - DBSystemMongoDB = DBSystemKey.String("mongodb") - // Redis - DBSystemRedis = DBSystemKey.String("redis") - // Couchbase - DBSystemCouchbase = DBSystemKey.String("couchbase") - // CouchDB - DBSystemCouchDB = DBSystemKey.String("couchdb") - // Microsoft Azure Cosmos DB - DBSystemCosmosDB = DBSystemKey.String("cosmosdb") - // Amazon DynamoDB - DBSystemDynamoDB = DBSystemKey.String("dynamodb") - // Neo4j - DBSystemNeo4j = DBSystemKey.String("neo4j") - // Apache Geode - DBSystemGeode = DBSystemKey.String("geode") - // Elasticsearch - DBSystemElasticsearch = DBSystemKey.String("elasticsearch") - // Memcached - DBSystemMemcached = DBSystemKey.String("memcached") - // CockroachDB - DBSystemCockroachdb = DBSystemKey.String("cockroachdb") - // OpenSearch - DBSystemOpensearch = DBSystemKey.String("opensearch") - // ClickHouse - DBSystemClickhouse = DBSystemKey.String("clickhouse") - // Cloud Spanner - DBSystemSpanner = DBSystemKey.String("spanner") - // Trino - DBSystemTrino = DBSystemKey.String("trino") -) - -// DBClientConnectionsPoolName returns an attribute KeyValue conforming to -// the "db.client.connections.pool.name" semantic conventions. It represents -// the name of the connection pool; unique within the instrumented application. -// In case the connection pool implementation doesn't provide a name, -// instrumentation should use a combination of `server.address` and -// `server.port` attributes formatted as `server.address:server.port`. -func DBClientConnectionsPoolName(val string) attribute.KeyValue { - return DBClientConnectionsPoolNameKey.String(val) -} - -// DBCollectionName returns an attribute KeyValue conforming to the -// "db.collection.name" semantic conventions. It represents the name of a -// collection (table, container) within the database. -func DBCollectionName(val string) attribute.KeyValue { - return DBCollectionNameKey.String(val) -} - -// DBNamespace returns an attribute KeyValue conforming to the -// "db.namespace" semantic conventions. It represents the name of the database, -// fully qualified within the server address and port. -func DBNamespace(val string) attribute.KeyValue { - return DBNamespaceKey.String(val) -} - -// DBOperationName returns an attribute KeyValue conforming to the -// "db.operation.name" semantic conventions. It represents the name of the -// operation or command being executed. -func DBOperationName(val string) attribute.KeyValue { - return DBOperationNameKey.String(val) -} - -// DBQueryText returns an attribute KeyValue conforming to the -// "db.query.text" semantic conventions. It represents the database query being -// executed. -func DBQueryText(val string) attribute.KeyValue { - return DBQueryTextKey.String(val) -} - -// This group defines attributes for Cassandra. -const ( - // DBCassandraConsistencyLevelKey is the attribute Key conforming to the - // "db.cassandra.consistency_level" semantic conventions. It represents the - // consistency level of the query. Based on consistency values from - // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") - - // DBCassandraCoordinatorDCKey is the attribute Key conforming to the - // "db.cassandra.coordinator.dc" semantic conventions. It represents the - // data center of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-west-2' - DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") - - // DBCassandraCoordinatorIDKey is the attribute Key conforming to the - // "db.cassandra.coordinator.id" semantic conventions. It represents the ID - // of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' - DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") - - // DBCassandraIdempotenceKey is the attribute Key conforming to the - // "db.cassandra.idempotence" semantic conventions. It represents the - // whether or not the query is idempotent. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") - - // DBCassandraPageSizeKey is the attribute Key conforming to the - // "db.cassandra.page_size" semantic conventions. It represents the fetch - // size used for paging, i.e. how many rows will be returned at once. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 5000 - DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") - - // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming - // to the "db.cassandra.speculative_execution_count" semantic conventions. - // It represents the number of times a query was speculatively executed. - // Not set or `0` if the query was not executed speculatively. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 2 - DBCassandraSpeculativeExecutionCountKey = attribute.Key("db.cassandra.speculative_execution_count") -) - -var ( - // all - DBCassandraConsistencyLevelAll = DBCassandraConsistencyLevelKey.String("all") - // each_quorum - DBCassandraConsistencyLevelEachQuorum = DBCassandraConsistencyLevelKey.String("each_quorum") - // quorum - DBCassandraConsistencyLevelQuorum = DBCassandraConsistencyLevelKey.String("quorum") - // local_quorum - DBCassandraConsistencyLevelLocalQuorum = DBCassandraConsistencyLevelKey.String("local_quorum") - // one - DBCassandraConsistencyLevelOne = DBCassandraConsistencyLevelKey.String("one") - // two - DBCassandraConsistencyLevelTwo = DBCassandraConsistencyLevelKey.String("two") - // three - DBCassandraConsistencyLevelThree = DBCassandraConsistencyLevelKey.String("three") - // local_one - DBCassandraConsistencyLevelLocalOne = DBCassandraConsistencyLevelKey.String("local_one") - // any - DBCassandraConsistencyLevelAny = DBCassandraConsistencyLevelKey.String("any") - // serial - DBCassandraConsistencyLevelSerial = DBCassandraConsistencyLevelKey.String("serial") - // local_serial - DBCassandraConsistencyLevelLocalSerial = DBCassandraConsistencyLevelKey.String("local_serial") -) - -// DBCassandraCoordinatorDC returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.dc" semantic conventions. It represents the data -// center of the coordinating node for a query. -func DBCassandraCoordinatorDC(val string) attribute.KeyValue { - return DBCassandraCoordinatorDCKey.String(val) -} - -// DBCassandraCoordinatorID returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.id" semantic conventions. It represents the ID of -// the coordinating node for a query. -func DBCassandraCoordinatorID(val string) attribute.KeyValue { - return DBCassandraCoordinatorIDKey.String(val) -} - -// DBCassandraIdempotence returns an attribute KeyValue conforming to the -// "db.cassandra.idempotence" semantic conventions. It represents the whether -// or not the query is idempotent. -func DBCassandraIdempotence(val bool) attribute.KeyValue { - return DBCassandraIdempotenceKey.Bool(val) -} - -// DBCassandraPageSize returns an attribute KeyValue conforming to the -// "db.cassandra.page_size" semantic conventions. It represents the fetch size -// used for paging, i.e. how many rows will be returned at once. -func DBCassandraPageSize(val int) attribute.KeyValue { - return DBCassandraPageSizeKey.Int(val) -} - -// DBCassandraSpeculativeExecutionCount returns an attribute KeyValue -// conforming to the "db.cassandra.speculative_execution_count" semantic -// conventions. It represents the number of times a query was speculatively -// executed. Not set or `0` if the query was not executed speculatively. -func DBCassandraSpeculativeExecutionCount(val int) attribute.KeyValue { - return DBCassandraSpeculativeExecutionCountKey.Int(val) -} - -// This group defines attributes for Azure Cosmos DB. -const ( - // DBCosmosDBClientIDKey is the attribute Key conforming to the - // "db.cosmosdb.client_id" semantic conventions. It represents the unique - // Cosmos client instance id. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '3ba4827d-4422-483f-b59f-85b74211c11d' - DBCosmosDBClientIDKey = attribute.Key("db.cosmosdb.client_id") - - // DBCosmosDBConnectionModeKey is the attribute Key conforming to the - // "db.cosmosdb.connection_mode" semantic conventions. It represents the - // cosmos client connection mode. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBConnectionModeKey = attribute.Key("db.cosmosdb.connection_mode") - - // DBCosmosDBOperationTypeKey is the attribute Key conforming to the - // "db.cosmosdb.operation_type" semantic conventions. It represents the - // cosmosDB Operation Type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBOperationTypeKey = attribute.Key("db.cosmosdb.operation_type") - - // DBCosmosDBRequestChargeKey is the attribute Key conforming to the - // "db.cosmosdb.request_charge" semantic conventions. It represents the rU - // consumed for that operation - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 46.18, 1.0 - DBCosmosDBRequestChargeKey = attribute.Key("db.cosmosdb.request_charge") - - // DBCosmosDBRequestContentLengthKey is the attribute Key conforming to the - // "db.cosmosdb.request_content_length" semantic conventions. It represents - // the request payload size in bytes - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBRequestContentLengthKey = attribute.Key("db.cosmosdb.request_content_length") - - // DBCosmosDBStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.status_code" semantic conventions. It represents the cosmos - // DB status code. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 200, 201 - DBCosmosDBStatusCodeKey = attribute.Key("db.cosmosdb.status_code") - - // DBCosmosDBSubStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.sub_status_code" semantic conventions. It represents the - // cosmos DB sub status code. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1000, 1002 - DBCosmosDBSubStatusCodeKey = attribute.Key("db.cosmosdb.sub_status_code") -) - -var ( - // Gateway (HTTP) connections mode - DBCosmosDBConnectionModeGateway = DBCosmosDBConnectionModeKey.String("gateway") - // Direct connection - DBCosmosDBConnectionModeDirect = DBCosmosDBConnectionModeKey.String("direct") -) - -var ( - // invalid - DBCosmosDBOperationTypeInvalid = DBCosmosDBOperationTypeKey.String("Invalid") - // create - DBCosmosDBOperationTypeCreate = DBCosmosDBOperationTypeKey.String("Create") - // patch - DBCosmosDBOperationTypePatch = DBCosmosDBOperationTypeKey.String("Patch") - // read - DBCosmosDBOperationTypeRead = DBCosmosDBOperationTypeKey.String("Read") - // read_feed - DBCosmosDBOperationTypeReadFeed = DBCosmosDBOperationTypeKey.String("ReadFeed") - // delete - DBCosmosDBOperationTypeDelete = DBCosmosDBOperationTypeKey.String("Delete") - // replace - DBCosmosDBOperationTypeReplace = DBCosmosDBOperationTypeKey.String("Replace") - // execute - DBCosmosDBOperationTypeExecute = DBCosmosDBOperationTypeKey.String("Execute") - // query - DBCosmosDBOperationTypeQuery = DBCosmosDBOperationTypeKey.String("Query") - // head - DBCosmosDBOperationTypeHead = DBCosmosDBOperationTypeKey.String("Head") - // head_feed - DBCosmosDBOperationTypeHeadFeed = DBCosmosDBOperationTypeKey.String("HeadFeed") - // upsert - DBCosmosDBOperationTypeUpsert = DBCosmosDBOperationTypeKey.String("Upsert") - // batch - DBCosmosDBOperationTypeBatch = DBCosmosDBOperationTypeKey.String("Batch") - // query_plan - DBCosmosDBOperationTypeQueryPlan = DBCosmosDBOperationTypeKey.String("QueryPlan") - // execute_javascript - DBCosmosDBOperationTypeExecuteJavascript = DBCosmosDBOperationTypeKey.String("ExecuteJavaScript") -) - -// DBCosmosDBClientID returns an attribute KeyValue conforming to the -// "db.cosmosdb.client_id" semantic conventions. It represents the unique -// Cosmos client instance id. -func DBCosmosDBClientID(val string) attribute.KeyValue { - return DBCosmosDBClientIDKey.String(val) -} - -// DBCosmosDBRequestCharge returns an attribute KeyValue conforming to the -// "db.cosmosdb.request_charge" semantic conventions. It represents the rU -// consumed for that operation -func DBCosmosDBRequestCharge(val float64) attribute.KeyValue { - return DBCosmosDBRequestChargeKey.Float64(val) -} - -// DBCosmosDBRequestContentLength returns an attribute KeyValue conforming -// to the "db.cosmosdb.request_content_length" semantic conventions. It -// represents the request payload size in bytes -func DBCosmosDBRequestContentLength(val int) attribute.KeyValue { - return DBCosmosDBRequestContentLengthKey.Int(val) -} - -// DBCosmosDBStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.status_code" semantic conventions. It represents the cosmos DB -// status code. -func DBCosmosDBStatusCode(val int) attribute.KeyValue { - return DBCosmosDBStatusCodeKey.Int(val) -} - -// DBCosmosDBSubStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.sub_status_code" semantic conventions. It represents the cosmos -// DB sub status code. -func DBCosmosDBSubStatusCode(val int) attribute.KeyValue { - return DBCosmosDBSubStatusCodeKey.Int(val) -} - -// This group defines attributes for Elasticsearch. -const ( - // DBElasticsearchClusterNameKey is the attribute Key conforming to the - // "db.elasticsearch.cluster.name" semantic conventions. It represents the - // represents the identifier of an Elasticsearch cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'e9106fc68e3044f0b1475b04bf4ffd5f' - DBElasticsearchClusterNameKey = attribute.Key("db.elasticsearch.cluster.name") - - // DBElasticsearchNodeNameKey is the attribute Key conforming to the - // "db.elasticsearch.node.name" semantic conventions. It represents the - // represents the human-readable identifier of the node/instance to which a - // request was routed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'instance-0000000001' - DBElasticsearchNodeNameKey = attribute.Key("db.elasticsearch.node.name") -) - -// DBElasticsearchClusterName returns an attribute KeyValue conforming to -// the "db.elasticsearch.cluster.name" semantic conventions. It represents the -// represents the identifier of an Elasticsearch cluster. -func DBElasticsearchClusterName(val string) attribute.KeyValue { - return DBElasticsearchClusterNameKey.String(val) -} - -// DBElasticsearchNodeName returns an attribute KeyValue conforming to the -// "db.elasticsearch.node.name" semantic conventions. It represents the -// represents the human-readable identifier of the node/instance to which a -// request was routed. -func DBElasticsearchNodeName(val string) attribute.KeyValue { - return DBElasticsearchNodeNameKey.String(val) -} - -// Attributes for software deployments. -const ( - // DeploymentEnvironmentKey is the attribute Key conforming to the - // "deployment.environment" semantic conventions. It represents the name of - // the [deployment - // environment](https://wikipedia.org/wiki/Deployment_environment) (aka - // deployment tier). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'staging', 'production' - // Note: `deployment.environment` does not affect the uniqueness - // constraints defined through - // the `service.namespace`, `service.name` and `service.instance.id` - // resource attributes. - // This implies that resources carrying the following attribute - // combinations MUST be - // considered to be identifying the same service: - // - // * `service.name=frontend`, `deployment.environment=production` - // * `service.name=frontend`, `deployment.environment=staging`. - DeploymentEnvironmentKey = attribute.Key("deployment.environment") -) - -// DeploymentEnvironment returns an attribute KeyValue conforming to the -// "deployment.environment" semantic conventions. It represents the name of the -// [deployment environment](https://wikipedia.org/wiki/Deployment_environment) -// (aka deployment tier). -func DeploymentEnvironment(val string) attribute.KeyValue { - return DeploymentEnvironmentKey.String(val) -} - -// Attributes that represents an occurrence of a lifecycle transition on the -// Android platform. -const ( - // AndroidStateKey is the attribute Key conforming to the "android.state" - // semantic conventions. It represents the deprecated use the - // `device.app.lifecycle` event definition including `android.state` as a - // payload field instead. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The Android lifecycle states are defined in [Activity lifecycle - // callbacks](https://developer.android.com/guide/components/activities/activity-lifecycle#lc), - // and from which the `OS identifiers` are derived. - AndroidStateKey = attribute.Key("android.state") -) - -var ( - // Any time before Activity.onResume() or, if the app has no Activity, Context.startService() has been called in the app for the first time - AndroidStateCreated = AndroidStateKey.String("created") - // Any time after Activity.onPause() or, if the app has no Activity, Context.stopService() has been called when the app was in the foreground state - AndroidStateBackground = AndroidStateKey.String("background") - // Any time after Activity.onResume() or, if the app has no Activity, Context.startService() has been called when the app was in either the created or background states - AndroidStateForeground = AndroidStateKey.String("foreground") -) - -// These attributes may be used to describe the receiver of a network -// exchange/packet. These should be used when there is no client/server -// relationship between the two sides, or when that relationship is unknown. -// This covers low-level network interactions (e.g. packet tracing) where you -// don't know if there was a connection or which side initiated it. This also -// covers unidirectional UDP flows and peer-to-peer communication where the -// "user-facing" surface of the protocol / API doesn't expose a clear notion of -// client and server. -const ( - // DestinationAddressKey is the attribute Key conforming to the - // "destination.address" semantic conventions. It represents the - // destination address - domain name if available without reverse DNS - // lookup; otherwise, IP address or Unix domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'destination.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the source side, and when communicating through - // an intermediary, `destination.address` SHOULD represent the destination - // address behind any intermediaries, for example proxies, if it's - // available. - DestinationAddressKey = attribute.Key("destination.address") - - // DestinationPortKey is the attribute Key conforming to the - // "destination.port" semantic conventions. It represents the destination - // port number - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3389, 2888 - DestinationPortKey = attribute.Key("destination.port") -) - -// DestinationAddress returns an attribute KeyValue conforming to the -// "destination.address" semantic conventions. It represents the destination -// address - domain name if available without reverse DNS lookup; otherwise, IP -// address or Unix domain socket name. -func DestinationAddress(val string) attribute.KeyValue { - return DestinationAddressKey.String(val) -} - -// DestinationPort returns an attribute KeyValue conforming to the -// "destination.port" semantic conventions. It represents the destination port -// number -func DestinationPort(val int) attribute.KeyValue { - return DestinationPortKey.Int(val) -} - -// Describes device attributes. -const ( - // DeviceIDKey is the attribute Key conforming to the "device.id" semantic - // conventions. It represents a unique identifier representing the device - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' - // Note: The device identifier MUST only be defined using the values - // outlined below. This value is not an advertising identifier and MUST NOT - // be used as such. On iOS (Swift or Objective-C), this value MUST be equal - // to the [vendor - // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). - // On Android (Java or Kotlin), this value MUST be equal to the Firebase - // Installation ID or a globally unique UUID which is persisted across - // sessions in your application. More information can be found - // [here](https://developer.android.com/training/articles/user-data-ids) on - // best practices and exact implementation details. Caution should be taken - // when storing personal data or anything which can identify a user. GDPR - // and data protection laws may apply, ensure you do your own due - // diligence. - DeviceIDKey = attribute.Key("device.id") - - // DeviceManufacturerKey is the attribute Key conforming to the - // "device.manufacturer" semantic conventions. It represents the name of - // the device manufacturer - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Apple', 'Samsung' - // Note: The Android OS provides this field via - // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). - // iOS apps SHOULD hardcode the value `Apple`. - DeviceManufacturerKey = attribute.Key("device.manufacturer") - - // DeviceModelIdentifierKey is the attribute Key conforming to the - // "device.model.identifier" semantic conventions. It represents the model - // identifier for the device - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iPhone3,4', 'SM-G920F' - // Note: It's recommended this value represents a machine-readable version - // of the model identifier rather than the market or consumer-friendly name - // of the device. - DeviceModelIdentifierKey = attribute.Key("device.model.identifier") - - // DeviceModelNameKey is the attribute Key conforming to the - // "device.model.name" semantic conventions. It represents the marketing - // name for the device model - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' - // Note: It's recommended this value represents a human-readable version of - // the device model rather than a machine-readable alternative. - DeviceModelNameKey = attribute.Key("device.model.name") -) - -// DeviceID returns an attribute KeyValue conforming to the "device.id" -// semantic conventions. It represents a unique identifier representing the -// device -func DeviceID(val string) attribute.KeyValue { - return DeviceIDKey.String(val) -} - -// DeviceManufacturer returns an attribute KeyValue conforming to the -// "device.manufacturer" semantic conventions. It represents the name of the -// device manufacturer -func DeviceManufacturer(val string) attribute.KeyValue { - return DeviceManufacturerKey.String(val) -} - -// DeviceModelIdentifier returns an attribute KeyValue conforming to the -// "device.model.identifier" semantic conventions. It represents the model -// identifier for the device -func DeviceModelIdentifier(val string) attribute.KeyValue { - return DeviceModelIdentifierKey.String(val) -} - -// DeviceModelName returns an attribute KeyValue conforming to the -// "device.model.name" semantic conventions. It represents the marketing name -// for the device model -func DeviceModelName(val string) attribute.KeyValue { - return DeviceModelNameKey.String(val) -} - -// These attributes may be used for any disk related operation. -const ( - // DiskIoDirectionKey is the attribute Key conforming to the - // "disk.io.direction" semantic conventions. It represents the disk IO - // operation direction. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'read' - DiskIoDirectionKey = attribute.Key("disk.io.direction") -) - -var ( - // read - DiskIoDirectionRead = DiskIoDirectionKey.String("read") - // write - DiskIoDirectionWrite = DiskIoDirectionKey.String("write") -) - -// The shared attributes used to report a DNS query. -const ( - // DNSQuestionNameKey is the attribute Key conforming to the - // "dns.question.name" semantic conventions. It represents the name being - // queried. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'www.example.com', 'opentelemetry.io' - // Note: If the name field contains non-printable characters (below 32 or - // above 126), those characters should be represented as escaped base 10 - // integers (\DDD). Back slashes and quotes should be escaped. Tabs, - // carriage returns, and line feeds should be converted to \t, \r, and \n - // respectively. - DNSQuestionNameKey = attribute.Key("dns.question.name") -) - -// DNSQuestionName returns an attribute KeyValue conforming to the -// "dns.question.name" semantic conventions. It represents the name being -// queried. -func DNSQuestionName(val string) attribute.KeyValue { - return DNSQuestionNameKey.String(val) -} - -// Attributes for operations with an authenticated and/or authorized enduser. -const ( - // EnduserIDKey is the attribute Key conforming to the "enduser.id" - // semantic conventions. It represents the username or client_id extracted - // from the access token or - // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header - // in the inbound request from outside the system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'username' - EnduserIDKey = attribute.Key("enduser.id") - - // EnduserRoleKey is the attribute Key conforming to the "enduser.role" - // semantic conventions. It represents the actual/assumed role the client - // is making the request under extracted from token or application security - // context. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'admin' - EnduserRoleKey = attribute.Key("enduser.role") - - // EnduserScopeKey is the attribute Key conforming to the "enduser.scope" - // semantic conventions. It represents the scopes or granted authorities - // the client currently possesses extracted from token or application - // security context. The value would come from the scope associated with an - // [OAuth 2.0 Access - // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute - // value in a [SAML 2.0 - // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'read:message, write:files' - EnduserScopeKey = attribute.Key("enduser.scope") -) - -// EnduserID returns an attribute KeyValue conforming to the "enduser.id" -// semantic conventions. It represents the username or client_id extracted from -// the access token or -// [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in -// the inbound request from outside the system. -func EnduserID(val string) attribute.KeyValue { - return EnduserIDKey.String(val) -} - -// EnduserRole returns an attribute KeyValue conforming to the -// "enduser.role" semantic conventions. It represents the actual/assumed role -// the client is making the request under extracted from token or application -// security context. -func EnduserRole(val string) attribute.KeyValue { - return EnduserRoleKey.String(val) -} - -// EnduserScope returns an attribute KeyValue conforming to the -// "enduser.scope" semantic conventions. It represents the scopes or granted -// authorities the client currently possesses extracted from token or -// application security context. The value would come from the scope associated -// with an [OAuth 2.0 Access -// Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute -// value in a [SAML 2.0 -// Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). -func EnduserScope(val string) attribute.KeyValue { - return EnduserScopeKey.String(val) -} - -// The shared attributes used to report an error. -const ( - // ErrorTypeKey is the attribute Key conforming to the "error.type" - // semantic conventions. It represents the describes a class of error the - // operation ended with. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'timeout', 'java.net.UnknownHostException', - // 'server_certificate_invalid', '500' - // Note: The `error.type` SHOULD be predictable, and SHOULD have low - // cardinality. - // - // When `error.type` is set to a type (e.g., an exception type), its - // canonical class name identifying the type within the artifact SHOULD be - // used. - // - // Instrumentations SHOULD document the list of errors they report. - // - // The cardinality of `error.type` within one instrumentation library - // SHOULD be low. - // Telemetry consumers that aggregate data from multiple instrumentation - // libraries and applications - // should be prepared for `error.type` to have high cardinality at query - // time when no - // additional filters are applied. - // - // If the operation has completed successfully, instrumentations SHOULD NOT - // set `error.type`. - // - // If a specific domain defines its own set of error identifiers (such as - // HTTP or gRPC status codes), - // it's RECOMMENDED to: - // - // * Use a domain-specific attribute - // * Set `error.type` to capture all errors, regardless of whether they are - // defined within the domain-specific set or not. - ErrorTypeKey = attribute.Key("error.type") -) - -var ( - // A fallback error value to be used when the instrumentation doesn't define a custom value - ErrorTypeOther = ErrorTypeKey.String("_OTHER") -) - -// Attributes for Events represented using Log Records. -const ( - // EventNameKey is the attribute Key conforming to the "event.name" - // semantic conventions. It represents the identifies the class / type of - // event. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'browser.mouse.click', 'device.app.lifecycle' - // Note: Event names are subject to the same rules as [attribute - // names](https://github.com/open-telemetry/opentelemetry-specification/tree/v1.33.0/specification/common/attribute-naming.md). - // Notably, event names are namespaced to avoid collisions and provide a - // clean separation of semantics for events in separate domains like - // browser, mobile, and kubernetes. - EventNameKey = attribute.Key("event.name") -) - -// EventName returns an attribute KeyValue conforming to the "event.name" -// semantic conventions. It represents the identifies the class / type of -// event. -func EventName(val string) attribute.KeyValue { - return EventNameKey.String(val) -} - -// The shared attributes used to report a single exception associated with a -// span or log. -const ( - // ExceptionEscapedKey is the attribute Key conforming to the - // "exception.escaped" semantic conventions. It represents the sHOULD be - // set to true if the exception event is recorded at a point where it is - // known that the exception is escaping the scope of the span. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Note: An exception is considered to have escaped (or left) the scope of - // a span, - // if that span is ended while the exception is still logically "in - // flight". - // This may be actually "in flight" in some languages (e.g. if the - // exception - // is passed to a Context manager's `__exit__` method in Python) but will - // usually be caught at the point of recording the exception in most - // languages. - // - // It is usually not possible to determine at the point where an exception - // is thrown - // whether it will escape the scope of a span. - // However, it is trivial to know that an exception - // will escape, if one checks for an active exception just before ending - // the span, - // as done in the [example for recording span - // exceptions](https://opentelemetry.io/docs/specs/semconv/exceptions/exceptions-spans/#recording-an-exception). - // - // It follows that an exception may still escape the scope of the span - // even if the `exception.escaped` attribute was not set or set to false, - // since the event might have been recorded at a time where it was not - // clear whether the exception will escape. - ExceptionEscapedKey = attribute.Key("exception.escaped") - - // ExceptionMessageKey is the attribute Key conforming to the - // "exception.message" semantic conventions. It represents the exception - // message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Division by zero', "Can't convert 'int' object to str - // implicitly" - ExceptionMessageKey = attribute.Key("exception.message") - - // ExceptionStacktraceKey is the attribute Key conforming to the - // "exception.stacktrace" semantic conventions. It represents a stacktrace - // as a string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Exception in thread "main" java.lang.RuntimeException: Test - // exception\\n at ' - // 'com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - ExceptionStacktraceKey = attribute.Key("exception.stacktrace") - - // ExceptionTypeKey is the attribute Key conforming to the "exception.type" - // semantic conventions. It represents the type of the exception (its - // fully-qualified class name, if applicable). The dynamic type of the - // exception should be preferred over the static type in languages that - // support it. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'java.net.ConnectException', 'OSError' - ExceptionTypeKey = attribute.Key("exception.type") -) - -// ExceptionEscaped returns an attribute KeyValue conforming to the -// "exception.escaped" semantic conventions. It represents the sHOULD be set to -// true if the exception event is recorded at a point where it is known that -// the exception is escaping the scope of the span. -func ExceptionEscaped(val bool) attribute.KeyValue { - return ExceptionEscapedKey.Bool(val) -} - -// ExceptionMessage returns an attribute KeyValue conforming to the -// "exception.message" semantic conventions. It represents the exception -// message. -func ExceptionMessage(val string) attribute.KeyValue { - return ExceptionMessageKey.String(val) -} - -// ExceptionStacktrace returns an attribute KeyValue conforming to the -// "exception.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func ExceptionStacktrace(val string) attribute.KeyValue { - return ExceptionStacktraceKey.String(val) -} - -// ExceptionType returns an attribute KeyValue conforming to the -// "exception.type" semantic conventions. It represents the type of the -// exception (its fully-qualified class name, if applicable). The dynamic type -// of the exception should be preferred over the static type in languages that -// support it. -func ExceptionType(val string) attribute.KeyValue { - return ExceptionTypeKey.String(val) -} - -// FaaS attributes -const ( - // FaaSColdstartKey is the attribute Key conforming to the "faas.coldstart" - // semantic conventions. It represents a boolean that is true if the - // serverless function is executed for the first time (aka cold-start). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - FaaSColdstartKey = attribute.Key("faas.coldstart") - - // FaaSCronKey is the attribute Key conforming to the "faas.cron" semantic - // conventions. It represents a string containing the schedule period as - // [Cron - // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0/5 * * * ? *' - FaaSCronKey = attribute.Key("faas.cron") - - // FaaSDocumentCollectionKey is the attribute Key conforming to the - // "faas.document.collection" semantic conventions. It represents the name - // of the source on which the triggering operation was performed. For - // example, in Cloud Storage or S3 corresponds to the bucket name, and in - // Cosmos DB to the database name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myBucketName', 'myDBName' - FaaSDocumentCollectionKey = attribute.Key("faas.document.collection") - - // FaaSDocumentNameKey is the attribute Key conforming to the - // "faas.document.name" semantic conventions. It represents the document - // name/table subjected to the operation. For example, in Cloud Storage or - // S3 is the name of the file, and in Cosmos DB the table name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myFile.txt', 'myTableName' - FaaSDocumentNameKey = attribute.Key("faas.document.name") - - // FaaSDocumentOperationKey is the attribute Key conforming to the - // "faas.document.operation" semantic conventions. It represents the - // describes the type of the operation that was performed on the data. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - FaaSDocumentOperationKey = attribute.Key("faas.document.operation") - - // FaaSDocumentTimeKey is the attribute Key conforming to the - // "faas.document.time" semantic conventions. It represents a string - // containing the time when the data was accessed in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2020-01-23T13:47:06Z' - FaaSDocumentTimeKey = attribute.Key("faas.document.time") - - // FaaSInstanceKey is the attribute Key conforming to the "faas.instance" - // semantic conventions. It represents the execution environment ID as a - // string, that will be potentially reused for other invocations to the - // same function/function version. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021/06/28/[$LATEST]2f399eb14537447da05ab2a2e39309de' - // Note: * **AWS Lambda:** Use the (full) log stream name. - FaaSInstanceKey = attribute.Key("faas.instance") - - // FaaSInvocationIDKey is the attribute Key conforming to the - // "faas.invocation_id" semantic conventions. It represents the invocation - // ID of the current function invocation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'af9d5aa4-a685-4c5f-a22b-444f80b3cc28' - FaaSInvocationIDKey = attribute.Key("faas.invocation_id") - - // FaaSInvokedNameKey is the attribute Key conforming to the - // "faas.invoked_name" semantic conventions. It represents the name of the - // invoked function. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-function' - // Note: SHOULD be equal to the `faas.name` resource attribute of the - // invoked function. - FaaSInvokedNameKey = attribute.Key("faas.invoked_name") - - // FaaSInvokedProviderKey is the attribute Key conforming to the - // "faas.invoked_provider" semantic conventions. It represents the cloud - // provider of the invoked function. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: SHOULD be equal to the `cloud.provider` resource attribute of the - // invoked function. - FaaSInvokedProviderKey = attribute.Key("faas.invoked_provider") - - // FaaSInvokedRegionKey is the attribute Key conforming to the - // "faas.invoked_region" semantic conventions. It represents the cloud - // region of the invoked function. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'eu-central-1' - // Note: SHOULD be equal to the `cloud.region` resource attribute of the - // invoked function. - FaaSInvokedRegionKey = attribute.Key("faas.invoked_region") - - // FaaSMaxMemoryKey is the attribute Key conforming to the - // "faas.max_memory" semantic conventions. It represents the amount of - // memory available to the serverless function converted to Bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 134217728 - // Note: It's recommended to set this attribute since e.g. too little - // memory can easily stop a Java AWS Lambda function from working - // correctly. On AWS Lambda, the environment variable - // `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information (which must - // be multiplied by 1,048,576). - FaaSMaxMemoryKey = attribute.Key("faas.max_memory") - - // FaaSNameKey is the attribute Key conforming to the "faas.name" semantic - // conventions. It represents the name of the single function that this - // runtime instance executes. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-function', 'myazurefunctionapp/some-function-name' - // Note: This is the name of the function as configured/deployed on the - // FaaS - // platform and is usually different from the name of the callback - // function (which may be stored in the - // [`code.namespace`/`code.function`](/docs/general/attributes.md#source-code-attributes) - // span attributes). - // - // For some cloud providers, the above definition is ambiguous. The - // following - // definition of function name MUST be used for this attribute - // (and consequently the span name) for the listed cloud - // providers/products: - // - // * **Azure:** The full name `/`, i.e., function app name - // followed by a forward slash followed by the function name (this form - // can also be seen in the resource JSON for the function). - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider (see also the `cloud.resource_id` attribute). - FaaSNameKey = attribute.Key("faas.name") - - // FaaSTimeKey is the attribute Key conforming to the "faas.time" semantic - // conventions. It represents a string containing the function invocation - // time in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2020-01-23T13:47:06Z' - FaaSTimeKey = attribute.Key("faas.time") - - // FaaSTriggerKey is the attribute Key conforming to the "faas.trigger" - // semantic conventions. It represents the type of the trigger which caused - // this function invocation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - FaaSTriggerKey = attribute.Key("faas.trigger") - - // FaaSVersionKey is the attribute Key conforming to the "faas.version" - // semantic conventions. It represents the immutable version of the - // function being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '26', 'pinkfroid-00002' - // Note: Depending on the cloud provider and platform, use: - // - // * **AWS Lambda:** The [function - // version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - // (an integer represented as a decimal string). - // * **Google Cloud Run (Services):** The - // [revision](https://cloud.google.com/run/docs/managing/revisions) - // (i.e., the function name plus the revision suffix). - // * **Google Cloud Functions:** The value of the - // [`K_REVISION` environment - // variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - // * **Azure Functions:** Not applicable. Do not set this attribute. - FaaSVersionKey = attribute.Key("faas.version") -) - -var ( - // When a new object is created - FaaSDocumentOperationInsert = FaaSDocumentOperationKey.String("insert") - // When an object is modified - FaaSDocumentOperationEdit = FaaSDocumentOperationKey.String("edit") - // When an object is deleted - FaaSDocumentOperationDelete = FaaSDocumentOperationKey.String("delete") -) - -var ( - // Alibaba Cloud - FaaSInvokedProviderAlibabaCloud = FaaSInvokedProviderKey.String("alibaba_cloud") - // Amazon Web Services - FaaSInvokedProviderAWS = FaaSInvokedProviderKey.String("aws") - // Microsoft Azure - FaaSInvokedProviderAzure = FaaSInvokedProviderKey.String("azure") - // Google Cloud Platform - FaaSInvokedProviderGCP = FaaSInvokedProviderKey.String("gcp") - // Tencent Cloud - FaaSInvokedProviderTencentCloud = FaaSInvokedProviderKey.String("tencent_cloud") -) - -var ( - // A response to some data source operation such as a database or filesystem read/write - FaaSTriggerDatasource = FaaSTriggerKey.String("datasource") - // To provide an answer to an inbound HTTP request - FaaSTriggerHTTP = FaaSTriggerKey.String("http") - // A function is set to be executed when messages are sent to a messaging system - FaaSTriggerPubsub = FaaSTriggerKey.String("pubsub") - // A function is scheduled to be executed regularly - FaaSTriggerTimer = FaaSTriggerKey.String("timer") - // If none of the others apply - FaaSTriggerOther = FaaSTriggerKey.String("other") -) - -// FaaSColdstart returns an attribute KeyValue conforming to the -// "faas.coldstart" semantic conventions. It represents a boolean that is true -// if the serverless function is executed for the first time (aka cold-start). -func FaaSColdstart(val bool) attribute.KeyValue { - return FaaSColdstartKey.Bool(val) -} - -// FaaSCron returns an attribute KeyValue conforming to the "faas.cron" -// semantic conventions. It represents a string containing the schedule period -// as [Cron -// Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). -func FaaSCron(val string) attribute.KeyValue { - return FaaSCronKey.String(val) -} - -// FaaSDocumentCollection returns an attribute KeyValue conforming to the -// "faas.document.collection" semantic conventions. It represents the name of -// the source on which the triggering operation was performed. For example, in -// Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the -// database name. -func FaaSDocumentCollection(val string) attribute.KeyValue { - return FaaSDocumentCollectionKey.String(val) -} - -// FaaSDocumentName returns an attribute KeyValue conforming to the -// "faas.document.name" semantic conventions. It represents the document -// name/table subjected to the operation. For example, in Cloud Storage or S3 -// is the name of the file, and in Cosmos DB the table name. -func FaaSDocumentName(val string) attribute.KeyValue { - return FaaSDocumentNameKey.String(val) -} - -// FaaSDocumentTime returns an attribute KeyValue conforming to the -// "faas.document.time" semantic conventions. It represents a string containing -// the time when the data was accessed in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSDocumentTime(val string) attribute.KeyValue { - return FaaSDocumentTimeKey.String(val) -} - -// FaaSInstance returns an attribute KeyValue conforming to the -// "faas.instance" semantic conventions. It represents the execution -// environment ID as a string, that will be potentially reused for other -// invocations to the same function/function version. -func FaaSInstance(val string) attribute.KeyValue { - return FaaSInstanceKey.String(val) -} - -// FaaSInvocationID returns an attribute KeyValue conforming to the -// "faas.invocation_id" semantic conventions. It represents the invocation ID -// of the current function invocation. -func FaaSInvocationID(val string) attribute.KeyValue { - return FaaSInvocationIDKey.String(val) -} - -// FaaSInvokedName returns an attribute KeyValue conforming to the -// "faas.invoked_name" semantic conventions. It represents the name of the -// invoked function. -func FaaSInvokedName(val string) attribute.KeyValue { - return FaaSInvokedNameKey.String(val) -} - -// FaaSInvokedRegion returns an attribute KeyValue conforming to the -// "faas.invoked_region" semantic conventions. It represents the cloud region -// of the invoked function. -func FaaSInvokedRegion(val string) attribute.KeyValue { - return FaaSInvokedRegionKey.String(val) -} - -// FaaSMaxMemory returns an attribute KeyValue conforming to the -// "faas.max_memory" semantic conventions. It represents the amount of memory -// available to the serverless function converted to Bytes. -func FaaSMaxMemory(val int) attribute.KeyValue { - return FaaSMaxMemoryKey.Int(val) -} - -// FaaSName returns an attribute KeyValue conforming to the "faas.name" -// semantic conventions. It represents the name of the single function that -// this runtime instance executes. -func FaaSName(val string) attribute.KeyValue { - return FaaSNameKey.String(val) -} - -// FaaSTime returns an attribute KeyValue conforming to the "faas.time" -// semantic conventions. It represents a string containing the function -// invocation time in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSTime(val string) attribute.KeyValue { - return FaaSTimeKey.String(val) -} - -// FaaSVersion returns an attribute KeyValue conforming to the -// "faas.version" semantic conventions. It represents the immutable version of -// the function being executed. -func FaaSVersion(val string) attribute.KeyValue { - return FaaSVersionKey.String(val) -} - -// Attributes for Feature Flags. -const ( - // FeatureFlagKeyKey is the attribute Key conforming to the - // "feature_flag.key" semantic conventions. It represents the unique - // identifier of the feature flag. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'logo-color' - FeatureFlagKeyKey = attribute.Key("feature_flag.key") - - // FeatureFlagProviderNameKey is the attribute Key conforming to the - // "feature_flag.provider_name" semantic conventions. It represents the - // name of the service provider that performs the flag evaluation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Flag Manager' - FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") - - // FeatureFlagVariantKey is the attribute Key conforming to the - // "feature_flag.variant" semantic conventions. It represents the sHOULD be - // a semantic identifier for a value. If one is unavailable, a stringified - // version of the value can be used. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'red', 'true', 'on' - // Note: A semantic identifier, commonly referred to as a variant, provides - // a means - // for referring to a value without including the value itself. This can - // provide additional context for understanding the meaning behind a value. - // For example, the variant `red` maybe be used for the value `#c05543`. - // - // A stringified version of the value can be used in situations where a - // semantic identifier is unavailable. String representation of the value - // should be determined by the implementer. - FeatureFlagVariantKey = attribute.Key("feature_flag.variant") -) - -// FeatureFlagKey returns an attribute KeyValue conforming to the -// "feature_flag.key" semantic conventions. It represents the unique identifier -// of the feature flag. -func FeatureFlagKey(val string) attribute.KeyValue { - return FeatureFlagKeyKey.String(val) -} - -// FeatureFlagProviderName returns an attribute KeyValue conforming to the -// "feature_flag.provider_name" semantic conventions. It represents the name of -// the service provider that performs the flag evaluation. -func FeatureFlagProviderName(val string) attribute.KeyValue { - return FeatureFlagProviderNameKey.String(val) -} - -// FeatureFlagVariant returns an attribute KeyValue conforming to the -// "feature_flag.variant" semantic conventions. It represents the sHOULD be a -// semantic identifier for a value. If one is unavailable, a stringified -// version of the value can be used. -func FeatureFlagVariant(val string) attribute.KeyValue { - return FeatureFlagVariantKey.String(val) -} - -// Describes file attributes. -const ( - // FileDirectoryKey is the attribute Key conforming to the "file.directory" - // semantic conventions. It represents the directory where the file is - // located. It should include the drive letter, when appropriate. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/home/user', 'C:\\Program Files\\MyApp' - FileDirectoryKey = attribute.Key("file.directory") - - // FileExtensionKey is the attribute Key conforming to the "file.extension" - // semantic conventions. It represents the file extension, excluding the - // leading dot. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'png', 'gz' - // Note: When the file name has multiple extensions (example.tar.gz), only - // the last one should be captured ("gz", not "tar.gz"). - FileExtensionKey = attribute.Key("file.extension") - - // FileNameKey is the attribute Key conforming to the "file.name" semantic - // conventions. It represents the name of the file including the extension, - // without the directory. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'example.png' - FileNameKey = attribute.Key("file.name") - - // FilePathKey is the attribute Key conforming to the "file.path" semantic - // conventions. It represents the full path to the file, including the file - // name. It should include the drive letter, when appropriate. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/home/alice/example.png', 'C:\\Program - // Files\\MyApp\\myapp.exe' - FilePathKey = attribute.Key("file.path") - - // FileSizeKey is the attribute Key conforming to the "file.size" semantic - // conventions. It represents the file size in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - FileSizeKey = attribute.Key("file.size") -) - -// FileDirectory returns an attribute KeyValue conforming to the -// "file.directory" semantic conventions. It represents the directory where the -// file is located. It should include the drive letter, when appropriate. -func FileDirectory(val string) attribute.KeyValue { - return FileDirectoryKey.String(val) -} - -// FileExtension returns an attribute KeyValue conforming to the -// "file.extension" semantic conventions. It represents the file extension, -// excluding the leading dot. -func FileExtension(val string) attribute.KeyValue { - return FileExtensionKey.String(val) -} - -// FileName returns an attribute KeyValue conforming to the "file.name" -// semantic conventions. It represents the name of the file including the -// extension, without the directory. -func FileName(val string) attribute.KeyValue { - return FileNameKey.String(val) -} - -// FilePath returns an attribute KeyValue conforming to the "file.path" -// semantic conventions. It represents the full path to the file, including the -// file name. It should include the drive letter, when appropriate. -func FilePath(val string) attribute.KeyValue { - return FilePathKey.String(val) -} - -// FileSize returns an attribute KeyValue conforming to the "file.size" -// semantic conventions. It represents the file size in bytes. -func FileSize(val int) attribute.KeyValue { - return FileSizeKey.Int(val) -} - -// Attributes for Google Cloud Run. -const ( - // GCPCloudRunJobExecutionKey is the attribute Key conforming to the - // "gcp.cloud_run.job.execution" semantic conventions. It represents the - // name of the Cloud Run - // [execution](https://cloud.google.com/run/docs/managing/job-executions) - // being run for the Job, as set by the - // [`CLOUD_RUN_EXECUTION`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) - // environment variable. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'job-name-xxxx', 'sample-job-mdw84' - GCPCloudRunJobExecutionKey = attribute.Key("gcp.cloud_run.job.execution") - - // GCPCloudRunJobTaskIndexKey is the attribute Key conforming to the - // "gcp.cloud_run.job.task_index" semantic conventions. It represents the - // index for a task within an execution as provided by the - // [`CLOUD_RUN_TASK_INDEX`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) - // environment variable. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 1 - GCPCloudRunJobTaskIndexKey = attribute.Key("gcp.cloud_run.job.task_index") -) - -// GCPCloudRunJobExecution returns an attribute KeyValue conforming to the -// "gcp.cloud_run.job.execution" semantic conventions. It represents the name -// of the Cloud Run -// [execution](https://cloud.google.com/run/docs/managing/job-executions) being -// run for the Job, as set by the -// [`CLOUD_RUN_EXECUTION`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) -// environment variable. -func GCPCloudRunJobExecution(val string) attribute.KeyValue { - return GCPCloudRunJobExecutionKey.String(val) -} - -// GCPCloudRunJobTaskIndex returns an attribute KeyValue conforming to the -// "gcp.cloud_run.job.task_index" semantic conventions. It represents the index -// for a task within an execution as provided by the -// [`CLOUD_RUN_TASK_INDEX`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) -// environment variable. -func GCPCloudRunJobTaskIndex(val int) attribute.KeyValue { - return GCPCloudRunJobTaskIndexKey.Int(val) -} - -// Attributes for Google Compute Engine (GCE). -const ( - // GCPGceInstanceHostnameKey is the attribute Key conforming to the - // "gcp.gce.instance.hostname" semantic conventions. It represents the - // hostname of a GCE instance. This is the full value of the default or - // [custom - // hostname](https://cloud.google.com/compute/docs/instances/custom-hostname-vm). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-host1234.example.com', - // 'sample-vm.us-west1-b.c.my-project.internal' - GCPGceInstanceHostnameKey = attribute.Key("gcp.gce.instance.hostname") - - // GCPGceInstanceNameKey is the attribute Key conforming to the - // "gcp.gce.instance.name" semantic conventions. It represents the instance - // name of a GCE instance. This is the value provided by `host.name`, the - // visible name of the instance in the Cloud Console UI, and the prefix for - // the default hostname of the instance as defined by the [default internal - // DNS - // name](https://cloud.google.com/compute/docs/internal-dns#instance-fully-qualified-domain-names). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'instance-1', 'my-vm-name' - GCPGceInstanceNameKey = attribute.Key("gcp.gce.instance.name") -) - -// GCPGceInstanceHostname returns an attribute KeyValue conforming to the -// "gcp.gce.instance.hostname" semantic conventions. It represents the hostname -// of a GCE instance. This is the full value of the default or [custom -// hostname](https://cloud.google.com/compute/docs/instances/custom-hostname-vm). -func GCPGceInstanceHostname(val string) attribute.KeyValue { - return GCPGceInstanceHostnameKey.String(val) -} - -// GCPGceInstanceName returns an attribute KeyValue conforming to the -// "gcp.gce.instance.name" semantic conventions. It represents the instance -// name of a GCE instance. This is the value provided by `host.name`, the -// visible name of the instance in the Cloud Console UI, and the prefix for the -// default hostname of the instance as defined by the [default internal DNS -// name](https://cloud.google.com/compute/docs/internal-dns#instance-fully-qualified-domain-names). -func GCPGceInstanceName(val string) attribute.KeyValue { - return GCPGceInstanceNameKey.String(val) -} - -// The attributes used to describe telemetry in the context of LLM (Large -// Language Models) requests and responses. -const ( - // GenAiCompletionKey is the attribute Key conforming to the - // "gen_ai.completion" semantic conventions. It represents the full - // response received from the LLM. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: "[{'role': 'assistant', 'content': 'The capital of France is - // Paris.'}]" - // Note: It's RECOMMENDED to format completions as JSON string matching - // [OpenAI messages - // format](https://platform.openai.com/docs/guides/text-generation) - GenAiCompletionKey = attribute.Key("gen_ai.completion") - - // GenAiPromptKey is the attribute Key conforming to the "gen_ai.prompt" - // semantic conventions. It represents the full prompt sent to an LLM. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: "[{'role': 'user', 'content': 'What is the capital of - // France?'}]" - // Note: It's RECOMMENDED to format prompts as JSON string matching [OpenAI - // messages - // format](https://platform.openai.com/docs/guides/text-generation) - GenAiPromptKey = attribute.Key("gen_ai.prompt") - - // GenAiRequestMaxTokensKey is the attribute Key conforming to the - // "gen_ai.request.max_tokens" semantic conventions. It represents the - // maximum number of tokens the LLM generates for a request. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 100 - GenAiRequestMaxTokensKey = attribute.Key("gen_ai.request.max_tokens") - - // GenAiRequestModelKey is the attribute Key conforming to the - // "gen_ai.request.model" semantic conventions. It represents the name of - // the LLM a request is being made to. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'gpt-4' - GenAiRequestModelKey = attribute.Key("gen_ai.request.model") - - // GenAiRequestTemperatureKey is the attribute Key conforming to the - // "gen_ai.request.temperature" semantic conventions. It represents the - // temperature setting for the LLM request. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0.0 - GenAiRequestTemperatureKey = attribute.Key("gen_ai.request.temperature") - - // GenAiRequestTopPKey is the attribute Key conforming to the - // "gen_ai.request.top_p" semantic conventions. It represents the top_p - // sampling setting for the LLM request. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1.0 - GenAiRequestTopPKey = attribute.Key("gen_ai.request.top_p") - - // GenAiResponseFinishReasonsKey is the attribute Key conforming to the - // "gen_ai.response.finish_reasons" semantic conventions. It represents the - // array of reasons the model stopped generating tokens, corresponding to - // each generation received. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'stop' - GenAiResponseFinishReasonsKey = attribute.Key("gen_ai.response.finish_reasons") - - // GenAiResponseIDKey is the attribute Key conforming to the - // "gen_ai.response.id" semantic conventions. It represents the unique - // identifier for the completion. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'chatcmpl-123' - GenAiResponseIDKey = attribute.Key("gen_ai.response.id") - - // GenAiResponseModelKey is the attribute Key conforming to the - // "gen_ai.response.model" semantic conventions. It represents the name of - // the LLM a response was generated from. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'gpt-4-0613' - GenAiResponseModelKey = attribute.Key("gen_ai.response.model") - - // GenAiSystemKey is the attribute Key conforming to the "gen_ai.system" - // semantic conventions. It represents the Generative AI product as - // identified by the client instrumentation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'openai' - // Note: The actual GenAI product may differ from the one identified by the - // client. For example, when using OpenAI client libraries to communicate - // with Mistral, the `gen_ai.system` is set to `openai` based on the - // instrumentation's best knowledge. - GenAiSystemKey = attribute.Key("gen_ai.system") - - // GenAiUsageCompletionTokensKey is the attribute Key conforming to the - // "gen_ai.usage.completion_tokens" semantic conventions. It represents the - // number of tokens used in the LLM response (completion). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 180 - GenAiUsageCompletionTokensKey = attribute.Key("gen_ai.usage.completion_tokens") - - // GenAiUsagePromptTokensKey is the attribute Key conforming to the - // "gen_ai.usage.prompt_tokens" semantic conventions. It represents the - // number of tokens used in the LLM prompt. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 100 - GenAiUsagePromptTokensKey = attribute.Key("gen_ai.usage.prompt_tokens") -) - -var ( - // OpenAI - GenAiSystemOpenai = GenAiSystemKey.String("openai") -) - -// GenAiCompletion returns an attribute KeyValue conforming to the -// "gen_ai.completion" semantic conventions. It represents the full response -// received from the LLM. -func GenAiCompletion(val string) attribute.KeyValue { - return GenAiCompletionKey.String(val) -} - -// GenAiPrompt returns an attribute KeyValue conforming to the -// "gen_ai.prompt" semantic conventions. It represents the full prompt sent to -// an LLM. -func GenAiPrompt(val string) attribute.KeyValue { - return GenAiPromptKey.String(val) -} - -// GenAiRequestMaxTokens returns an attribute KeyValue conforming to the -// "gen_ai.request.max_tokens" semantic conventions. It represents the maximum -// number of tokens the LLM generates for a request. -func GenAiRequestMaxTokens(val int) attribute.KeyValue { - return GenAiRequestMaxTokensKey.Int(val) -} - -// GenAiRequestModel returns an attribute KeyValue conforming to the -// "gen_ai.request.model" semantic conventions. It represents the name of the -// LLM a request is being made to. -func GenAiRequestModel(val string) attribute.KeyValue { - return GenAiRequestModelKey.String(val) -} - -// GenAiRequestTemperature returns an attribute KeyValue conforming to the -// "gen_ai.request.temperature" semantic conventions. It represents the -// temperature setting for the LLM request. -func GenAiRequestTemperature(val float64) attribute.KeyValue { - return GenAiRequestTemperatureKey.Float64(val) -} - -// GenAiRequestTopP returns an attribute KeyValue conforming to the -// "gen_ai.request.top_p" semantic conventions. It represents the top_p -// sampling setting for the LLM request. -func GenAiRequestTopP(val float64) attribute.KeyValue { - return GenAiRequestTopPKey.Float64(val) -} - -// GenAiResponseFinishReasons returns an attribute KeyValue conforming to -// the "gen_ai.response.finish_reasons" semantic conventions. It represents the -// array of reasons the model stopped generating tokens, corresponding to each -// generation received. -func GenAiResponseFinishReasons(val ...string) attribute.KeyValue { - return GenAiResponseFinishReasonsKey.StringSlice(val) -} - -// GenAiResponseID returns an attribute KeyValue conforming to the -// "gen_ai.response.id" semantic conventions. It represents the unique -// identifier for the completion. -func GenAiResponseID(val string) attribute.KeyValue { - return GenAiResponseIDKey.String(val) -} - -// GenAiResponseModel returns an attribute KeyValue conforming to the -// "gen_ai.response.model" semantic conventions. It represents the name of the -// LLM a response was generated from. -func GenAiResponseModel(val string) attribute.KeyValue { - return GenAiResponseModelKey.String(val) -} - -// GenAiUsageCompletionTokens returns an attribute KeyValue conforming to -// the "gen_ai.usage.completion_tokens" semantic conventions. It represents the -// number of tokens used in the LLM response (completion). -func GenAiUsageCompletionTokens(val int) attribute.KeyValue { - return GenAiUsageCompletionTokensKey.Int(val) -} - -// GenAiUsagePromptTokens returns an attribute KeyValue conforming to the -// "gen_ai.usage.prompt_tokens" semantic conventions. It represents the number -// of tokens used in the LLM prompt. -func GenAiUsagePromptTokens(val int) attribute.KeyValue { - return GenAiUsagePromptTokensKey.Int(val) -} - -// Attributes for GraphQL. -const ( - // GraphqlDocumentKey is the attribute Key conforming to the - // "graphql.document" semantic conventions. It represents the GraphQL - // document being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'query findBookByID { bookByID(id: ?) { name } }' - // Note: The value may be sanitized to exclude sensitive information. - GraphqlDocumentKey = attribute.Key("graphql.document") - - // GraphqlOperationNameKey is the attribute Key conforming to the - // "graphql.operation.name" semantic conventions. It represents the name of - // the operation being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'findBookByID' - GraphqlOperationNameKey = attribute.Key("graphql.operation.name") - - // GraphqlOperationTypeKey is the attribute Key conforming to the - // "graphql.operation.type" semantic conventions. It represents the type of - // the operation being executed. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'query', 'mutation', 'subscription' - GraphqlOperationTypeKey = attribute.Key("graphql.operation.type") -) - -var ( - // GraphQL query - GraphqlOperationTypeQuery = GraphqlOperationTypeKey.String("query") - // GraphQL mutation - GraphqlOperationTypeMutation = GraphqlOperationTypeKey.String("mutation") - // GraphQL subscription - GraphqlOperationTypeSubscription = GraphqlOperationTypeKey.String("subscription") -) - -// GraphqlDocument returns an attribute KeyValue conforming to the -// "graphql.document" semantic conventions. It represents the GraphQL document -// being executed. -func GraphqlDocument(val string) attribute.KeyValue { - return GraphqlDocumentKey.String(val) -} - -// GraphqlOperationName returns an attribute KeyValue conforming to the -// "graphql.operation.name" semantic conventions. It represents the name of the -// operation being executed. -func GraphqlOperationName(val string) attribute.KeyValue { - return GraphqlOperationNameKey.String(val) -} - -// Attributes for the Android platform on which the Android application is -// running. -const ( - // HerokuAppIDKey is the attribute Key conforming to the "heroku.app.id" - // semantic conventions. It represents the unique identifier for the - // application - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2daa2797-e42b-4624-9322-ec3f968df4da' - HerokuAppIDKey = attribute.Key("heroku.app.id") - - // HerokuReleaseCommitKey is the attribute Key conforming to the - // "heroku.release.commit" semantic conventions. It represents the commit - // hash for the current release - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'e6134959463efd8966b20e75b913cafe3f5ec' - HerokuReleaseCommitKey = attribute.Key("heroku.release.commit") - - // HerokuReleaseCreationTimestampKey is the attribute Key conforming to the - // "heroku.release.creation_timestamp" semantic conventions. It represents - // the time and date the release was created - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2022-10-23T18:00:42Z' - HerokuReleaseCreationTimestampKey = attribute.Key("heroku.release.creation_timestamp") -) - -// HerokuAppID returns an attribute KeyValue conforming to the -// "heroku.app.id" semantic conventions. It represents the unique identifier -// for the application -func HerokuAppID(val string) attribute.KeyValue { - return HerokuAppIDKey.String(val) -} - -// HerokuReleaseCommit returns an attribute KeyValue conforming to the -// "heroku.release.commit" semantic conventions. It represents the commit hash -// for the current release -func HerokuReleaseCommit(val string) attribute.KeyValue { - return HerokuReleaseCommitKey.String(val) -} - -// HerokuReleaseCreationTimestamp returns an attribute KeyValue conforming -// to the "heroku.release.creation_timestamp" semantic conventions. It -// represents the time and date the release was created -func HerokuReleaseCreationTimestamp(val string) attribute.KeyValue { - return HerokuReleaseCreationTimestampKey.String(val) -} - -// A host is defined as a computing instance. For example, physical servers, -// virtual machines, switches or disk array. -const ( - // HostArchKey is the attribute Key conforming to the "host.arch" semantic - // conventions. It represents the CPU architecture the host system is - // running on. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - HostArchKey = attribute.Key("host.arch") - - // HostCPUCacheL2SizeKey is the attribute Key conforming to the - // "host.cpu.cache.l2.size" semantic conventions. It represents the amount - // of level 2 memory cache available to the processor (in Bytes). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 12288000 - HostCPUCacheL2SizeKey = attribute.Key("host.cpu.cache.l2.size") - - // HostCPUFamilyKey is the attribute Key conforming to the - // "host.cpu.family" semantic conventions. It represents the family or - // generation of the CPU. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '6', 'PA-RISC 1.1e' - HostCPUFamilyKey = attribute.Key("host.cpu.family") - - // HostCPUModelIDKey is the attribute Key conforming to the - // "host.cpu.model.id" semantic conventions. It represents the model - // identifier. It provides more granular information about the CPU, - // distinguishing it from other CPUs within the same family. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '6', '9000/778/B180L' - HostCPUModelIDKey = attribute.Key("host.cpu.model.id") - - // HostCPUModelNameKey is the attribute Key conforming to the - // "host.cpu.model.name" semantic conventions. It represents the model - // designation of the processor. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz' - HostCPUModelNameKey = attribute.Key("host.cpu.model.name") - - // HostCPUSteppingKey is the attribute Key conforming to the - // "host.cpu.stepping" semantic conventions. It represents the stepping or - // core revisions. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1', 'r1p1' - HostCPUSteppingKey = attribute.Key("host.cpu.stepping") - - // HostCPUVendorIDKey is the attribute Key conforming to the - // "host.cpu.vendor.id" semantic conventions. It represents the processor - // manufacturer identifier. A maximum 12-character string. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'GenuineIntel' - // Note: [CPUID](https://wiki.osdev.org/CPUID) command returns the vendor - // ID string in EBX, EDX and ECX registers. Writing these to memory in this - // order results in a 12-character string. - HostCPUVendorIDKey = attribute.Key("host.cpu.vendor.id") - - // HostIDKey is the attribute Key conforming to the "host.id" semantic - // conventions. It represents the unique host ID. For Cloud, this must be - // the instance_id assigned by the cloud provider. For non-containerized - // systems, this should be the `machine-id`. See the table below for the - // sources to use to determine the `machine-id` based on operating system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'fdbf79e8af94cb7f9e8df36789187052' - HostIDKey = attribute.Key("host.id") - - // HostImageIDKey is the attribute Key conforming to the "host.image.id" - // semantic conventions. It represents the vM image ID or host OS image ID. - // For Cloud, this value is from the provider. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ami-07b06b442921831e5' - HostImageIDKey = attribute.Key("host.image.id") - - // HostImageNameKey is the attribute Key conforming to the - // "host.image.name" semantic conventions. It represents the name of the VM - // image or OS install the host was instantiated from. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'infra-ami-eks-worker-node-7d4ec78312', 'CentOS-8-x86_64-1905' - HostImageNameKey = attribute.Key("host.image.name") - - // HostImageVersionKey is the attribute Key conforming to the - // "host.image.version" semantic conventions. It represents the version - // string of the VM image or host OS as defined in [Version - // Attributes](/docs/resource/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0.1' - HostImageVersionKey = attribute.Key("host.image.version") - - // HostIPKey is the attribute Key conforming to the "host.ip" semantic - // conventions. It represents the available IP addresses of the host, - // excluding loopback interfaces. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '192.168.1.140', 'fe80::abc2:4a28:737a:609e' - // Note: IPv4 Addresses MUST be specified in dotted-quad notation. IPv6 - // addresses MUST be specified in the [RFC - // 5952](https://www.rfc-editor.org/rfc/rfc5952.html) format. - HostIPKey = attribute.Key("host.ip") - - // HostMacKey is the attribute Key conforming to the "host.mac" semantic - // conventions. It represents the available MAC addresses of the host, - // excluding loopback interfaces. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'AC-DE-48-23-45-67', 'AC-DE-48-23-45-67-01-9F' - // Note: MAC Addresses MUST be represented in [IEEE RA hexadecimal - // form](https://standards.ieee.org/wp-content/uploads/import/documents/tutorials/eui.pdf): - // as hyphen-separated octets in uppercase hexadecimal form from most to - // least significant. - HostMacKey = attribute.Key("host.mac") - - // HostNameKey is the attribute Key conforming to the "host.name" semantic - // conventions. It represents the name of the host. On Unix systems, it may - // contain what the hostname command returns, or the fully qualified - // hostname, or another name specified by the user. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-test' - HostNameKey = attribute.Key("host.name") - - // HostTypeKey is the attribute Key conforming to the "host.type" semantic - // conventions. It represents the type of host. For Cloud, this must be the - // machine type. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'n1-standard-1' - HostTypeKey = attribute.Key("host.type") -) - -var ( - // AMD64 - HostArchAMD64 = HostArchKey.String("amd64") - // ARM32 - HostArchARM32 = HostArchKey.String("arm32") - // ARM64 - HostArchARM64 = HostArchKey.String("arm64") - // Itanium - HostArchIA64 = HostArchKey.String("ia64") - // 32-bit PowerPC - HostArchPPC32 = HostArchKey.String("ppc32") - // 64-bit PowerPC - HostArchPPC64 = HostArchKey.String("ppc64") - // IBM z/Architecture - HostArchS390x = HostArchKey.String("s390x") - // 32-bit x86 - HostArchX86 = HostArchKey.String("x86") -) - -// HostCPUCacheL2Size returns an attribute KeyValue conforming to the -// "host.cpu.cache.l2.size" semantic conventions. It represents the amount of -// level 2 memory cache available to the processor (in Bytes). -func HostCPUCacheL2Size(val int) attribute.KeyValue { - return HostCPUCacheL2SizeKey.Int(val) -} - -// HostCPUFamily returns an attribute KeyValue conforming to the -// "host.cpu.family" semantic conventions. It represents the family or -// generation of the CPU. -func HostCPUFamily(val string) attribute.KeyValue { - return HostCPUFamilyKey.String(val) -} - -// HostCPUModelID returns an attribute KeyValue conforming to the -// "host.cpu.model.id" semantic conventions. It represents the model -// identifier. It provides more granular information about the CPU, -// distinguishing it from other CPUs within the same family. -func HostCPUModelID(val string) attribute.KeyValue { - return HostCPUModelIDKey.String(val) -} - -// HostCPUModelName returns an attribute KeyValue conforming to the -// "host.cpu.model.name" semantic conventions. It represents the model -// designation of the processor. -func HostCPUModelName(val string) attribute.KeyValue { - return HostCPUModelNameKey.String(val) -} - -// HostCPUStepping returns an attribute KeyValue conforming to the -// "host.cpu.stepping" semantic conventions. It represents the stepping or core -// revisions. -func HostCPUStepping(val string) attribute.KeyValue { - return HostCPUSteppingKey.String(val) -} - -// HostCPUVendorID returns an attribute KeyValue conforming to the -// "host.cpu.vendor.id" semantic conventions. It represents the processor -// manufacturer identifier. A maximum 12-character string. -func HostCPUVendorID(val string) attribute.KeyValue { - return HostCPUVendorIDKey.String(val) -} - -// HostID returns an attribute KeyValue conforming to the "host.id" semantic -// conventions. It represents the unique host ID. For Cloud, this must be the -// instance_id assigned by the cloud provider. For non-containerized systems, -// this should be the `machine-id`. See the table below for the sources to use -// to determine the `machine-id` based on operating system. -func HostID(val string) attribute.KeyValue { - return HostIDKey.String(val) -} - -// HostImageID returns an attribute KeyValue conforming to the -// "host.image.id" semantic conventions. It represents the vM image ID or host -// OS image ID. For Cloud, this value is from the provider. -func HostImageID(val string) attribute.KeyValue { - return HostImageIDKey.String(val) -} - -// HostImageName returns an attribute KeyValue conforming to the -// "host.image.name" semantic conventions. It represents the name of the VM -// image or OS install the host was instantiated from. -func HostImageName(val string) attribute.KeyValue { - return HostImageNameKey.String(val) -} - -// HostImageVersion returns an attribute KeyValue conforming to the -// "host.image.version" semantic conventions. It represents the version string -// of the VM image or host OS as defined in [Version -// Attributes](/docs/resource/README.md#version-attributes). -func HostImageVersion(val string) attribute.KeyValue { - return HostImageVersionKey.String(val) -} - -// HostIP returns an attribute KeyValue conforming to the "host.ip" semantic -// conventions. It represents the available IP addresses of the host, excluding -// loopback interfaces. -func HostIP(val ...string) attribute.KeyValue { - return HostIPKey.StringSlice(val) -} - -// HostMac returns an attribute KeyValue conforming to the "host.mac" -// semantic conventions. It represents the available MAC addresses of the host, -// excluding loopback interfaces. -func HostMac(val ...string) attribute.KeyValue { - return HostMacKey.StringSlice(val) -} - -// HostName returns an attribute KeyValue conforming to the "host.name" -// semantic conventions. It represents the name of the host. On Unix systems, -// it may contain what the hostname command returns, or the fully qualified -// hostname, or another name specified by the user. -func HostName(val string) attribute.KeyValue { - return HostNameKey.String(val) -} - -// HostType returns an attribute KeyValue conforming to the "host.type" -// semantic conventions. It represents the type of host. For Cloud, this must -// be the machine type. -func HostType(val string) attribute.KeyValue { - return HostTypeKey.String(val) -} - -// Semantic convention attributes in the HTTP namespace. -const ( - // HTTPConnectionStateKey is the attribute Key conforming to the - // "http.connection.state" semantic conventions. It represents the state of - // the HTTP connection in the HTTP connection pool. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'active', 'idle' - HTTPConnectionStateKey = attribute.Key("http.connection.state") - - // HTTPRequestBodySizeKey is the attribute Key conforming to the - // "http.request.body.size" semantic conventions. It represents the size of - // the request payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3495 - HTTPRequestBodySizeKey = attribute.Key("http.request.body.size") - - // HTTPRequestMethodKey is the attribute Key conforming to the - // "http.request.method" semantic conventions. It represents the hTTP - // request method. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'GET', 'POST', 'HEAD' - // Note: HTTP request method value SHOULD be "known" to the - // instrumentation. - // By default, this convention defines "known" methods as the ones listed - // in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods) - // and the PATCH method defined in - // [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html). - // - // If the HTTP request method is not known to instrumentation, it MUST set - // the `http.request.method` attribute to `_OTHER`. - // - // If the HTTP instrumentation could end up converting valid HTTP request - // methods to `_OTHER`, then it MUST provide a way to override - // the list of known HTTP methods. If this override is done via environment - // variable, then the environment variable MUST be named - // OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated - // list of case-sensitive known HTTP methods - // (this list MUST be a full override of the default known method, it is - // not a list of known methods in addition to the defaults). - // - // HTTP method names are case-sensitive and `http.request.method` attribute - // value MUST match a known HTTP method name exactly. - // Instrumentations for specific web frameworks that consider HTTP methods - // to be case insensitive, SHOULD populate a canonical equivalent. - // Tracing instrumentations that do so, MUST also set - // `http.request.method_original` to the original value. - HTTPRequestMethodKey = attribute.Key("http.request.method") - - // HTTPRequestMethodOriginalKey is the attribute Key conforming to the - // "http.request.method_original" semantic conventions. It represents the - // original HTTP method sent by the client in the request line. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'GeT', 'ACL', 'foo' - HTTPRequestMethodOriginalKey = attribute.Key("http.request.method_original") - - // HTTPRequestResendCountKey is the attribute Key conforming to the - // "http.request.resend_count" semantic conventions. It represents the - // ordinal number of request resending attempt (for any reason, including - // redirects). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3 - // Note: The resend count SHOULD be updated each time an HTTP request gets - // resent by the client, regardless of what was the cause of the resending - // (e.g. redirection, authorization failure, 503 Server Unavailable, - // network issues, or any other). - HTTPRequestResendCountKey = attribute.Key("http.request.resend_count") - - // HTTPRequestSizeKey is the attribute Key conforming to the - // "http.request.size" semantic conventions. It represents the total size - // of the request in bytes. This should be the total number of bytes sent - // over the wire, including the request line (HTTP/1.1), framing (HTTP/2 - // and HTTP/3), headers, and request body if any. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1437 - HTTPRequestSizeKey = attribute.Key("http.request.size") - - // HTTPResponseBodySizeKey is the attribute Key conforming to the - // "http.response.body.size" semantic conventions. It represents the size - // of the response payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3495 - HTTPResponseBodySizeKey = attribute.Key("http.response.body.size") - - // HTTPResponseSizeKey is the attribute Key conforming to the - // "http.response.size" semantic conventions. It represents the total size - // of the response in bytes. This should be the total number of bytes sent - // over the wire, including the status line (HTTP/1.1), framing (HTTP/2 and - // HTTP/3), headers, and response body and trailers if any. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1437 - HTTPResponseSizeKey = attribute.Key("http.response.size") - - // HTTPResponseStatusCodeKey is the attribute Key conforming to the - // "http.response.status_code" semantic conventions. It represents the - // [HTTP response status - // code](https://tools.ietf.org/html/rfc7231#section-6). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 200 - HTTPResponseStatusCodeKey = attribute.Key("http.response.status_code") - - // HTTPRouteKey is the attribute Key conforming to the "http.route" - // semantic conventions. It represents the matched route, that is, the path - // template in the format used by the respective server framework. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/users/:userID?', '{controller}/{action}/{id?}' - // Note: MUST NOT be populated when this is not supported by the HTTP - // server framework as the route attribute should have low-cardinality and - // the URI path can NOT substitute it. - // SHOULD include the [application - // root](/docs/http/http-spans.md#http-server-definitions) if there is one. - HTTPRouteKey = attribute.Key("http.route") -) - -var ( - // active state - HTTPConnectionStateActive = HTTPConnectionStateKey.String("active") - // idle state - HTTPConnectionStateIdle = HTTPConnectionStateKey.String("idle") -) - -var ( - // CONNECT method - HTTPRequestMethodConnect = HTTPRequestMethodKey.String("CONNECT") - // DELETE method - HTTPRequestMethodDelete = HTTPRequestMethodKey.String("DELETE") - // GET method - HTTPRequestMethodGet = HTTPRequestMethodKey.String("GET") - // HEAD method - HTTPRequestMethodHead = HTTPRequestMethodKey.String("HEAD") - // OPTIONS method - HTTPRequestMethodOptions = HTTPRequestMethodKey.String("OPTIONS") - // PATCH method - HTTPRequestMethodPatch = HTTPRequestMethodKey.String("PATCH") - // POST method - HTTPRequestMethodPost = HTTPRequestMethodKey.String("POST") - // PUT method - HTTPRequestMethodPut = HTTPRequestMethodKey.String("PUT") - // TRACE method - HTTPRequestMethodTrace = HTTPRequestMethodKey.String("TRACE") - // Any HTTP method that the instrumentation has no prior knowledge of - HTTPRequestMethodOther = HTTPRequestMethodKey.String("_OTHER") -) - -// HTTPRequestBodySize returns an attribute KeyValue conforming to the -// "http.request.body.size" semantic conventions. It represents the size of the -// request payload body in bytes. This is the number of bytes transferred -// excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPRequestBodySize(val int) attribute.KeyValue { - return HTTPRequestBodySizeKey.Int(val) -} - -// HTTPRequestMethodOriginal returns an attribute KeyValue conforming to the -// "http.request.method_original" semantic conventions. It represents the -// original HTTP method sent by the client in the request line. -func HTTPRequestMethodOriginal(val string) attribute.KeyValue { - return HTTPRequestMethodOriginalKey.String(val) -} - -// HTTPRequestResendCount returns an attribute KeyValue conforming to the -// "http.request.resend_count" semantic conventions. It represents the ordinal -// number of request resending attempt (for any reason, including redirects). -func HTTPRequestResendCount(val int) attribute.KeyValue { - return HTTPRequestResendCountKey.Int(val) -} - -// HTTPRequestSize returns an attribute KeyValue conforming to the -// "http.request.size" semantic conventions. It represents the total size of -// the request in bytes. This should be the total number of bytes sent over the -// wire, including the request line (HTTP/1.1), framing (HTTP/2 and HTTP/3), -// headers, and request body if any. -func HTTPRequestSize(val int) attribute.KeyValue { - return HTTPRequestSizeKey.Int(val) -} - -// HTTPResponseBodySize returns an attribute KeyValue conforming to the -// "http.response.body.size" semantic conventions. It represents the size of -// the response payload body in bytes. This is the number of bytes transferred -// excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPResponseBodySize(val int) attribute.KeyValue { - return HTTPResponseBodySizeKey.Int(val) -} - -// HTTPResponseSize returns an attribute KeyValue conforming to the -// "http.response.size" semantic conventions. It represents the total size of -// the response in bytes. This should be the total number of bytes sent over -// the wire, including the status line (HTTP/1.1), framing (HTTP/2 and HTTP/3), -// headers, and response body and trailers if any. -func HTTPResponseSize(val int) attribute.KeyValue { - return HTTPResponseSizeKey.Int(val) -} - -// HTTPResponseStatusCode returns an attribute KeyValue conforming to the -// "http.response.status_code" semantic conventions. It represents the [HTTP -// response status code](https://tools.ietf.org/html/rfc7231#section-6). -func HTTPResponseStatusCode(val int) attribute.KeyValue { - return HTTPResponseStatusCodeKey.Int(val) -} - -// HTTPRoute returns an attribute KeyValue conforming to the "http.route" -// semantic conventions. It represents the matched route, that is, the path -// template in the format used by the respective server framework. -func HTTPRoute(val string) attribute.KeyValue { - return HTTPRouteKey.String(val) -} - -// Java Virtual machine related attributes. -const ( - // JvmBufferPoolNameKey is the attribute Key conforming to the - // "jvm.buffer.pool.name" semantic conventions. It represents the name of - // the buffer pool. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mapped', 'direct' - // Note: Pool names are generally obtained via - // [BufferPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/BufferPoolMXBean.html#getName()). - JvmBufferPoolNameKey = attribute.Key("jvm.buffer.pool.name") - - // JvmGcActionKey is the attribute Key conforming to the "jvm.gc.action" - // semantic conventions. It represents the name of the garbage collector - // action. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'end of minor GC', 'end of major GC' - // Note: Garbage collector action is generally obtained via - // [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). - JvmGcActionKey = attribute.Key("jvm.gc.action") - - // JvmGcNameKey is the attribute Key conforming to the "jvm.gc.name" - // semantic conventions. It represents the name of the garbage collector. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'G1 Young Generation', 'G1 Old Generation' - // Note: Garbage collector name is generally obtained via - // [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). - JvmGcNameKey = attribute.Key("jvm.gc.name") - - // JvmMemoryPoolNameKey is the attribute Key conforming to the - // "jvm.memory.pool.name" semantic conventions. It represents the name of - // the memory pool. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'G1 Old Gen', 'G1 Eden space', 'G1 Survivor Space' - // Note: Pool names are generally obtained via - // [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - JvmMemoryPoolNameKey = attribute.Key("jvm.memory.pool.name") - - // JvmMemoryTypeKey is the attribute Key conforming to the - // "jvm.memory.type" semantic conventions. It represents the type of - // memory. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'heap', 'non_heap' - JvmMemoryTypeKey = attribute.Key("jvm.memory.type") - - // JvmThreadDaemonKey is the attribute Key conforming to the - // "jvm.thread.daemon" semantic conventions. It represents the whether the - // thread is daemon or not. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - JvmThreadDaemonKey = attribute.Key("jvm.thread.daemon") - - // JvmThreadStateKey is the attribute Key conforming to the - // "jvm.thread.state" semantic conventions. It represents the state of the - // thread. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'runnable', 'blocked' - JvmThreadStateKey = attribute.Key("jvm.thread.state") -) - -var ( - // Heap memory - JvmMemoryTypeHeap = JvmMemoryTypeKey.String("heap") - // Non-heap memory - JvmMemoryTypeNonHeap = JvmMemoryTypeKey.String("non_heap") -) - -var ( - // A thread that has not yet started is in this state - JvmThreadStateNew = JvmThreadStateKey.String("new") - // A thread executing in the Java virtual machine is in this state - JvmThreadStateRunnable = JvmThreadStateKey.String("runnable") - // A thread that is blocked waiting for a monitor lock is in this state - JvmThreadStateBlocked = JvmThreadStateKey.String("blocked") - // A thread that is waiting indefinitely for another thread to perform a particular action is in this state - JvmThreadStateWaiting = JvmThreadStateKey.String("waiting") - // A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state - JvmThreadStateTimedWaiting = JvmThreadStateKey.String("timed_waiting") - // A thread that has exited is in this state - JvmThreadStateTerminated = JvmThreadStateKey.String("terminated") -) - -// JvmBufferPoolName returns an attribute KeyValue conforming to the -// "jvm.buffer.pool.name" semantic conventions. It represents the name of the -// buffer pool. -func JvmBufferPoolName(val string) attribute.KeyValue { - return JvmBufferPoolNameKey.String(val) -} - -// JvmGcAction returns an attribute KeyValue conforming to the -// "jvm.gc.action" semantic conventions. It represents the name of the garbage -// collector action. -func JvmGcAction(val string) attribute.KeyValue { - return JvmGcActionKey.String(val) -} - -// JvmGcName returns an attribute KeyValue conforming to the "jvm.gc.name" -// semantic conventions. It represents the name of the garbage collector. -func JvmGcName(val string) attribute.KeyValue { - return JvmGcNameKey.String(val) -} - -// JvmMemoryPoolName returns an attribute KeyValue conforming to the -// "jvm.memory.pool.name" semantic conventions. It represents the name of the -// memory pool. -func JvmMemoryPoolName(val string) attribute.KeyValue { - return JvmMemoryPoolNameKey.String(val) -} - -// JvmThreadDaemon returns an attribute KeyValue conforming to the -// "jvm.thread.daemon" semantic conventions. It represents the whether the -// thread is daemon or not. -func JvmThreadDaemon(val bool) attribute.KeyValue { - return JvmThreadDaemonKey.Bool(val) -} - -// Kubernetes resource attributes. -const ( - // K8SClusterNameKey is the attribute Key conforming to the - // "k8s.cluster.name" semantic conventions. It represents the name of the - // cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-cluster' - K8SClusterNameKey = attribute.Key("k8s.cluster.name") - - // K8SClusterUIDKey is the attribute Key conforming to the - // "k8s.cluster.uid" semantic conventions. It represents a pseudo-ID for - // the cluster, set to the UID of the `kube-system` namespace. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '218fc5a9-a5f1-4b54-aa05-46717d0ab26d' - // Note: K8S doesn't have support for obtaining a cluster ID. If this is - // ever - // added, we will recommend collecting the `k8s.cluster.uid` through the - // official APIs. In the meantime, we are able to use the `uid` of the - // `kube-system` namespace as a proxy for cluster ID. Read on for the - // rationale. - // - // Every object created in a K8S cluster is assigned a distinct UID. The - // `kube-system` namespace is used by Kubernetes itself and will exist - // for the lifetime of the cluster. Using the `uid` of the `kube-system` - // namespace is a reasonable proxy for the K8S ClusterID as it will only - // change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are - // UUIDs as standardized by - // [ISO/IEC 9834-8 and ITU-T - // X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html). - // Which states: - // - // > If generated according to one of the mechanisms defined in Rec. - // ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be - // different from all other UUIDs generated before 3603 A.D., or is - // extremely likely to be different (depending on the mechanism chosen). - // - // Therefore, UIDs between clusters should be extremely unlikely to - // conflict. - K8SClusterUIDKey = attribute.Key("k8s.cluster.uid") - - // K8SContainerNameKey is the attribute Key conforming to the - // "k8s.container.name" semantic conventions. It represents the name of the - // Container from Pod specification, must be unique within a Pod. Container - // runtime usually uses different globally unique name (`container.name`). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'redis' - K8SContainerNameKey = attribute.Key("k8s.container.name") - - // K8SContainerRestartCountKey is the attribute Key conforming to the - // "k8s.container.restart_count" semantic conventions. It represents the - // number of times the container was restarted. This attribute can be used - // to identify a particular container (running or stopped) within a - // container spec. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - K8SContainerRestartCountKey = attribute.Key("k8s.container.restart_count") - - // K8SContainerStatusLastTerminatedReasonKey is the attribute Key - // conforming to the "k8s.container.status.last_terminated_reason" semantic - // conventions. It represents the last terminated reason of the Container. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Evicted', 'Error' - K8SContainerStatusLastTerminatedReasonKey = attribute.Key("k8s.container.status.last_terminated_reason") - - // K8SCronJobNameKey is the attribute Key conforming to the - // "k8s.cronjob.name" semantic conventions. It represents the name of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SCronJobNameKey = attribute.Key("k8s.cronjob.name") - - // K8SCronJobUIDKey is the attribute Key conforming to the - // "k8s.cronjob.uid" semantic conventions. It represents the UID of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SCronJobUIDKey = attribute.Key("k8s.cronjob.uid") - - // K8SDaemonSetNameKey is the attribute Key conforming to the - // "k8s.daemonset.name" semantic conventions. It represents the name of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SDaemonSetNameKey = attribute.Key("k8s.daemonset.name") - - // K8SDaemonSetUIDKey is the attribute Key conforming to the - // "k8s.daemonset.uid" semantic conventions. It represents the UID of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDaemonSetUIDKey = attribute.Key("k8s.daemonset.uid") - - // K8SDeploymentNameKey is the attribute Key conforming to the - // "k8s.deployment.name" semantic conventions. It represents the name of - // the Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SDeploymentNameKey = attribute.Key("k8s.deployment.name") - - // K8SDeploymentUIDKey is the attribute Key conforming to the - // "k8s.deployment.uid" semantic conventions. It represents the UID of the - // Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDeploymentUIDKey = attribute.Key("k8s.deployment.uid") - - // K8SJobNameKey is the attribute Key conforming to the "k8s.job.name" - // semantic conventions. It represents the name of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SJobNameKey = attribute.Key("k8s.job.name") - - // K8SJobUIDKey is the attribute Key conforming to the "k8s.job.uid" - // semantic conventions. It represents the UID of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SJobUIDKey = attribute.Key("k8s.job.uid") - - // K8SNamespaceNameKey is the attribute Key conforming to the - // "k8s.namespace.name" semantic conventions. It represents the name of the - // namespace that the pod is running in. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'default' - K8SNamespaceNameKey = attribute.Key("k8s.namespace.name") - - // K8SNodeNameKey is the attribute Key conforming to the "k8s.node.name" - // semantic conventions. It represents the name of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'node-1' - K8SNodeNameKey = attribute.Key("k8s.node.name") - - // K8SNodeUIDKey is the attribute Key conforming to the "k8s.node.uid" - // semantic conventions. It represents the UID of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2' - K8SNodeUIDKey = attribute.Key("k8s.node.uid") - - // K8SPodNameKey is the attribute Key conforming to the "k8s.pod.name" - // semantic conventions. It represents the name of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-pod-autoconf' - K8SPodNameKey = attribute.Key("k8s.pod.name") - - // K8SPodUIDKey is the attribute Key conforming to the "k8s.pod.uid" - // semantic conventions. It represents the UID of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SPodUIDKey = attribute.Key("k8s.pod.uid") - - // K8SReplicaSetNameKey is the attribute Key conforming to the - // "k8s.replicaset.name" semantic conventions. It represents the name of - // the ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SReplicaSetNameKey = attribute.Key("k8s.replicaset.name") - - // K8SReplicaSetUIDKey is the attribute Key conforming to the - // "k8s.replicaset.uid" semantic conventions. It represents the UID of the - // ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SReplicaSetUIDKey = attribute.Key("k8s.replicaset.uid") - - // K8SStatefulSetNameKey is the attribute Key conforming to the - // "k8s.statefulset.name" semantic conventions. It represents the name of - // the StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SStatefulSetNameKey = attribute.Key("k8s.statefulset.name") - - // K8SStatefulSetUIDKey is the attribute Key conforming to the - // "k8s.statefulset.uid" semantic conventions. It represents the UID of the - // StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SStatefulSetUIDKey = attribute.Key("k8s.statefulset.uid") -) - -// K8SClusterName returns an attribute KeyValue conforming to the -// "k8s.cluster.name" semantic conventions. It represents the name of the -// cluster. -func K8SClusterName(val string) attribute.KeyValue { - return K8SClusterNameKey.String(val) -} - -// K8SClusterUID returns an attribute KeyValue conforming to the -// "k8s.cluster.uid" semantic conventions. It represents a pseudo-ID for the -// cluster, set to the UID of the `kube-system` namespace. -func K8SClusterUID(val string) attribute.KeyValue { - return K8SClusterUIDKey.String(val) -} - -// K8SContainerName returns an attribute KeyValue conforming to the -// "k8s.container.name" semantic conventions. It represents the name of the -// Container from Pod specification, must be unique within a Pod. Container -// runtime usually uses different globally unique name (`container.name`). -func K8SContainerName(val string) attribute.KeyValue { - return K8SContainerNameKey.String(val) -} - -// K8SContainerRestartCount returns an attribute KeyValue conforming to the -// "k8s.container.restart_count" semantic conventions. It represents the number -// of times the container was restarted. This attribute can be used to identify -// a particular container (running or stopped) within a container spec. -func K8SContainerRestartCount(val int) attribute.KeyValue { - return K8SContainerRestartCountKey.Int(val) -} - -// K8SContainerStatusLastTerminatedReason returns an attribute KeyValue -// conforming to the "k8s.container.status.last_terminated_reason" semantic -// conventions. It represents the last terminated reason of the Container. -func K8SContainerStatusLastTerminatedReason(val string) attribute.KeyValue { - return K8SContainerStatusLastTerminatedReasonKey.String(val) -} - -// K8SCronJobName returns an attribute KeyValue conforming to the -// "k8s.cronjob.name" semantic conventions. It represents the name of the -// CronJob. -func K8SCronJobName(val string) attribute.KeyValue { - return K8SCronJobNameKey.String(val) -} - -// K8SCronJobUID returns an attribute KeyValue conforming to the -// "k8s.cronjob.uid" semantic conventions. It represents the UID of the -// CronJob. -func K8SCronJobUID(val string) attribute.KeyValue { - return K8SCronJobUIDKey.String(val) -} - -// K8SDaemonSetName returns an attribute KeyValue conforming to the -// "k8s.daemonset.name" semantic conventions. It represents the name of the -// DaemonSet. -func K8SDaemonSetName(val string) attribute.KeyValue { - return K8SDaemonSetNameKey.String(val) -} - -// K8SDaemonSetUID returns an attribute KeyValue conforming to the -// "k8s.daemonset.uid" semantic conventions. It represents the UID of the -// DaemonSet. -func K8SDaemonSetUID(val string) attribute.KeyValue { - return K8SDaemonSetUIDKey.String(val) -} - -// K8SDeploymentName returns an attribute KeyValue conforming to the -// "k8s.deployment.name" semantic conventions. It represents the name of the -// Deployment. -func K8SDeploymentName(val string) attribute.KeyValue { - return K8SDeploymentNameKey.String(val) -} - -// K8SDeploymentUID returns an attribute KeyValue conforming to the -// "k8s.deployment.uid" semantic conventions. It represents the UID of the -// Deployment. -func K8SDeploymentUID(val string) attribute.KeyValue { - return K8SDeploymentUIDKey.String(val) -} - -// K8SJobName returns an attribute KeyValue conforming to the "k8s.job.name" -// semantic conventions. It represents the name of the Job. -func K8SJobName(val string) attribute.KeyValue { - return K8SJobNameKey.String(val) -} - -// K8SJobUID returns an attribute KeyValue conforming to the "k8s.job.uid" -// semantic conventions. It represents the UID of the Job. -func K8SJobUID(val string) attribute.KeyValue { - return K8SJobUIDKey.String(val) -} - -// K8SNamespaceName returns an attribute KeyValue conforming to the -// "k8s.namespace.name" semantic conventions. It represents the name of the -// namespace that the pod is running in. -func K8SNamespaceName(val string) attribute.KeyValue { - return K8SNamespaceNameKey.String(val) -} - -// K8SNodeName returns an attribute KeyValue conforming to the -// "k8s.node.name" semantic conventions. It represents the name of the Node. -func K8SNodeName(val string) attribute.KeyValue { - return K8SNodeNameKey.String(val) -} - -// K8SNodeUID returns an attribute KeyValue conforming to the "k8s.node.uid" -// semantic conventions. It represents the UID of the Node. -func K8SNodeUID(val string) attribute.KeyValue { - return K8SNodeUIDKey.String(val) -} - -// K8SPodName returns an attribute KeyValue conforming to the "k8s.pod.name" -// semantic conventions. It represents the name of the Pod. -func K8SPodName(val string) attribute.KeyValue { - return K8SPodNameKey.String(val) -} - -// K8SPodUID returns an attribute KeyValue conforming to the "k8s.pod.uid" -// semantic conventions. It represents the UID of the Pod. -func K8SPodUID(val string) attribute.KeyValue { - return K8SPodUIDKey.String(val) -} - -// K8SReplicaSetName returns an attribute KeyValue conforming to the -// "k8s.replicaset.name" semantic conventions. It represents the name of the -// ReplicaSet. -func K8SReplicaSetName(val string) attribute.KeyValue { - return K8SReplicaSetNameKey.String(val) -} - -// K8SReplicaSetUID returns an attribute KeyValue conforming to the -// "k8s.replicaset.uid" semantic conventions. It represents the UID of the -// ReplicaSet. -func K8SReplicaSetUID(val string) attribute.KeyValue { - return K8SReplicaSetUIDKey.String(val) -} - -// K8SStatefulSetName returns an attribute KeyValue conforming to the -// "k8s.statefulset.name" semantic conventions. It represents the name of the -// StatefulSet. -func K8SStatefulSetName(val string) attribute.KeyValue { - return K8SStatefulSetNameKey.String(val) -} - -// K8SStatefulSetUID returns an attribute KeyValue conforming to the -// "k8s.statefulset.uid" semantic conventions. It represents the UID of the -// StatefulSet. -func K8SStatefulSetUID(val string) attribute.KeyValue { - return K8SStatefulSetUIDKey.String(val) -} - -// Log attributes -const ( - // LogIostreamKey is the attribute Key conforming to the "log.iostream" - // semantic conventions. It represents the stream associated with the log. - // See below for a list of well-known values. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - LogIostreamKey = attribute.Key("log.iostream") -) - -var ( - // Logs from stdout stream - LogIostreamStdout = LogIostreamKey.String("stdout") - // Events from stderr stream - LogIostreamStderr = LogIostreamKey.String("stderr") -) - -// Attributes for a file to which log was emitted. -const ( - // LogFileNameKey is the attribute Key conforming to the "log.file.name" - // semantic conventions. It represents the basename of the file. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'audit.log' - LogFileNameKey = attribute.Key("log.file.name") - - // LogFileNameResolvedKey is the attribute Key conforming to the - // "log.file.name_resolved" semantic conventions. It represents the - // basename of the file, with symlinks resolved. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'uuid.log' - LogFileNameResolvedKey = attribute.Key("log.file.name_resolved") - - // LogFilePathKey is the attribute Key conforming to the "log.file.path" - // semantic conventions. It represents the full path to the file. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/var/log/mysql/audit.log' - LogFilePathKey = attribute.Key("log.file.path") - - // LogFilePathResolvedKey is the attribute Key conforming to the - // "log.file.path_resolved" semantic conventions. It represents the full - // path to the file, with symlinks resolved. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/var/lib/docker/uuid.log' - LogFilePathResolvedKey = attribute.Key("log.file.path_resolved") -) - -// LogFileName returns an attribute KeyValue conforming to the -// "log.file.name" semantic conventions. It represents the basename of the -// file. -func LogFileName(val string) attribute.KeyValue { - return LogFileNameKey.String(val) -} - -// LogFileNameResolved returns an attribute KeyValue conforming to the -// "log.file.name_resolved" semantic conventions. It represents the basename of -// the file, with symlinks resolved. -func LogFileNameResolved(val string) attribute.KeyValue { - return LogFileNameResolvedKey.String(val) -} - -// LogFilePath returns an attribute KeyValue conforming to the -// "log.file.path" semantic conventions. It represents the full path to the -// file. -func LogFilePath(val string) attribute.KeyValue { - return LogFilePathKey.String(val) -} - -// LogFilePathResolved returns an attribute KeyValue conforming to the -// "log.file.path_resolved" semantic conventions. It represents the full path -// to the file, with symlinks resolved. -func LogFilePathResolved(val string) attribute.KeyValue { - return LogFilePathResolvedKey.String(val) -} - -// The generic attributes that may be used in any Log Record. -const ( - // LogRecordUIDKey is the attribute Key conforming to the "log.record.uid" - // semantic conventions. It represents a unique identifier for the Log - // Record. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '01ARZ3NDEKTSV4RRFFQ69G5FAV' - // Note: If an id is provided, other log records with the same id will be - // considered duplicates and can be removed safely. This means, that two - // distinguishable log records MUST have different values. - // The id MAY be an [Universally Unique Lexicographically Sortable - // Identifier (ULID)](https://github.com/ulid/spec), but other identifiers - // (e.g. UUID) may be used as needed. - LogRecordUIDKey = attribute.Key("log.record.uid") -) - -// LogRecordUID returns an attribute KeyValue conforming to the -// "log.record.uid" semantic conventions. It represents a unique identifier for -// the Log Record. -func LogRecordUID(val string) attribute.KeyValue { - return LogRecordUIDKey.String(val) -} - -// Attributes describing telemetry around messaging systems and messaging -// activities. -const ( - // MessagingBatchMessageCountKey is the attribute Key conforming to the - // "messaging.batch.message_count" semantic conventions. It represents the - // number of messages sent, received, or processed in the scope of the - // batching operation. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 1, 2 - // Note: Instrumentations SHOULD NOT set `messaging.batch.message_count` on - // spans that operate with a single message. When a messaging client - // library supports both batch and single-message API for the same - // operation, instrumentations SHOULD use `messaging.batch.message_count` - // for batching APIs and SHOULD NOT use it for single-message APIs. - MessagingBatchMessageCountKey = attribute.Key("messaging.batch.message_count") - - // MessagingClientIDKey is the attribute Key conforming to the - // "messaging.client.id" semantic conventions. It represents a unique - // identifier for the client that consumes or produces a message. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'client-5', 'myhost@8742@s8083jm' - MessagingClientIDKey = attribute.Key("messaging.client.id") - - // MessagingDestinationAnonymousKey is the attribute Key conforming to the - // "messaging.destination.anonymous" semantic conventions. It represents a - // boolean that is true if the message destination is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationAnonymousKey = attribute.Key("messaging.destination.anonymous") - - // MessagingDestinationNameKey is the attribute Key conforming to the - // "messaging.destination.name" semantic conventions. It represents the - // message destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyQueue', 'MyTopic' - // Note: Destination name SHOULD uniquely identify a specific queue, topic - // or other entity within the broker. If - // the broker doesn't have such notion, the destination name SHOULD - // uniquely identify the broker. - MessagingDestinationNameKey = attribute.Key("messaging.destination.name") - - // MessagingDestinationPartitionIDKey is the attribute Key conforming to - // the "messaging.destination.partition.id" semantic conventions. It - // represents the identifier of the partition messages are sent to or - // received from, unique within the `messaging.destination.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1' - MessagingDestinationPartitionIDKey = attribute.Key("messaging.destination.partition.id") - - // MessagingDestinationTemplateKey is the attribute Key conforming to the - // "messaging.destination.template" semantic conventions. It represents the - // low cardinality representation of the messaging destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/customers/{customerID}' - // Note: Destination names could be constructed from templates. An example - // would be a destination name involving a user name or product id. - // Although the destination name in this case is of high cardinality, the - // underlying template is of low cardinality and can be effectively used - // for grouping and aggregation. - MessagingDestinationTemplateKey = attribute.Key("messaging.destination.template") - - // MessagingDestinationTemporaryKey is the attribute Key conforming to the - // "messaging.destination.temporary" semantic conventions. It represents a - // boolean that is true if the message destination is temporary and might - // not exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationTemporaryKey = attribute.Key("messaging.destination.temporary") - - // MessagingDestinationPublishAnonymousKey is the attribute Key conforming - // to the "messaging.destination_publish.anonymous" semantic conventions. - // It represents a boolean that is true if the publish message destination - // is anonymous (could be unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationPublishAnonymousKey = attribute.Key("messaging.destination_publish.anonymous") - - // MessagingDestinationPublishNameKey is the attribute Key conforming to - // the "messaging.destination_publish.name" semantic conventions. It - // represents the name of the original destination the message was - // published to - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyQueue', 'MyTopic' - // Note: The name SHOULD uniquely identify a specific queue, topic, or - // other entity within the broker. If - // the broker doesn't have such notion, the original destination name - // SHOULD uniquely identify the broker. - MessagingDestinationPublishNameKey = attribute.Key("messaging.destination_publish.name") - - // MessagingMessageBodySizeKey is the attribute Key conforming to the - // "messaging.message.body.size" semantic conventions. It represents the - // size of the message body in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1439 - // Note: This can refer to both the compressed or uncompressed body size. - // If both sizes are known, the uncompressed - // body size should be used. - MessagingMessageBodySizeKey = attribute.Key("messaging.message.body.size") - - // MessagingMessageConversationIDKey is the attribute Key conforming to the - // "messaging.message.conversation_id" semantic conventions. It represents - // the conversation ID identifying the conversation to which the message - // belongs, represented as a string. Sometimes called "Correlation ID". - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyConversationID' - MessagingMessageConversationIDKey = attribute.Key("messaging.message.conversation_id") - - // MessagingMessageEnvelopeSizeKey is the attribute Key conforming to the - // "messaging.message.envelope.size" semantic conventions. It represents - // the size of the message body and metadata in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 2738 - // Note: This can refer to both the compressed or uncompressed size. If - // both sizes are known, the uncompressed - // size should be used. - MessagingMessageEnvelopeSizeKey = attribute.Key("messaging.message.envelope.size") - - // MessagingMessageIDKey is the attribute Key conforming to the - // "messaging.message.id" semantic conventions. It represents a value used - // by the messaging system as an identifier for the message, represented as - // a string. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '452a7c7c7c7048c2f887f61572b18fc2' - MessagingMessageIDKey = attribute.Key("messaging.message.id") - - // MessagingOperationNameKey is the attribute Key conforming to the - // "messaging.operation.name" semantic conventions. It represents the - // system-specific name of the messaging operation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ack', 'nack', 'send' - MessagingOperationNameKey = attribute.Key("messaging.operation.name") - - // MessagingOperationTypeKey is the attribute Key conforming to the - // "messaging.operation.type" semantic conventions. It represents a string - // identifying the type of the messaging operation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: If a custom value is used, it MUST be of low cardinality. - MessagingOperationTypeKey = attribute.Key("messaging.operation.type") - - // MessagingSystemKey is the attribute Key conforming to the - // "messaging.system" semantic conventions. It represents the messaging - // system as identified by the client instrumentation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The actual messaging system may differ from the one known by the - // client. For example, when using Kafka client libraries to communicate - // with Azure Event Hubs, the `messaging.system` is set to `kafka` based on - // the instrumentation's best knowledge. - MessagingSystemKey = attribute.Key("messaging.system") -) - -var ( - // One or more messages are provided for publishing to an intermediary. If a single message is published, the context of the "Publish" span can be used as the creation context and no "Create" span needs to be created - MessagingOperationTypePublish = MessagingOperationTypeKey.String("publish") - // A message is created. "Create" spans always refer to a single message and are used to provide a unique creation context for messages in batch publishing scenarios - MessagingOperationTypeCreate = MessagingOperationTypeKey.String("create") - // One or more messages are requested by a consumer. This operation refers to pull-based scenarios, where consumers explicitly call methods of messaging SDKs to receive messages - MessagingOperationTypeReceive = MessagingOperationTypeKey.String("receive") - // One or more messages are delivered to or processed by a consumer - MessagingOperationTypeDeliver = MessagingOperationTypeKey.String("process") - // One or more messages are settled - MessagingOperationTypeSettle = MessagingOperationTypeKey.String("settle") -) - -var ( - // Apache ActiveMQ - MessagingSystemActivemq = MessagingSystemKey.String("activemq") - // Amazon Simple Queue Service (SQS) - MessagingSystemAWSSqs = MessagingSystemKey.String("aws_sqs") - // Azure Event Grid - MessagingSystemEventgrid = MessagingSystemKey.String("eventgrid") - // Azure Event Hubs - MessagingSystemEventhubs = MessagingSystemKey.String("eventhubs") - // Azure Service Bus - MessagingSystemServicebus = MessagingSystemKey.String("servicebus") - // Google Cloud Pub/Sub - MessagingSystemGCPPubsub = MessagingSystemKey.String("gcp_pubsub") - // Java Message Service - MessagingSystemJms = MessagingSystemKey.String("jms") - // Apache Kafka - MessagingSystemKafka = MessagingSystemKey.String("kafka") - // RabbitMQ - MessagingSystemRabbitmq = MessagingSystemKey.String("rabbitmq") - // Apache RocketMQ - MessagingSystemRocketmq = MessagingSystemKey.String("rocketmq") -) - -// MessagingBatchMessageCount returns an attribute KeyValue conforming to -// the "messaging.batch.message_count" semantic conventions. It represents the -// number of messages sent, received, or processed in the scope of the batching -// operation. -func MessagingBatchMessageCount(val int) attribute.KeyValue { - return MessagingBatchMessageCountKey.Int(val) -} - -// MessagingClientID returns an attribute KeyValue conforming to the -// "messaging.client.id" semantic conventions. It represents a unique -// identifier for the client that consumes or produces a message. -func MessagingClientID(val string) attribute.KeyValue { - return MessagingClientIDKey.String(val) -} - -// MessagingDestinationAnonymous returns an attribute KeyValue conforming to -// the "messaging.destination.anonymous" semantic conventions. It represents a -// boolean that is true if the message destination is anonymous (could be -// unnamed or have auto-generated name). -func MessagingDestinationAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationAnonymousKey.Bool(val) -} - -// MessagingDestinationName returns an attribute KeyValue conforming to the -// "messaging.destination.name" semantic conventions. It represents the message -// destination name -func MessagingDestinationName(val string) attribute.KeyValue { - return MessagingDestinationNameKey.String(val) -} - -// MessagingDestinationPartitionID returns an attribute KeyValue conforming -// to the "messaging.destination.partition.id" semantic conventions. It -// represents the identifier of the partition messages are sent to or received -// from, unique within the `messaging.destination.name`. -func MessagingDestinationPartitionID(val string) attribute.KeyValue { - return MessagingDestinationPartitionIDKey.String(val) -} - -// MessagingDestinationTemplate returns an attribute KeyValue conforming to -// the "messaging.destination.template" semantic conventions. It represents the -// low cardinality representation of the messaging destination name -func MessagingDestinationTemplate(val string) attribute.KeyValue { - return MessagingDestinationTemplateKey.String(val) -} - -// MessagingDestinationTemporary returns an attribute KeyValue conforming to -// the "messaging.destination.temporary" semantic conventions. It represents a -// boolean that is true if the message destination is temporary and might not -// exist anymore after messages are processed. -func MessagingDestinationTemporary(val bool) attribute.KeyValue { - return MessagingDestinationTemporaryKey.Bool(val) -} - -// MessagingDestinationPublishAnonymous returns an attribute KeyValue -// conforming to the "messaging.destination_publish.anonymous" semantic -// conventions. It represents a boolean that is true if the publish message -// destination is anonymous (could be unnamed or have auto-generated name). -func MessagingDestinationPublishAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationPublishAnonymousKey.Bool(val) -} - -// MessagingDestinationPublishName returns an attribute KeyValue conforming -// to the "messaging.destination_publish.name" semantic conventions. It -// represents the name of the original destination the message was published to -func MessagingDestinationPublishName(val string) attribute.KeyValue { - return MessagingDestinationPublishNameKey.String(val) -} - -// MessagingMessageBodySize returns an attribute KeyValue conforming to the -// "messaging.message.body.size" semantic conventions. It represents the size -// of the message body in bytes. -func MessagingMessageBodySize(val int) attribute.KeyValue { - return MessagingMessageBodySizeKey.Int(val) -} - -// MessagingMessageConversationID returns an attribute KeyValue conforming -// to the "messaging.message.conversation_id" semantic conventions. It -// represents the conversation ID identifying the conversation to which the -// message belongs, represented as a string. Sometimes called "Correlation ID". -func MessagingMessageConversationID(val string) attribute.KeyValue { - return MessagingMessageConversationIDKey.String(val) -} - -// MessagingMessageEnvelopeSize returns an attribute KeyValue conforming to -// the "messaging.message.envelope.size" semantic conventions. It represents -// the size of the message body and metadata in bytes. -func MessagingMessageEnvelopeSize(val int) attribute.KeyValue { - return MessagingMessageEnvelopeSizeKey.Int(val) -} - -// MessagingMessageID returns an attribute KeyValue conforming to the -// "messaging.message.id" semantic conventions. It represents a value used by -// the messaging system as an identifier for the message, represented as a -// string. -func MessagingMessageID(val string) attribute.KeyValue { - return MessagingMessageIDKey.String(val) -} - -// MessagingOperationName returns an attribute KeyValue conforming to the -// "messaging.operation.name" semantic conventions. It represents the -// system-specific name of the messaging operation. -func MessagingOperationName(val string) attribute.KeyValue { - return MessagingOperationNameKey.String(val) -} - -// This group describes attributes specific to Apache Kafka. -const ( - // MessagingKafkaConsumerGroupKey is the attribute Key conforming to the - // "messaging.kafka.consumer.group" semantic conventions. It represents the - // name of the Kafka Consumer Group that is handling the message. Only - // applies to consumers, not producers. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-group' - MessagingKafkaConsumerGroupKey = attribute.Key("messaging.kafka.consumer.group") - - // MessagingKafkaMessageKeyKey is the attribute Key conforming to the - // "messaging.kafka.message.key" semantic conventions. It represents the - // message keys in Kafka are used for grouping alike messages to ensure - // they're processed on the same partition. They differ from - // `messaging.message.id` in that they're not unique. If the key is `null`, - // the attribute MUST NOT be set. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myKey' - // Note: If the key type is not string, it's string representation has to - // be supplied for the attribute. If the key has no unambiguous, canonical - // string form, don't include its value. - MessagingKafkaMessageKeyKey = attribute.Key("messaging.kafka.message.key") - - // MessagingKafkaMessageOffsetKey is the attribute Key conforming to the - // "messaging.kafka.message.offset" semantic conventions. It represents the - // offset of a record in the corresponding Kafka partition. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - MessagingKafkaMessageOffsetKey = attribute.Key("messaging.kafka.message.offset") - - // MessagingKafkaMessageTombstoneKey is the attribute Key conforming to the - // "messaging.kafka.message.tombstone" semantic conventions. It represents - // a boolean that is true if the message is a tombstone. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingKafkaMessageTombstoneKey = attribute.Key("messaging.kafka.message.tombstone") -) - -// MessagingKafkaConsumerGroup returns an attribute KeyValue conforming to -// the "messaging.kafka.consumer.group" semantic conventions. It represents the -// name of the Kafka Consumer Group that is handling the message. Only applies -// to consumers, not producers. -func MessagingKafkaConsumerGroup(val string) attribute.KeyValue { - return MessagingKafkaConsumerGroupKey.String(val) -} - -// MessagingKafkaMessageKey returns an attribute KeyValue conforming to the -// "messaging.kafka.message.key" semantic conventions. It represents the -// message keys in Kafka are used for grouping alike messages to ensure they're -// processed on the same partition. They differ from `messaging.message.id` in -// that they're not unique. If the key is `null`, the attribute MUST NOT be -// set. -func MessagingKafkaMessageKey(val string) attribute.KeyValue { - return MessagingKafkaMessageKeyKey.String(val) -} - -// MessagingKafkaMessageOffset returns an attribute KeyValue conforming to -// the "messaging.kafka.message.offset" semantic conventions. It represents the -// offset of a record in the corresponding Kafka partition. -func MessagingKafkaMessageOffset(val int) attribute.KeyValue { - return MessagingKafkaMessageOffsetKey.Int(val) -} - -// MessagingKafkaMessageTombstone returns an attribute KeyValue conforming -// to the "messaging.kafka.message.tombstone" semantic conventions. It -// represents a boolean that is true if the message is a tombstone. -func MessagingKafkaMessageTombstone(val bool) attribute.KeyValue { - return MessagingKafkaMessageTombstoneKey.Bool(val) -} - -// This group describes attributes specific to RabbitMQ. -const ( - // MessagingRabbitmqDestinationRoutingKeyKey is the attribute Key - // conforming to the "messaging.rabbitmq.destination.routing_key" semantic - // conventions. It represents the rabbitMQ message routing key. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myKey' - MessagingRabbitmqDestinationRoutingKeyKey = attribute.Key("messaging.rabbitmq.destination.routing_key") - - // MessagingRabbitmqMessageDeliveryTagKey is the attribute Key conforming - // to the "messaging.rabbitmq.message.delivery_tag" semantic conventions. - // It represents the rabbitMQ message delivery tag - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 123 - MessagingRabbitmqMessageDeliveryTagKey = attribute.Key("messaging.rabbitmq.message.delivery_tag") -) - -// MessagingRabbitmqDestinationRoutingKey returns an attribute KeyValue -// conforming to the "messaging.rabbitmq.destination.routing_key" semantic -// conventions. It represents the rabbitMQ message routing key. -func MessagingRabbitmqDestinationRoutingKey(val string) attribute.KeyValue { - return MessagingRabbitmqDestinationRoutingKeyKey.String(val) -} - -// MessagingRabbitmqMessageDeliveryTag returns an attribute KeyValue -// conforming to the "messaging.rabbitmq.message.delivery_tag" semantic -// conventions. It represents the rabbitMQ message delivery tag -func MessagingRabbitmqMessageDeliveryTag(val int) attribute.KeyValue { - return MessagingRabbitmqMessageDeliveryTagKey.Int(val) -} - -// This group describes attributes specific to RocketMQ. -const ( - // MessagingRocketmqClientGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.client_group" semantic conventions. It represents - // the name of the RocketMQ producer/consumer group that is handling the - // message. The client type is identified by the SpanKind. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myConsumerGroup' - MessagingRocketmqClientGroupKey = attribute.Key("messaging.rocketmq.client_group") - - // MessagingRocketmqConsumptionModelKey is the attribute Key conforming to - // the "messaging.rocketmq.consumption_model" semantic conventions. It - // represents the model of message consumption. This only applies to - // consumer spans. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingRocketmqConsumptionModelKey = attribute.Key("messaging.rocketmq.consumption_model") - - // MessagingRocketmqMessageDelayTimeLevelKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delay_time_level" semantic - // conventions. It represents the delay time level for delay message, which - // determines the message delay time. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3 - MessagingRocketmqMessageDelayTimeLevelKey = attribute.Key("messaging.rocketmq.message.delay_time_level") - - // MessagingRocketmqMessageDeliveryTimestampKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delivery_timestamp" - // semantic conventions. It represents the timestamp in milliseconds that - // the delay message is expected to be delivered to consumer. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1665987217045 - MessagingRocketmqMessageDeliveryTimestampKey = attribute.Key("messaging.rocketmq.message.delivery_timestamp") - - // MessagingRocketmqMessageGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.message.group" semantic conventions. It represents - // the it is essential for FIFO message. Messages that belong to the same - // message group are always processed one by one within the same consumer - // group. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myMessageGroup' - MessagingRocketmqMessageGroupKey = attribute.Key("messaging.rocketmq.message.group") - - // MessagingRocketmqMessageKeysKey is the attribute Key conforming to the - // "messaging.rocketmq.message.keys" semantic conventions. It represents - // the key(s) of message, another way to mark message besides message id. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'keyA', 'keyB' - MessagingRocketmqMessageKeysKey = attribute.Key("messaging.rocketmq.message.keys") - - // MessagingRocketmqMessageTagKey is the attribute Key conforming to the - // "messaging.rocketmq.message.tag" semantic conventions. It represents the - // secondary classifier of message besides topic. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'tagA' - MessagingRocketmqMessageTagKey = attribute.Key("messaging.rocketmq.message.tag") - - // MessagingRocketmqMessageTypeKey is the attribute Key conforming to the - // "messaging.rocketmq.message.type" semantic conventions. It represents - // the type of message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingRocketmqMessageTypeKey = attribute.Key("messaging.rocketmq.message.type") - - // MessagingRocketmqNamespaceKey is the attribute Key conforming to the - // "messaging.rocketmq.namespace" semantic conventions. It represents the - // namespace of RocketMQ resources, resources in different namespaces are - // individual. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myNamespace' - MessagingRocketmqNamespaceKey = attribute.Key("messaging.rocketmq.namespace") -) - -var ( - // Clustering consumption model - MessagingRocketmqConsumptionModelClustering = MessagingRocketmqConsumptionModelKey.String("clustering") - // Broadcasting consumption model - MessagingRocketmqConsumptionModelBroadcasting = MessagingRocketmqConsumptionModelKey.String("broadcasting") -) - -var ( - // Normal message - MessagingRocketmqMessageTypeNormal = MessagingRocketmqMessageTypeKey.String("normal") - // FIFO message - MessagingRocketmqMessageTypeFifo = MessagingRocketmqMessageTypeKey.String("fifo") - // Delay message - MessagingRocketmqMessageTypeDelay = MessagingRocketmqMessageTypeKey.String("delay") - // Transaction message - MessagingRocketmqMessageTypeTransaction = MessagingRocketmqMessageTypeKey.String("transaction") -) - -// MessagingRocketmqClientGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.client_group" semantic conventions. It represents -// the name of the RocketMQ producer/consumer group that is handling the -// message. The client type is identified by the SpanKind. -func MessagingRocketmqClientGroup(val string) attribute.KeyValue { - return MessagingRocketmqClientGroupKey.String(val) -} - -// MessagingRocketmqMessageDelayTimeLevel returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delay_time_level" semantic -// conventions. It represents the delay time level for delay message, which -// determines the message delay time. -func MessagingRocketmqMessageDelayTimeLevel(val int) attribute.KeyValue { - return MessagingRocketmqMessageDelayTimeLevelKey.Int(val) -} - -// MessagingRocketmqMessageDeliveryTimestamp returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delivery_timestamp" semantic -// conventions. It represents the timestamp in milliseconds that the delay -// message is expected to be delivered to consumer. -func MessagingRocketmqMessageDeliveryTimestamp(val int) attribute.KeyValue { - return MessagingRocketmqMessageDeliveryTimestampKey.Int(val) -} - -// MessagingRocketmqMessageGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.group" semantic conventions. It represents -// the it is essential for FIFO message. Messages that belong to the same -// message group are always processed one by one within the same consumer -// group. -func MessagingRocketmqMessageGroup(val string) attribute.KeyValue { - return MessagingRocketmqMessageGroupKey.String(val) -} - -// MessagingRocketmqMessageKeys returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.keys" semantic conventions. It represents -// the key(s) of message, another way to mark message besides message id. -func MessagingRocketmqMessageKeys(val ...string) attribute.KeyValue { - return MessagingRocketmqMessageKeysKey.StringSlice(val) -} - -// MessagingRocketmqMessageTag returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.tag" semantic conventions. It represents the -// secondary classifier of message besides topic. -func MessagingRocketmqMessageTag(val string) attribute.KeyValue { - return MessagingRocketmqMessageTagKey.String(val) -} - -// MessagingRocketmqNamespace returns an attribute KeyValue conforming to -// the "messaging.rocketmq.namespace" semantic conventions. It represents the -// namespace of RocketMQ resources, resources in different namespaces are -// individual. -func MessagingRocketmqNamespace(val string) attribute.KeyValue { - return MessagingRocketmqNamespaceKey.String(val) -} - -// This group describes attributes specific to GCP Pub/Sub. -const ( - // MessagingGCPPubsubMessageAckDeadlineKey is the attribute Key conforming - // to the "messaging.gcp_pubsub.message.ack_deadline" semantic conventions. - // It represents the ack deadline in seconds set for the modify ack - // deadline request. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - MessagingGCPPubsubMessageAckDeadlineKey = attribute.Key("messaging.gcp_pubsub.message.ack_deadline") - - // MessagingGCPPubsubMessageAckIDKey is the attribute Key conforming to the - // "messaging.gcp_pubsub.message.ack_id" semantic conventions. It - // represents the ack id for a given message. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ack_id' - MessagingGCPPubsubMessageAckIDKey = attribute.Key("messaging.gcp_pubsub.message.ack_id") - - // MessagingGCPPubsubMessageDeliveryAttemptKey is the attribute Key - // conforming to the "messaging.gcp_pubsub.message.delivery_attempt" - // semantic conventions. It represents the delivery attempt for a given - // message. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 2 - MessagingGCPPubsubMessageDeliveryAttemptKey = attribute.Key("messaging.gcp_pubsub.message.delivery_attempt") - - // MessagingGCPPubsubMessageOrderingKeyKey is the attribute Key conforming - // to the "messaging.gcp_pubsub.message.ordering_key" semantic conventions. - // It represents the ordering key for a given message. If the attribute is - // not present, the message does not have an ordering key. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ordering_key' - MessagingGCPPubsubMessageOrderingKeyKey = attribute.Key("messaging.gcp_pubsub.message.ordering_key") -) - -// MessagingGCPPubsubMessageAckDeadline returns an attribute KeyValue -// conforming to the "messaging.gcp_pubsub.message.ack_deadline" semantic -// conventions. It represents the ack deadline in seconds set for the modify -// ack deadline request. -func MessagingGCPPubsubMessageAckDeadline(val int) attribute.KeyValue { - return MessagingGCPPubsubMessageAckDeadlineKey.Int(val) -} - -// MessagingGCPPubsubMessageAckID returns an attribute KeyValue conforming -// to the "messaging.gcp_pubsub.message.ack_id" semantic conventions. It -// represents the ack id for a given message. -func MessagingGCPPubsubMessageAckID(val string) attribute.KeyValue { - return MessagingGCPPubsubMessageAckIDKey.String(val) -} - -// MessagingGCPPubsubMessageDeliveryAttempt returns an attribute KeyValue -// conforming to the "messaging.gcp_pubsub.message.delivery_attempt" semantic -// conventions. It represents the delivery attempt for a given message. -func MessagingGCPPubsubMessageDeliveryAttempt(val int) attribute.KeyValue { - return MessagingGCPPubsubMessageDeliveryAttemptKey.Int(val) -} - -// MessagingGCPPubsubMessageOrderingKey returns an attribute KeyValue -// conforming to the "messaging.gcp_pubsub.message.ordering_key" semantic -// conventions. It represents the ordering key for a given message. If the -// attribute is not present, the message does not have an ordering key. -func MessagingGCPPubsubMessageOrderingKey(val string) attribute.KeyValue { - return MessagingGCPPubsubMessageOrderingKeyKey.String(val) -} - -// This group describes attributes specific to Azure Service Bus. -const ( - // MessagingServicebusDestinationSubscriptionNameKey is the attribute Key - // conforming to the "messaging.servicebus.destination.subscription_name" - // semantic conventions. It represents the name of the subscription in the - // topic messages are received from. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mySubscription' - MessagingServicebusDestinationSubscriptionNameKey = attribute.Key("messaging.servicebus.destination.subscription_name") - - // MessagingServicebusDispositionStatusKey is the attribute Key conforming - // to the "messaging.servicebus.disposition_status" semantic conventions. - // It represents the describes the [settlement - // type](https://learn.microsoft.com/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingServicebusDispositionStatusKey = attribute.Key("messaging.servicebus.disposition_status") - - // MessagingServicebusMessageDeliveryCountKey is the attribute Key - // conforming to the "messaging.servicebus.message.delivery_count" semantic - // conventions. It represents the number of deliveries that have been - // attempted for this message. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 2 - MessagingServicebusMessageDeliveryCountKey = attribute.Key("messaging.servicebus.message.delivery_count") - - // MessagingServicebusMessageEnqueuedTimeKey is the attribute Key - // conforming to the "messaging.servicebus.message.enqueued_time" semantic - // conventions. It represents the UTC epoch seconds at which the message - // has been accepted and stored in the entity. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1701393730 - MessagingServicebusMessageEnqueuedTimeKey = attribute.Key("messaging.servicebus.message.enqueued_time") -) - -var ( - // Message is completed - MessagingServicebusDispositionStatusComplete = MessagingServicebusDispositionStatusKey.String("complete") - // Message is abandoned - MessagingServicebusDispositionStatusAbandon = MessagingServicebusDispositionStatusKey.String("abandon") - // Message is sent to dead letter queue - MessagingServicebusDispositionStatusDeadLetter = MessagingServicebusDispositionStatusKey.String("dead_letter") - // Message is deferred - MessagingServicebusDispositionStatusDefer = MessagingServicebusDispositionStatusKey.String("defer") -) - -// MessagingServicebusDestinationSubscriptionName returns an attribute -// KeyValue conforming to the -// "messaging.servicebus.destination.subscription_name" semantic conventions. -// It represents the name of the subscription in the topic messages are -// received from. -func MessagingServicebusDestinationSubscriptionName(val string) attribute.KeyValue { - return MessagingServicebusDestinationSubscriptionNameKey.String(val) -} - -// MessagingServicebusMessageDeliveryCount returns an attribute KeyValue -// conforming to the "messaging.servicebus.message.delivery_count" semantic -// conventions. It represents the number of deliveries that have been attempted -// for this message. -func MessagingServicebusMessageDeliveryCount(val int) attribute.KeyValue { - return MessagingServicebusMessageDeliveryCountKey.Int(val) -} - -// MessagingServicebusMessageEnqueuedTime returns an attribute KeyValue -// conforming to the "messaging.servicebus.message.enqueued_time" semantic -// conventions. It represents the UTC epoch seconds at which the message has -// been accepted and stored in the entity. -func MessagingServicebusMessageEnqueuedTime(val int) attribute.KeyValue { - return MessagingServicebusMessageEnqueuedTimeKey.Int(val) -} - -// This group describes attributes specific to Azure Event Hubs. -const ( - // MessagingEventhubsConsumerGroupKey is the attribute Key conforming to - // the "messaging.eventhubs.consumer.group" semantic conventions. It - // represents the name of the consumer group the event consumer is - // associated with. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'indexer' - MessagingEventhubsConsumerGroupKey = attribute.Key("messaging.eventhubs.consumer.group") - - // MessagingEventhubsMessageEnqueuedTimeKey is the attribute Key conforming - // to the "messaging.eventhubs.message.enqueued_time" semantic conventions. - // It represents the UTC epoch seconds at which the message has been - // accepted and stored in the entity. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1701393730 - MessagingEventhubsMessageEnqueuedTimeKey = attribute.Key("messaging.eventhubs.message.enqueued_time") -) - -// MessagingEventhubsConsumerGroup returns an attribute KeyValue conforming -// to the "messaging.eventhubs.consumer.group" semantic conventions. It -// represents the name of the consumer group the event consumer is associated -// with. -func MessagingEventhubsConsumerGroup(val string) attribute.KeyValue { - return MessagingEventhubsConsumerGroupKey.String(val) -} - -// MessagingEventhubsMessageEnqueuedTime returns an attribute KeyValue -// conforming to the "messaging.eventhubs.message.enqueued_time" semantic -// conventions. It represents the UTC epoch seconds at which the message has -// been accepted and stored in the entity. -func MessagingEventhubsMessageEnqueuedTime(val int) attribute.KeyValue { - return MessagingEventhubsMessageEnqueuedTimeKey.Int(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetworkCarrierIccKey is the attribute Key conforming to the - // "network.carrier.icc" semantic conventions. It represents the ISO 3166-1 - // alpha-2 2-character country code associated with the mobile carrier - // network. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'DE' - NetworkCarrierIccKey = attribute.Key("network.carrier.icc") - - // NetworkCarrierMccKey is the attribute Key conforming to the - // "network.carrier.mcc" semantic conventions. It represents the mobile - // carrier country code. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '310' - NetworkCarrierMccKey = attribute.Key("network.carrier.mcc") - - // NetworkCarrierMncKey is the attribute Key conforming to the - // "network.carrier.mnc" semantic conventions. It represents the mobile - // carrier network code. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '001' - NetworkCarrierMncKey = attribute.Key("network.carrier.mnc") - - // NetworkCarrierNameKey is the attribute Key conforming to the - // "network.carrier.name" semantic conventions. It represents the name of - // the mobile carrier. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'sprint' - NetworkCarrierNameKey = attribute.Key("network.carrier.name") - - // NetworkConnectionSubtypeKey is the attribute Key conforming to the - // "network.connection.subtype" semantic conventions. It represents the - // this describes more details regarding the connection.type. It may be the - // type of cell technology connection, but it could be used for describing - // details about a wifi connection. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'LTE' - NetworkConnectionSubtypeKey = attribute.Key("network.connection.subtype") - - // NetworkConnectionTypeKey is the attribute Key conforming to the - // "network.connection.type" semantic conventions. It represents the - // internet connection type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'wifi' - NetworkConnectionTypeKey = attribute.Key("network.connection.type") - - // NetworkIoDirectionKey is the attribute Key conforming to the - // "network.io.direction" semantic conventions. It represents the network - // IO operation direction. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'transmit' - NetworkIoDirectionKey = attribute.Key("network.io.direction") - - // NetworkLocalAddressKey is the attribute Key conforming to the - // "network.local.address" semantic conventions. It represents the local - // address of the network connection - IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10.1.2.80', '/tmp/my.sock' - NetworkLocalAddressKey = attribute.Key("network.local.address") - - // NetworkLocalPortKey is the attribute Key conforming to the - // "network.local.port" semantic conventions. It represents the local port - // number of the network connection. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - NetworkLocalPortKey = attribute.Key("network.local.port") - - // NetworkPeerAddressKey is the attribute Key conforming to the - // "network.peer.address" semantic conventions. It represents the peer - // address of the network connection - IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10.1.2.80', '/tmp/my.sock' - NetworkPeerAddressKey = attribute.Key("network.peer.address") - - // NetworkPeerPortKey is the attribute Key conforming to the - // "network.peer.port" semantic conventions. It represents the peer port - // number of the network connection. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - NetworkPeerPortKey = attribute.Key("network.peer.port") - - // NetworkProtocolNameKey is the attribute Key conforming to the - // "network.protocol.name" semantic conventions. It represents the [OSI - // application layer](https://osi-model.com/application-layer/) or non-OSI - // equivalent. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'amqp', 'http', 'mqtt' - // Note: The value SHOULD be normalized to lowercase. - NetworkProtocolNameKey = attribute.Key("network.protocol.name") - - // NetworkProtocolVersionKey is the attribute Key conforming to the - // "network.protocol.version" semantic conventions. It represents the - // actual version of the protocol used for network communication. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.1', '2' - // Note: If protocol version is subject to negotiation (for example using - // [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute - // SHOULD be set to the negotiated version. If the actual protocol version - // is not known, this attribute SHOULD NOT be set. - NetworkProtocolVersionKey = attribute.Key("network.protocol.version") - - // NetworkTransportKey is the attribute Key conforming to the - // "network.transport" semantic conventions. It represents the [OSI - // transport layer](https://osi-model.com/transport-layer/) or - // [inter-process communication - // method](https://wikipedia.org/wiki/Inter-process_communication). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'tcp', 'udp' - // Note: The value SHOULD be normalized to lowercase. - // - // Consider always setting the transport when setting a port number, since - // a port number is ambiguous without knowing the transport. For example - // different processes could be listening on TCP port 12345 and UDP port - // 12345. - NetworkTransportKey = attribute.Key("network.transport") - - // NetworkTypeKey is the attribute Key conforming to the "network.type" - // semantic conventions. It represents the [OSI network - // layer](https://osi-model.com/network-layer/) or non-OSI equivalent. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ipv4', 'ipv6' - // Note: The value SHOULD be normalized to lowercase. - NetworkTypeKey = attribute.Key("network.type") -) - -var ( - // GPRS - NetworkConnectionSubtypeGprs = NetworkConnectionSubtypeKey.String("gprs") - // EDGE - NetworkConnectionSubtypeEdge = NetworkConnectionSubtypeKey.String("edge") - // UMTS - NetworkConnectionSubtypeUmts = NetworkConnectionSubtypeKey.String("umts") - // CDMA - NetworkConnectionSubtypeCdma = NetworkConnectionSubtypeKey.String("cdma") - // EVDO Rel. 0 - NetworkConnectionSubtypeEvdo0 = NetworkConnectionSubtypeKey.String("evdo_0") - // EVDO Rev. A - NetworkConnectionSubtypeEvdoA = NetworkConnectionSubtypeKey.String("evdo_a") - // CDMA2000 1XRTT - NetworkConnectionSubtypeCdma20001xrtt = NetworkConnectionSubtypeKey.String("cdma2000_1xrtt") - // HSDPA - NetworkConnectionSubtypeHsdpa = NetworkConnectionSubtypeKey.String("hsdpa") - // HSUPA - NetworkConnectionSubtypeHsupa = NetworkConnectionSubtypeKey.String("hsupa") - // HSPA - NetworkConnectionSubtypeHspa = NetworkConnectionSubtypeKey.String("hspa") - // IDEN - NetworkConnectionSubtypeIden = NetworkConnectionSubtypeKey.String("iden") - // EVDO Rev. B - NetworkConnectionSubtypeEvdoB = NetworkConnectionSubtypeKey.String("evdo_b") - // LTE - NetworkConnectionSubtypeLte = NetworkConnectionSubtypeKey.String("lte") - // EHRPD - NetworkConnectionSubtypeEhrpd = NetworkConnectionSubtypeKey.String("ehrpd") - // HSPAP - NetworkConnectionSubtypeHspap = NetworkConnectionSubtypeKey.String("hspap") - // GSM - NetworkConnectionSubtypeGsm = NetworkConnectionSubtypeKey.String("gsm") - // TD-SCDMA - NetworkConnectionSubtypeTdScdma = NetworkConnectionSubtypeKey.String("td_scdma") - // IWLAN - NetworkConnectionSubtypeIwlan = NetworkConnectionSubtypeKey.String("iwlan") - // 5G NR (New Radio) - NetworkConnectionSubtypeNr = NetworkConnectionSubtypeKey.String("nr") - // 5G NRNSA (New Radio Non-Standalone) - NetworkConnectionSubtypeNrnsa = NetworkConnectionSubtypeKey.String("nrnsa") - // LTE CA - NetworkConnectionSubtypeLteCa = NetworkConnectionSubtypeKey.String("lte_ca") -) - -var ( - // wifi - NetworkConnectionTypeWifi = NetworkConnectionTypeKey.String("wifi") - // wired - NetworkConnectionTypeWired = NetworkConnectionTypeKey.String("wired") - // cell - NetworkConnectionTypeCell = NetworkConnectionTypeKey.String("cell") - // unavailable - NetworkConnectionTypeUnavailable = NetworkConnectionTypeKey.String("unavailable") - // unknown - NetworkConnectionTypeUnknown = NetworkConnectionTypeKey.String("unknown") -) - -var ( - // transmit - NetworkIoDirectionTransmit = NetworkIoDirectionKey.String("transmit") - // receive - NetworkIoDirectionReceive = NetworkIoDirectionKey.String("receive") -) - -var ( - // TCP - NetworkTransportTCP = NetworkTransportKey.String("tcp") - // UDP - NetworkTransportUDP = NetworkTransportKey.String("udp") - // Named or anonymous pipe - NetworkTransportPipe = NetworkTransportKey.String("pipe") - // Unix domain socket - NetworkTransportUnix = NetworkTransportKey.String("unix") -) - -var ( - // IPv4 - NetworkTypeIpv4 = NetworkTypeKey.String("ipv4") - // IPv6 - NetworkTypeIpv6 = NetworkTypeKey.String("ipv6") -) - -// NetworkCarrierIcc returns an attribute KeyValue conforming to the -// "network.carrier.icc" semantic conventions. It represents the ISO 3166-1 -// alpha-2 2-character country code associated with the mobile carrier network. -func NetworkCarrierIcc(val string) attribute.KeyValue { - return NetworkCarrierIccKey.String(val) -} - -// NetworkCarrierMcc returns an attribute KeyValue conforming to the -// "network.carrier.mcc" semantic conventions. It represents the mobile carrier -// country code. -func NetworkCarrierMcc(val string) attribute.KeyValue { - return NetworkCarrierMccKey.String(val) -} - -// NetworkCarrierMnc returns an attribute KeyValue conforming to the -// "network.carrier.mnc" semantic conventions. It represents the mobile carrier -// network code. -func NetworkCarrierMnc(val string) attribute.KeyValue { - return NetworkCarrierMncKey.String(val) -} - -// NetworkCarrierName returns an attribute KeyValue conforming to the -// "network.carrier.name" semantic conventions. It represents the name of the -// mobile carrier. -func NetworkCarrierName(val string) attribute.KeyValue { - return NetworkCarrierNameKey.String(val) -} - -// NetworkLocalAddress returns an attribute KeyValue conforming to the -// "network.local.address" semantic conventions. It represents the local -// address of the network connection - IP address or Unix domain socket name. -func NetworkLocalAddress(val string) attribute.KeyValue { - return NetworkLocalAddressKey.String(val) -} - -// NetworkLocalPort returns an attribute KeyValue conforming to the -// "network.local.port" semantic conventions. It represents the local port -// number of the network connection. -func NetworkLocalPort(val int) attribute.KeyValue { - return NetworkLocalPortKey.Int(val) -} - -// NetworkPeerAddress returns an attribute KeyValue conforming to the -// "network.peer.address" semantic conventions. It represents the peer address -// of the network connection - IP address or Unix domain socket name. -func NetworkPeerAddress(val string) attribute.KeyValue { - return NetworkPeerAddressKey.String(val) -} - -// NetworkPeerPort returns an attribute KeyValue conforming to the -// "network.peer.port" semantic conventions. It represents the peer port number -// of the network connection. -func NetworkPeerPort(val int) attribute.KeyValue { - return NetworkPeerPortKey.Int(val) -} - -// NetworkProtocolName returns an attribute KeyValue conforming to the -// "network.protocol.name" semantic conventions. It represents the [OSI -// application layer](https://osi-model.com/application-layer/) or non-OSI -// equivalent. -func NetworkProtocolName(val string) attribute.KeyValue { - return NetworkProtocolNameKey.String(val) -} - -// NetworkProtocolVersion returns an attribute KeyValue conforming to the -// "network.protocol.version" semantic conventions. It represents the actual -// version of the protocol used for network communication. -func NetworkProtocolVersion(val string) attribute.KeyValue { - return NetworkProtocolVersionKey.String(val) -} - -// An OCI image manifest. -const ( - // OciManifestDigestKey is the attribute Key conforming to the - // "oci.manifest.digest" semantic conventions. It represents the digest of - // the OCI image manifest. For container images specifically is the digest - // by which the container image is known. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'sha256:e4ca62c0d62f3e886e684806dfe9d4e0cda60d54986898173c1083856cfda0f4' - // Note: Follows [OCI Image Manifest - // Specification](https://github.com/opencontainers/image-spec/blob/main/manifest.md), - // and specifically the [Digest - // property](https://github.com/opencontainers/image-spec/blob/main/descriptor.md#digests). - // An example can be found in [Example Image - // Manifest](https://docs.docker.com/registry/spec/manifest-v2-2/#example-image-manifest). - OciManifestDigestKey = attribute.Key("oci.manifest.digest") -) - -// OciManifestDigest returns an attribute KeyValue conforming to the -// "oci.manifest.digest" semantic conventions. It represents the digest of the -// OCI image manifest. For container images specifically is the digest by which -// the container image is known. -func OciManifestDigest(val string) attribute.KeyValue { - return OciManifestDigestKey.String(val) -} - -// Attributes used by the OpenTracing Shim layer. -const ( - // OpentracingRefTypeKey is the attribute Key conforming to the - // "opentracing.ref_type" semantic conventions. It represents the - // parent-child Reference type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The causal relationship between a child Span and a parent Span. - OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") -) - -var ( - // The parent Span depends on the child Span in some capacity - OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") - // The parent Span doesn't depend in any way on the result of the child Span - OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") -) - -// The operating system (OS) on which the process represented by this resource -// is running. -const ( - // OSBuildIDKey is the attribute Key conforming to the "os.build_id" - // semantic conventions. It represents the unique identifier for a - // particular build or compilation of the operating system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'TQ3C.230805.001.B2', '20E247', '22621' - OSBuildIDKey = attribute.Key("os.build_id") - - // OSDescriptionKey is the attribute Key conforming to the "os.description" - // semantic conventions. It represents the human readable (not intended to - // be parsed) OS version information, like e.g. reported by `ver` or - // `lsb_release -a` commands. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Microsoft Windows [Version 10.0.18363.778]', 'Ubuntu 18.04.1 - // LTS' - OSDescriptionKey = attribute.Key("os.description") - - // OSNameKey is the attribute Key conforming to the "os.name" semantic - // conventions. It represents the human readable operating system name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iOS', 'Android', 'Ubuntu' - OSNameKey = attribute.Key("os.name") - - // OSTypeKey is the attribute Key conforming to the "os.type" semantic - // conventions. It represents the operating system type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - OSTypeKey = attribute.Key("os.type") - - // OSVersionKey is the attribute Key conforming to the "os.version" - // semantic conventions. It represents the version string of the operating - // system as defined in [Version - // Attributes](/docs/resource/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '14.2.1', '18.04.1' - OSVersionKey = attribute.Key("os.version") -) - -var ( - // Microsoft Windows - OSTypeWindows = OSTypeKey.String("windows") - // Linux - OSTypeLinux = OSTypeKey.String("linux") - // Apple Darwin - OSTypeDarwin = OSTypeKey.String("darwin") - // FreeBSD - OSTypeFreeBSD = OSTypeKey.String("freebsd") - // NetBSD - OSTypeNetBSD = OSTypeKey.String("netbsd") - // OpenBSD - OSTypeOpenBSD = OSTypeKey.String("openbsd") - // DragonFly BSD - OSTypeDragonflyBSD = OSTypeKey.String("dragonflybsd") - // HP-UX (Hewlett Packard Unix) - OSTypeHPUX = OSTypeKey.String("hpux") - // AIX (Advanced Interactive eXecutive) - OSTypeAIX = OSTypeKey.String("aix") - // SunOS, Oracle Solaris - OSTypeSolaris = OSTypeKey.String("solaris") - // IBM z/OS - OSTypeZOS = OSTypeKey.String("z_os") -) - -// OSBuildID returns an attribute KeyValue conforming to the "os.build_id" -// semantic conventions. It represents the unique identifier for a particular -// build or compilation of the operating system. -func OSBuildID(val string) attribute.KeyValue { - return OSBuildIDKey.String(val) -} - -// OSDescription returns an attribute KeyValue conforming to the -// "os.description" semantic conventions. It represents the human readable (not -// intended to be parsed) OS version information, like e.g. reported by `ver` -// or `lsb_release -a` commands. -func OSDescription(val string) attribute.KeyValue { - return OSDescriptionKey.String(val) -} - -// OSName returns an attribute KeyValue conforming to the "os.name" semantic -// conventions. It represents the human readable operating system name. -func OSName(val string) attribute.KeyValue { - return OSNameKey.String(val) -} - -// OSVersion returns an attribute KeyValue conforming to the "os.version" -// semantic conventions. It represents the version string of the operating -// system as defined in [Version -// Attributes](/docs/resource/README.md#version-attributes). -func OSVersion(val string) attribute.KeyValue { - return OSVersionKey.String(val) -} - -// Attributes reserved for OpenTelemetry -const ( - // OTelStatusCodeKey is the attribute Key conforming to the - // "otel.status_code" semantic conventions. It represents the name of the - // code, either "OK" or "ERROR". MUST NOT be set if the status code is - // UNSET. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - OTelStatusCodeKey = attribute.Key("otel.status_code") - - // OTelStatusDescriptionKey is the attribute Key conforming to the - // "otel.status_description" semantic conventions. It represents the - // description of the Status if it has a value, otherwise not set. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'resource not found' - OTelStatusDescriptionKey = attribute.Key("otel.status_description") -) - -var ( - // The operation has been validated by an Application developer or Operator to have completed successfully - OTelStatusCodeOk = OTelStatusCodeKey.String("OK") - // The operation contains an error - OTelStatusCodeError = OTelStatusCodeKey.String("ERROR") -) - -// OTelStatusDescription returns an attribute KeyValue conforming to the -// "otel.status_description" semantic conventions. It represents the -// description of the Status if it has a value, otherwise not set. -func OTelStatusDescription(val string) attribute.KeyValue { - return OTelStatusDescriptionKey.String(val) -} - -// Attributes used by non-OTLP exporters to represent OpenTelemetry Scope's -// concepts. -const ( - // OTelScopeNameKey is the attribute Key conforming to the - // "otel.scope.name" semantic conventions. It represents the name of the - // instrumentation scope - (`InstrumentationScope.Name` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'io.opentelemetry.contrib.mongodb' - OTelScopeNameKey = attribute.Key("otel.scope.name") - - // OTelScopeVersionKey is the attribute Key conforming to the - // "otel.scope.version" semantic conventions. It represents the version of - // the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.0.0' - OTelScopeVersionKey = attribute.Key("otel.scope.version") -) - -// OTelScopeName returns an attribute KeyValue conforming to the -// "otel.scope.name" semantic conventions. It represents the name of the -// instrumentation scope - (`InstrumentationScope.Name` in OTLP). -func OTelScopeName(val string) attribute.KeyValue { - return OTelScopeNameKey.String(val) -} - -// OTelScopeVersion returns an attribute KeyValue conforming to the -// "otel.scope.version" semantic conventions. It represents the version of the -// instrumentation scope - (`InstrumentationScope.Version` in OTLP). -func OTelScopeVersion(val string) attribute.KeyValue { - return OTelScopeVersionKey.String(val) -} - -// Operations that access some remote service. -const ( - // PeerServiceKey is the attribute Key conforming to the "peer.service" - // semantic conventions. It represents the - // [`service.name`](/docs/resource/README.md#service) of the remote - // service. SHOULD be equal to the actual `service.name` resource attribute - // of the remote service if any. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'AuthTokenCache' - PeerServiceKey = attribute.Key("peer.service") -) - -// PeerService returns an attribute KeyValue conforming to the -// "peer.service" semantic conventions. It represents the -// [`service.name`](/docs/resource/README.md#service) of the remote service. -// SHOULD be equal to the actual `service.name` resource attribute of the -// remote service if any. -func PeerService(val string) attribute.KeyValue { - return PeerServiceKey.String(val) -} - -// An operating system process. -const ( - // ProcessCommandKey is the attribute Key conforming to the - // "process.command" semantic conventions. It represents the command used - // to launch the process (i.e. the command name). On Linux based systems, - // can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can - // be set to the first parameter extracted from `GetCommandLineW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'cmd/otelcol' - ProcessCommandKey = attribute.Key("process.command") - - // ProcessCommandArgsKey is the attribute Key conforming to the - // "process.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) as received - // by the process. On Linux-based systems (and some other Unixoid systems - // supporting procfs), can be set according to the list of null-delimited - // strings extracted from `proc/[pid]/cmdline`. For libc-based executables, - // this would be the full argv vector passed to `main`. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'cmd/otecol', '--config=config.yaml' - ProcessCommandArgsKey = attribute.Key("process.command_args") - - // ProcessCommandLineKey is the attribute Key conforming to the - // "process.command_line" semantic conventions. It represents the full - // command used to launch the process as a single string representing the - // full command. On Windows, can be set to the result of `GetCommandLineW`. - // Do not set this if you have to assemble it just for monitoring; use - // `process.command_args` instead. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'C:\\cmd\\otecol --config="my directory\\config.yaml"' - ProcessCommandLineKey = attribute.Key("process.command_line") - - // ProcessContextSwitchTypeKey is the attribute Key conforming to the - // "process.context_switch_type" semantic conventions. It represents the - // specifies whether the context switches for this data point were - // voluntary or involuntary. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - ProcessContextSwitchTypeKey = attribute.Key("process.context_switch_type") - - // ProcessCreationTimeKey is the attribute Key conforming to the - // "process.creation.time" semantic conventions. It represents the date and - // time the process was created, in ISO 8601 format. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2023-11-21T09:25:34.853Z' - ProcessCreationTimeKey = attribute.Key("process.creation.time") - - // ProcessExecutableNameKey is the attribute Key conforming to the - // "process.executable.name" semantic conventions. It represents the name - // of the process executable. On Linux based systems, can be set to the - // `Name` in `proc/[pid]/status`. On Windows, can be set to the base name - // of `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcol' - ProcessExecutableNameKey = attribute.Key("process.executable.name") - - // ProcessExecutablePathKey is the attribute Key conforming to the - // "process.executable.path" semantic conventions. It represents the full - // path to the process executable. On Linux based systems, can be set to - // the target of `proc/[pid]/exe`. On Windows, can be set to the result of - // `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/usr/bin/cmd/otelcol' - ProcessExecutablePathKey = attribute.Key("process.executable.path") - - // ProcessExitCodeKey is the attribute Key conforming to the - // "process.exit.code" semantic conventions. It represents the exit code of - // the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 127 - ProcessExitCodeKey = attribute.Key("process.exit.code") - - // ProcessExitTimeKey is the attribute Key conforming to the - // "process.exit.time" semantic conventions. It represents the date and - // time the process exited, in ISO 8601 format. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2023-11-21T09:26:12.315Z' - ProcessExitTimeKey = attribute.Key("process.exit.time") - - // ProcessGroupLeaderPIDKey is the attribute Key conforming to the - // "process.group_leader.pid" semantic conventions. It represents the PID - // of the process's group leader. This is also the process group ID (PGID) - // of the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 23 - ProcessGroupLeaderPIDKey = attribute.Key("process.group_leader.pid") - - // ProcessInteractiveKey is the attribute Key conforming to the - // "process.interactive" semantic conventions. It represents the whether - // the process is connected to an interactive shell. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - ProcessInteractiveKey = attribute.Key("process.interactive") - - // ProcessOwnerKey is the attribute Key conforming to the "process.owner" - // semantic conventions. It represents the username of the user that owns - // the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'root' - ProcessOwnerKey = attribute.Key("process.owner") - - // ProcessPagingFaultTypeKey is the attribute Key conforming to the - // "process.paging.fault_type" semantic conventions. It represents the type - // of page fault for this data point. Type `major` is for major/hard page - // faults, and `minor` is for minor/soft page faults. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - ProcessPagingFaultTypeKey = attribute.Key("process.paging.fault_type") - - // ProcessParentPIDKey is the attribute Key conforming to the - // "process.parent_pid" semantic conventions. It represents the parent - // Process identifier (PPID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 111 - ProcessParentPIDKey = attribute.Key("process.parent_pid") - - // ProcessPIDKey is the attribute Key conforming to the "process.pid" - // semantic conventions. It represents the process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1234 - ProcessPIDKey = attribute.Key("process.pid") - - // ProcessRealUserIDKey is the attribute Key conforming to the - // "process.real_user.id" semantic conventions. It represents the real user - // ID (RUID) of the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1000 - ProcessRealUserIDKey = attribute.Key("process.real_user.id") - - // ProcessRealUserNameKey is the attribute Key conforming to the - // "process.real_user.name" semantic conventions. It represents the - // username of the real user of the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'operator' - ProcessRealUserNameKey = attribute.Key("process.real_user.name") - - // ProcessRuntimeDescriptionKey is the attribute Key conforming to the - // "process.runtime.description" semantic conventions. It represents an - // additional description about the runtime of the process, for example a - // specific vendor customization of the runtime environment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0' - ProcessRuntimeDescriptionKey = attribute.Key("process.runtime.description") - - // ProcessRuntimeNameKey is the attribute Key conforming to the - // "process.runtime.name" semantic conventions. It represents the name of - // the runtime of this process. For compiled native binaries, this SHOULD - // be the name of the compiler. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'OpenJDK Runtime Environment' - ProcessRuntimeNameKey = attribute.Key("process.runtime.name") - - // ProcessRuntimeVersionKey is the attribute Key conforming to the - // "process.runtime.version" semantic conventions. It represents the - // version of the runtime of this process, as returned by the runtime - // without modification. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '14.0.2' - ProcessRuntimeVersionKey = attribute.Key("process.runtime.version") - - // ProcessSavedUserIDKey is the attribute Key conforming to the - // "process.saved_user.id" semantic conventions. It represents the saved - // user ID (SUID) of the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1002 - ProcessSavedUserIDKey = attribute.Key("process.saved_user.id") - - // ProcessSavedUserNameKey is the attribute Key conforming to the - // "process.saved_user.name" semantic conventions. It represents the - // username of the saved user. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'operator' - ProcessSavedUserNameKey = attribute.Key("process.saved_user.name") - - // ProcessSessionLeaderPIDKey is the attribute Key conforming to the - // "process.session_leader.pid" semantic conventions. It represents the PID - // of the process's session leader. This is also the session ID (SID) of - // the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 14 - ProcessSessionLeaderPIDKey = attribute.Key("process.session_leader.pid") - - // ProcessUserIDKey is the attribute Key conforming to the - // "process.user.id" semantic conventions. It represents the effective user - // ID (EUID) of the process. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1001 - ProcessUserIDKey = attribute.Key("process.user.id") - - // ProcessUserNameKey is the attribute Key conforming to the - // "process.user.name" semantic conventions. It represents the username of - // the effective user of the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'root' - ProcessUserNameKey = attribute.Key("process.user.name") - - // ProcessVpidKey is the attribute Key conforming to the "process.vpid" - // semantic conventions. It represents the virtual process identifier. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 12 - // Note: The process ID within a PID namespace. This is not necessarily - // unique across all processes on the host but it is unique within the - // process namespace that the process exists within. - ProcessVpidKey = attribute.Key("process.vpid") -) - -var ( - // voluntary - ProcessContextSwitchTypeVoluntary = ProcessContextSwitchTypeKey.String("voluntary") - // involuntary - ProcessContextSwitchTypeInvoluntary = ProcessContextSwitchTypeKey.String("involuntary") -) - -var ( - // major - ProcessPagingFaultTypeMajor = ProcessPagingFaultTypeKey.String("major") - // minor - ProcessPagingFaultTypeMinor = ProcessPagingFaultTypeKey.String("minor") -) - -// ProcessCommand returns an attribute KeyValue conforming to the -// "process.command" semantic conventions. It represents the command used to -// launch the process (i.e. the command name). On Linux based systems, can be -// set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to -// the first parameter extracted from `GetCommandLineW`. -func ProcessCommand(val string) attribute.KeyValue { - return ProcessCommandKey.String(val) -} - -// ProcessCommandArgs returns an attribute KeyValue conforming to the -// "process.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) as received by -// the process. On Linux-based systems (and some other Unixoid systems -// supporting procfs), can be set according to the list of null-delimited -// strings extracted from `proc/[pid]/cmdline`. For libc-based executables, -// this would be the full argv vector passed to `main`. -func ProcessCommandArgs(val ...string) attribute.KeyValue { - return ProcessCommandArgsKey.StringSlice(val) -} - -// ProcessCommandLine returns an attribute KeyValue conforming to the -// "process.command_line" semantic conventions. It represents the full command -// used to launch the process as a single string representing the full command. -// On Windows, can be set to the result of `GetCommandLineW`. Do not set this -// if you have to assemble it just for monitoring; use `process.command_args` -// instead. -func ProcessCommandLine(val string) attribute.KeyValue { - return ProcessCommandLineKey.String(val) -} - -// ProcessCreationTime returns an attribute KeyValue conforming to the -// "process.creation.time" semantic conventions. It represents the date and -// time the process was created, in ISO 8601 format. -func ProcessCreationTime(val string) attribute.KeyValue { - return ProcessCreationTimeKey.String(val) -} - -// ProcessExecutableName returns an attribute KeyValue conforming to the -// "process.executable.name" semantic conventions. It represents the name of -// the process executable. On Linux based systems, can be set to the `Name` in -// `proc/[pid]/status`. On Windows, can be set to the base name of -// `GetProcessImageFileNameW`. -func ProcessExecutableName(val string) attribute.KeyValue { - return ProcessExecutableNameKey.String(val) -} - -// ProcessExecutablePath returns an attribute KeyValue conforming to the -// "process.executable.path" semantic conventions. It represents the full path -// to the process executable. On Linux based systems, can be set to the target -// of `proc/[pid]/exe`. On Windows, can be set to the result of -// `GetProcessImageFileNameW`. -func ProcessExecutablePath(val string) attribute.KeyValue { - return ProcessExecutablePathKey.String(val) -} - -// ProcessExitCode returns an attribute KeyValue conforming to the -// "process.exit.code" semantic conventions. It represents the exit code of the -// process. -func ProcessExitCode(val int) attribute.KeyValue { - return ProcessExitCodeKey.Int(val) -} - -// ProcessExitTime returns an attribute KeyValue conforming to the -// "process.exit.time" semantic conventions. It represents the date and time -// the process exited, in ISO 8601 format. -func ProcessExitTime(val string) attribute.KeyValue { - return ProcessExitTimeKey.String(val) -} - -// ProcessGroupLeaderPID returns an attribute KeyValue conforming to the -// "process.group_leader.pid" semantic conventions. It represents the PID of -// the process's group leader. This is also the process group ID (PGID) of the -// process. -func ProcessGroupLeaderPID(val int) attribute.KeyValue { - return ProcessGroupLeaderPIDKey.Int(val) -} - -// ProcessInteractive returns an attribute KeyValue conforming to the -// "process.interactive" semantic conventions. It represents the whether the -// process is connected to an interactive shell. -func ProcessInteractive(val bool) attribute.KeyValue { - return ProcessInteractiveKey.Bool(val) -} - -// ProcessOwner returns an attribute KeyValue conforming to the -// "process.owner" semantic conventions. It represents the username of the user -// that owns the process. -func ProcessOwner(val string) attribute.KeyValue { - return ProcessOwnerKey.String(val) -} - -// ProcessParentPID returns an attribute KeyValue conforming to the -// "process.parent_pid" semantic conventions. It represents the parent Process -// identifier (PPID). -func ProcessParentPID(val int) attribute.KeyValue { - return ProcessParentPIDKey.Int(val) -} - -// ProcessPID returns an attribute KeyValue conforming to the "process.pid" -// semantic conventions. It represents the process identifier (PID). -func ProcessPID(val int) attribute.KeyValue { - return ProcessPIDKey.Int(val) -} - -// ProcessRealUserID returns an attribute KeyValue conforming to the -// "process.real_user.id" semantic conventions. It represents the real user ID -// (RUID) of the process. -func ProcessRealUserID(val int) attribute.KeyValue { - return ProcessRealUserIDKey.Int(val) -} - -// ProcessRealUserName returns an attribute KeyValue conforming to the -// "process.real_user.name" semantic conventions. It represents the username of -// the real user of the process. -func ProcessRealUserName(val string) attribute.KeyValue { - return ProcessRealUserNameKey.String(val) -} - -// ProcessRuntimeDescription returns an attribute KeyValue conforming to the -// "process.runtime.description" semantic conventions. It represents an -// additional description about the runtime of the process, for example a -// specific vendor customization of the runtime environment. -func ProcessRuntimeDescription(val string) attribute.KeyValue { - return ProcessRuntimeDescriptionKey.String(val) -} - -// ProcessRuntimeName returns an attribute KeyValue conforming to the -// "process.runtime.name" semantic conventions. It represents the name of the -// runtime of this process. For compiled native binaries, this SHOULD be the -// name of the compiler. -func ProcessRuntimeName(val string) attribute.KeyValue { - return ProcessRuntimeNameKey.String(val) -} - -// ProcessRuntimeVersion returns an attribute KeyValue conforming to the -// "process.runtime.version" semantic conventions. It represents the version of -// the runtime of this process, as returned by the runtime without -// modification. -func ProcessRuntimeVersion(val string) attribute.KeyValue { - return ProcessRuntimeVersionKey.String(val) -} - -// ProcessSavedUserID returns an attribute KeyValue conforming to the -// "process.saved_user.id" semantic conventions. It represents the saved user -// ID (SUID) of the process. -func ProcessSavedUserID(val int) attribute.KeyValue { - return ProcessSavedUserIDKey.Int(val) -} - -// ProcessSavedUserName returns an attribute KeyValue conforming to the -// "process.saved_user.name" semantic conventions. It represents the username -// of the saved user. -func ProcessSavedUserName(val string) attribute.KeyValue { - return ProcessSavedUserNameKey.String(val) -} - -// ProcessSessionLeaderPID returns an attribute KeyValue conforming to the -// "process.session_leader.pid" semantic conventions. It represents the PID of -// the process's session leader. This is also the session ID (SID) of the -// process. -func ProcessSessionLeaderPID(val int) attribute.KeyValue { - return ProcessSessionLeaderPIDKey.Int(val) -} - -// ProcessUserID returns an attribute KeyValue conforming to the -// "process.user.id" semantic conventions. It represents the effective user ID -// (EUID) of the process. -func ProcessUserID(val int) attribute.KeyValue { - return ProcessUserIDKey.Int(val) -} - -// ProcessUserName returns an attribute KeyValue conforming to the -// "process.user.name" semantic conventions. It represents the username of the -// effective user of the process. -func ProcessUserName(val string) attribute.KeyValue { - return ProcessUserNameKey.String(val) -} - -// ProcessVpid returns an attribute KeyValue conforming to the -// "process.vpid" semantic conventions. It represents the virtual process -// identifier. -func ProcessVpid(val int) attribute.KeyValue { - return ProcessVpidKey.Int(val) -} - -// Attributes for process CPU -const ( - // ProcessCPUStateKey is the attribute Key conforming to the - // "process.cpu.state" semantic conventions. It represents the CPU state of - // the process. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - ProcessCPUStateKey = attribute.Key("process.cpu.state") -) - -var ( - // system - ProcessCPUStateSystem = ProcessCPUStateKey.String("system") - // user - ProcessCPUStateUser = ProcessCPUStateKey.String("user") - // wait - ProcessCPUStateWait = ProcessCPUStateKey.String("wait") -) - -// Attributes for remote procedure calls. -const ( - // RPCConnectRPCErrorCodeKey is the attribute Key conforming to the - // "rpc.connect_rpc.error_code" semantic conventions. It represents the - // [error codes](https://connect.build/docs/protocol/#error-codes) of the - // Connect request. Error codes are always string values. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCConnectRPCErrorCodeKey = attribute.Key("rpc.connect_rpc.error_code") - - // RPCGRPCStatusCodeKey is the attribute Key conforming to the - // "rpc.grpc.status_code" semantic conventions. It represents the [numeric - // status - // code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of - // the gRPC request. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCGRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") - - // RPCJsonrpcErrorCodeKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_code" semantic conventions. It represents the - // `error.code` property of response if it is an error response. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: -32700, 100 - RPCJsonrpcErrorCodeKey = attribute.Key("rpc.jsonrpc.error_code") - - // RPCJsonrpcErrorMessageKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_message" semantic conventions. It represents the - // `error.message` property of response if it is an error response. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Parse error', 'User already exists' - RPCJsonrpcErrorMessageKey = attribute.Key("rpc.jsonrpc.error_message") - - // RPCJsonrpcRequestIDKey is the attribute Key conforming to the - // "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` - // property of request or response. Since protocol allows id to be int, - // string, `null` or missing (for notifications), value is expected to be - // cast to string for simplicity. Use empty string in case of `null` value. - // Omit entirely if this is a notification. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '10', 'request-7', '' - RPCJsonrpcRequestIDKey = attribute.Key("rpc.jsonrpc.request_id") - - // RPCJsonrpcVersionKey is the attribute Key conforming to the - // "rpc.jsonrpc.version" semantic conventions. It represents the protocol - // version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 - // doesn't specify this, the value can be omitted. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2.0', '1.0' - RPCJsonrpcVersionKey = attribute.Key("rpc.jsonrpc.version") - - // RPCMessageCompressedSizeKey is the attribute Key conforming to the - // "rpc.message.compressed_size" semantic conventions. It represents the - // compressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - RPCMessageCompressedSizeKey = attribute.Key("rpc.message.compressed_size") - - // RPCMessageIDKey is the attribute Key conforming to the "rpc.message.id" - // semantic conventions. It represents the mUST be calculated as two - // different counters starting from `1` one for sent messages and one for - // received message. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Note: This way we guarantee that the values will be consistent between - // different implementations. - RPCMessageIDKey = attribute.Key("rpc.message.id") - - // RPCMessageTypeKey is the attribute Key conforming to the - // "rpc.message.type" semantic conventions. It represents the whether this - // is a received or sent message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCMessageTypeKey = attribute.Key("rpc.message.type") - - // RPCMessageUncompressedSizeKey is the attribute Key conforming to the - // "rpc.message.uncompressed_size" semantic conventions. It represents the - // uncompressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - RPCMessageUncompressedSizeKey = attribute.Key("rpc.message.uncompressed_size") - - // RPCMethodKey is the attribute Key conforming to the "rpc.method" - // semantic conventions. It represents the name of the (logical) method - // being called, must be equal to the $method part in the span name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'exampleMethod' - // Note: This is the logical name of the method from the RPC interface - // perspective, which can be different from the name of any implementing - // method/function. The `code.function` attribute may be used to store the - // latter (e.g., method actually executing the call on the server side, RPC - // client stub method on the client side). - RPCMethodKey = attribute.Key("rpc.method") - - // RPCServiceKey is the attribute Key conforming to the "rpc.service" - // semantic conventions. It represents the full (logical) name of the - // service being called, including its package name, if applicable. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myservice.EchoService' - // Note: This is the logical name of the service from the RPC interface - // perspective, which can be different from the name of any implementing - // class. The `code.namespace` attribute may be used to store the latter - // (despite the attribute name, it may include a class name; e.g., class - // with method actually executing the call on the server side, RPC client - // stub class on the client side). - RPCServiceKey = attribute.Key("rpc.service") - - // RPCSystemKey is the attribute Key conforming to the "rpc.system" - // semantic conventions. It represents a string identifying the remoting - // system. See below for a list of well-known identifiers. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCSystemKey = attribute.Key("rpc.system") -) - -var ( - // cancelled - RPCConnectRPCErrorCodeCancelled = RPCConnectRPCErrorCodeKey.String("cancelled") - // unknown - RPCConnectRPCErrorCodeUnknown = RPCConnectRPCErrorCodeKey.String("unknown") - // invalid_argument - RPCConnectRPCErrorCodeInvalidArgument = RPCConnectRPCErrorCodeKey.String("invalid_argument") - // deadline_exceeded - RPCConnectRPCErrorCodeDeadlineExceeded = RPCConnectRPCErrorCodeKey.String("deadline_exceeded") - // not_found - RPCConnectRPCErrorCodeNotFound = RPCConnectRPCErrorCodeKey.String("not_found") - // already_exists - RPCConnectRPCErrorCodeAlreadyExists = RPCConnectRPCErrorCodeKey.String("already_exists") - // permission_denied - RPCConnectRPCErrorCodePermissionDenied = RPCConnectRPCErrorCodeKey.String("permission_denied") - // resource_exhausted - RPCConnectRPCErrorCodeResourceExhausted = RPCConnectRPCErrorCodeKey.String("resource_exhausted") - // failed_precondition - RPCConnectRPCErrorCodeFailedPrecondition = RPCConnectRPCErrorCodeKey.String("failed_precondition") - // aborted - RPCConnectRPCErrorCodeAborted = RPCConnectRPCErrorCodeKey.String("aborted") - // out_of_range - RPCConnectRPCErrorCodeOutOfRange = RPCConnectRPCErrorCodeKey.String("out_of_range") - // unimplemented - RPCConnectRPCErrorCodeUnimplemented = RPCConnectRPCErrorCodeKey.String("unimplemented") - // internal - RPCConnectRPCErrorCodeInternal = RPCConnectRPCErrorCodeKey.String("internal") - // unavailable - RPCConnectRPCErrorCodeUnavailable = RPCConnectRPCErrorCodeKey.String("unavailable") - // data_loss - RPCConnectRPCErrorCodeDataLoss = RPCConnectRPCErrorCodeKey.String("data_loss") - // unauthenticated - RPCConnectRPCErrorCodeUnauthenticated = RPCConnectRPCErrorCodeKey.String("unauthenticated") -) - -var ( - // OK - RPCGRPCStatusCodeOk = RPCGRPCStatusCodeKey.Int(0) - // CANCELLED - RPCGRPCStatusCodeCancelled = RPCGRPCStatusCodeKey.Int(1) - // UNKNOWN - RPCGRPCStatusCodeUnknown = RPCGRPCStatusCodeKey.Int(2) - // INVALID_ARGUMENT - RPCGRPCStatusCodeInvalidArgument = RPCGRPCStatusCodeKey.Int(3) - // DEADLINE_EXCEEDED - RPCGRPCStatusCodeDeadlineExceeded = RPCGRPCStatusCodeKey.Int(4) - // NOT_FOUND - RPCGRPCStatusCodeNotFound = RPCGRPCStatusCodeKey.Int(5) - // ALREADY_EXISTS - RPCGRPCStatusCodeAlreadyExists = RPCGRPCStatusCodeKey.Int(6) - // PERMISSION_DENIED - RPCGRPCStatusCodePermissionDenied = RPCGRPCStatusCodeKey.Int(7) - // RESOURCE_EXHAUSTED - RPCGRPCStatusCodeResourceExhausted = RPCGRPCStatusCodeKey.Int(8) - // FAILED_PRECONDITION - RPCGRPCStatusCodeFailedPrecondition = RPCGRPCStatusCodeKey.Int(9) - // ABORTED - RPCGRPCStatusCodeAborted = RPCGRPCStatusCodeKey.Int(10) - // OUT_OF_RANGE - RPCGRPCStatusCodeOutOfRange = RPCGRPCStatusCodeKey.Int(11) - // UNIMPLEMENTED - RPCGRPCStatusCodeUnimplemented = RPCGRPCStatusCodeKey.Int(12) - // INTERNAL - RPCGRPCStatusCodeInternal = RPCGRPCStatusCodeKey.Int(13) - // UNAVAILABLE - RPCGRPCStatusCodeUnavailable = RPCGRPCStatusCodeKey.Int(14) - // DATA_LOSS - RPCGRPCStatusCodeDataLoss = RPCGRPCStatusCodeKey.Int(15) - // UNAUTHENTICATED - RPCGRPCStatusCodeUnauthenticated = RPCGRPCStatusCodeKey.Int(16) -) - -var ( - // sent - RPCMessageTypeSent = RPCMessageTypeKey.String("SENT") - // received - RPCMessageTypeReceived = RPCMessageTypeKey.String("RECEIVED") -) - -var ( - // gRPC - RPCSystemGRPC = RPCSystemKey.String("grpc") - // Java RMI - RPCSystemJavaRmi = RPCSystemKey.String("java_rmi") - // .NET WCF - RPCSystemDotnetWcf = RPCSystemKey.String("dotnet_wcf") - // Apache Dubbo - RPCSystemApacheDubbo = RPCSystemKey.String("apache_dubbo") - // Connect RPC - RPCSystemConnectRPC = RPCSystemKey.String("connect_rpc") -) - -// RPCJsonrpcErrorCode returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_code" semantic conventions. It represents the -// `error.code` property of response if it is an error response. -func RPCJsonrpcErrorCode(val int) attribute.KeyValue { - return RPCJsonrpcErrorCodeKey.Int(val) -} - -// RPCJsonrpcErrorMessage returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_message" semantic conventions. It represents the -// `error.message` property of response if it is an error response. -func RPCJsonrpcErrorMessage(val string) attribute.KeyValue { - return RPCJsonrpcErrorMessageKey.String(val) -} - -// RPCJsonrpcRequestID returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` -// property of request or response. Since protocol allows id to be int, string, -// `null` or missing (for notifications), value is expected to be cast to -// string for simplicity. Use empty string in case of `null` value. Omit -// entirely if this is a notification. -func RPCJsonrpcRequestID(val string) attribute.KeyValue { - return RPCJsonrpcRequestIDKey.String(val) -} - -// RPCJsonrpcVersion returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.version" semantic conventions. It represents the protocol -// version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 -// doesn't specify this, the value can be omitted. -func RPCJsonrpcVersion(val string) attribute.KeyValue { - return RPCJsonrpcVersionKey.String(val) -} - -// RPCMessageCompressedSize returns an attribute KeyValue conforming to the -// "rpc.message.compressed_size" semantic conventions. It represents the -// compressed size of the message in bytes. -func RPCMessageCompressedSize(val int) attribute.KeyValue { - return RPCMessageCompressedSizeKey.Int(val) -} - -// RPCMessageID returns an attribute KeyValue conforming to the -// "rpc.message.id" semantic conventions. It represents the mUST be calculated -// as two different counters starting from `1` one for sent messages and one -// for received message. -func RPCMessageID(val int) attribute.KeyValue { - return RPCMessageIDKey.Int(val) -} - -// RPCMessageUncompressedSize returns an attribute KeyValue conforming to -// the "rpc.message.uncompressed_size" semantic conventions. It represents the -// uncompressed size of the message in bytes. -func RPCMessageUncompressedSize(val int) attribute.KeyValue { - return RPCMessageUncompressedSizeKey.Int(val) -} - -// RPCMethod returns an attribute KeyValue conforming to the "rpc.method" -// semantic conventions. It represents the name of the (logical) method being -// called, must be equal to the $method part in the span name. -func RPCMethod(val string) attribute.KeyValue { - return RPCMethodKey.String(val) -} - -// RPCService returns an attribute KeyValue conforming to the "rpc.service" -// semantic conventions. It represents the full (logical) name of the service -// being called, including its package name, if applicable. -func RPCService(val string) attribute.KeyValue { - return RPCServiceKey.String(val) -} - -// These attributes may be used to describe the server in a connection-based -// network interaction where there is one side that initiates the connection -// (the client is the side that initiates the connection). This covers all TCP -// network interactions since TCP is connection-based and one side initiates -// the connection (an exception is made for peer-to-peer communication over TCP -// where the "user-facing" surface of the protocol / API doesn't expose a clear -// notion of client and server). This also covers UDP network interactions -// where one side initiates the interaction, e.g. QUIC (HTTP/3) and DNS. -const ( - // ServerAddressKey is the attribute Key conforming to the "server.address" - // semantic conventions. It represents the server domain name if available - // without reverse DNS lookup; otherwise, IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the client side, and when communicating through - // an intermediary, `server.address` SHOULD represent the server address - // behind any intermediaries, for example proxies, if it's available. - ServerAddressKey = attribute.Key("server.address") - - // ServerPortKey is the attribute Key conforming to the "server.port" - // semantic conventions. It represents the server port number. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 80, 8080, 443 - // Note: When observed from the client side, and when communicating through - // an intermediary, `server.port` SHOULD represent the server port behind - // any intermediaries, for example proxies, if it's available. - ServerPortKey = attribute.Key("server.port") -) - -// ServerAddress returns an attribute KeyValue conforming to the -// "server.address" semantic conventions. It represents the server domain name -// if available without reverse DNS lookup; otherwise, IP address or Unix -// domain socket name. -func ServerAddress(val string) attribute.KeyValue { - return ServerAddressKey.String(val) -} - -// ServerPort returns an attribute KeyValue conforming to the "server.port" -// semantic conventions. It represents the server port number. -func ServerPort(val int) attribute.KeyValue { - return ServerPortKey.Int(val) -} - -// A service instance. -const ( - // ServiceInstanceIDKey is the attribute Key conforming to the - // "service.instance.id" semantic conventions. It represents the string ID - // of the service instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '627cc493-f310-47de-96bd-71410b7dec09' - // Note: MUST be unique for each instance of the same - // `service.namespace,service.name` pair (in other words - // `service.namespace,service.name,service.instance.id` triplet MUST be - // globally unique). The ID helps to - // distinguish instances of the same service that exist at the same time - // (e.g. instances of a horizontally scaled - // service). - // - // Implementations, such as SDKs, are recommended to generate a random - // Version 1 or Version 4 [RFC - // 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an - // inherent unique ID as the source of - // this value if stability is desirable. In that case, the ID SHOULD be - // used as source of a UUID Version 5 and - // SHOULD use the following UUID as the namespace: - // `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. - // - // UUIDs are typically recommended, as only an opaque value for the - // purposes of identifying a service instance is - // needed. Similar to what can be seen in the man page for the - // [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/machine-id.html) - // file, the underlying - // data, such as pod name and namespace should be treated as confidential, - // being the user's choice to expose it - // or not via another resource attribute. - // - // For applications running behind an application server (like unicorn), we - // do not recommend using one identifier - // for all processes participating in the application. Instead, it's - // recommended each division (e.g. a worker - // thread in unicorn) to have its own instance.id. - // - // It's not recommended for a Collector to set `service.instance.id` if it - // can't unambiguously determine the - // service instance that is generating that telemetry. For instance, - // creating an UUID based on `pod.name` will - // likely be wrong, as the Collector might not know from which container - // within that pod the telemetry originated. - // However, Collectors can set the `service.instance.id` if they can - // unambiguously determine the service instance - // for that telemetry. This is typically the case for scraping receivers, - // as they know the target address and - // port. - ServiceInstanceIDKey = attribute.Key("service.instance.id") - - // ServiceNameKey is the attribute Key conforming to the "service.name" - // semantic conventions. It represents the logical name of the service. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'shoppingcart' - // Note: MUST be the same for all instances of horizontally scaled - // services. If the value was not specified, SDKs MUST fallback to - // `unknown_service:` concatenated with - // [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If - // `process.executable.name` is not available, the value MUST be set to - // `unknown_service`. - ServiceNameKey = attribute.Key("service.name") - - // ServiceNamespaceKey is the attribute Key conforming to the - // "service.namespace" semantic conventions. It represents a namespace for - // `service.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Shop' - // Note: A string value having a meaning that helps to distinguish a group - // of services, for example the team name that owns a group of services. - // `service.name` is expected to be unique within the same namespace. If - // `service.namespace` is not specified in the Resource then `service.name` - // is expected to be unique for all services that have no explicit - // namespace defined (so the empty/unspecified namespace is simply one more - // valid namespace). Zero-length namespace string is assumed equal to - // unspecified namespace. - ServiceNamespaceKey = attribute.Key("service.namespace") - - // ServiceVersionKey is the attribute Key conforming to the - // "service.version" semantic conventions. It represents the version string - // of the service API or implementation. The format is not defined by these - // conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2.0.0', 'a01dbef8a' - ServiceVersionKey = attribute.Key("service.version") -) - -// ServiceInstanceID returns an attribute KeyValue conforming to the -// "service.instance.id" semantic conventions. It represents the string ID of -// the service instance. -func ServiceInstanceID(val string) attribute.KeyValue { - return ServiceInstanceIDKey.String(val) -} - -// ServiceName returns an attribute KeyValue conforming to the -// "service.name" semantic conventions. It represents the logical name of the -// service. -func ServiceName(val string) attribute.KeyValue { - return ServiceNameKey.String(val) -} - -// ServiceNamespace returns an attribute KeyValue conforming to the -// "service.namespace" semantic conventions. It represents a namespace for -// `service.name`. -func ServiceNamespace(val string) attribute.KeyValue { - return ServiceNamespaceKey.String(val) -} - -// ServiceVersion returns an attribute KeyValue conforming to the -// "service.version" semantic conventions. It represents the version string of -// the service API or implementation. The format is not defined by these -// conventions. -func ServiceVersion(val string) attribute.KeyValue { - return ServiceVersionKey.String(val) -} - -// Session is defined as the period of time encompassing all activities -// performed by the application and the actions executed by the end user. -// Consequently, a Session is represented as a collection of Logs, Events, and -// Spans emitted by the Client Application throughout the Session's duration. -// Each Session is assigned a unique identifier, which is included as an -// attribute in the Logs, Events, and Spans generated during the Session's -// lifecycle. -// When a session reaches end of life, typically due to user inactivity or -// session timeout, a new session identifier will be assigned. The previous -// session identifier may be provided by the instrumentation so that telemetry -// backends can link the two sessions. -const ( - // SessionIDKey is the attribute Key conforming to the "session.id" - // semantic conventions. It represents a unique id to identify a session. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '00112233-4455-6677-8899-aabbccddeeff' - SessionIDKey = attribute.Key("session.id") - - // SessionPreviousIDKey is the attribute Key conforming to the - // "session.previous_id" semantic conventions. It represents the previous - // `session.id` for this user, when known. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '00112233-4455-6677-8899-aabbccddeeff' - SessionPreviousIDKey = attribute.Key("session.previous_id") -) - -// SessionID returns an attribute KeyValue conforming to the "session.id" -// semantic conventions. It represents a unique id to identify a session. -func SessionID(val string) attribute.KeyValue { - return SessionIDKey.String(val) -} - -// SessionPreviousID returns an attribute KeyValue conforming to the -// "session.previous_id" semantic conventions. It represents the previous -// `session.id` for this user, when known. -func SessionPreviousID(val string) attribute.KeyValue { - return SessionPreviousIDKey.String(val) -} - -// SignalR attributes -const ( - // SignalrConnectionStatusKey is the attribute Key conforming to the - // "signalr.connection.status" semantic conventions. It represents the - // signalR HTTP connection closure status. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'app_shutdown', 'timeout' - SignalrConnectionStatusKey = attribute.Key("signalr.connection.status") - - // SignalrTransportKey is the attribute Key conforming to the - // "signalr.transport" semantic conventions. It represents the [SignalR - // transport - // type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'web_sockets', 'long_polling' - SignalrTransportKey = attribute.Key("signalr.transport") -) - -var ( - // The connection was closed normally - SignalrConnectionStatusNormalClosure = SignalrConnectionStatusKey.String("normal_closure") - // The connection was closed due to a timeout - SignalrConnectionStatusTimeout = SignalrConnectionStatusKey.String("timeout") - // The connection was closed because the app is shutting down - SignalrConnectionStatusAppShutdown = SignalrConnectionStatusKey.String("app_shutdown") -) - -var ( - // ServerSentEvents protocol - SignalrTransportServerSentEvents = SignalrTransportKey.String("server_sent_events") - // LongPolling protocol - SignalrTransportLongPolling = SignalrTransportKey.String("long_polling") - // WebSockets protocol - SignalrTransportWebSockets = SignalrTransportKey.String("web_sockets") -) - -// These attributes may be used to describe the sender of a network -// exchange/packet. These should be used when there is no client/server -// relationship between the two sides, or when that relationship is unknown. -// This covers low-level network interactions (e.g. packet tracing) where you -// don't know if there was a connection or which side initiated it. This also -// covers unidirectional UDP flows and peer-to-peer communication where the -// "user-facing" surface of the protocol / API doesn't expose a clear notion of -// client and server. -const ( - // SourceAddressKey is the attribute Key conforming to the "source.address" - // semantic conventions. It represents the source address - domain name if - // available without reverse DNS lookup; otherwise, IP address or Unix - // domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'source.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the destination side, and when communicating - // through an intermediary, `source.address` SHOULD represent the source - // address behind any intermediaries, for example proxies, if it's - // available. - SourceAddressKey = attribute.Key("source.address") - - // SourcePortKey is the attribute Key conforming to the "source.port" - // semantic conventions. It represents the source port number - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3389, 2888 - SourcePortKey = attribute.Key("source.port") -) - -// SourceAddress returns an attribute KeyValue conforming to the -// "source.address" semantic conventions. It represents the source address - -// domain name if available without reverse DNS lookup; otherwise, IP address -// or Unix domain socket name. -func SourceAddress(val string) attribute.KeyValue { - return SourceAddressKey.String(val) -} - -// SourcePort returns an attribute KeyValue conforming to the "source.port" -// semantic conventions. It represents the source port number -func SourcePort(val int) attribute.KeyValue { - return SourcePortKey.Int(val) -} - -// Describes System attributes -const ( - // SystemDeviceKey is the attribute Key conforming to the "system.device" - // semantic conventions. It represents the device identifier - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '(identifier)' - SystemDeviceKey = attribute.Key("system.device") -) - -// SystemDevice returns an attribute KeyValue conforming to the -// "system.device" semantic conventions. It represents the device identifier -func SystemDevice(val string) attribute.KeyValue { - return SystemDeviceKey.String(val) -} - -// Describes System CPU attributes -const ( - // SystemCPULogicalNumberKey is the attribute Key conforming to the - // "system.cpu.logical_number" semantic conventions. It represents the - // logical CPU number [0..n-1] - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1 - SystemCPULogicalNumberKey = attribute.Key("system.cpu.logical_number") - - // SystemCPUStateKey is the attribute Key conforming to the - // "system.cpu.state" semantic conventions. It represents the state of the - // CPU - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'idle', 'interrupt' - SystemCPUStateKey = attribute.Key("system.cpu.state") -) - -var ( - // user - SystemCPUStateUser = SystemCPUStateKey.String("user") - // system - SystemCPUStateSystem = SystemCPUStateKey.String("system") - // nice - SystemCPUStateNice = SystemCPUStateKey.String("nice") - // idle - SystemCPUStateIdle = SystemCPUStateKey.String("idle") - // iowait - SystemCPUStateIowait = SystemCPUStateKey.String("iowait") - // interrupt - SystemCPUStateInterrupt = SystemCPUStateKey.String("interrupt") - // steal - SystemCPUStateSteal = SystemCPUStateKey.String("steal") -) - -// SystemCPULogicalNumber returns an attribute KeyValue conforming to the -// "system.cpu.logical_number" semantic conventions. It represents the logical -// CPU number [0..n-1] -func SystemCPULogicalNumber(val int) attribute.KeyValue { - return SystemCPULogicalNumberKey.Int(val) -} - -// Describes System Memory attributes -const ( - // SystemMemoryStateKey is the attribute Key conforming to the - // "system.memory.state" semantic conventions. It represents the memory - // state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'free', 'cached' - SystemMemoryStateKey = attribute.Key("system.memory.state") -) - -var ( - // used - SystemMemoryStateUsed = SystemMemoryStateKey.String("used") - // free - SystemMemoryStateFree = SystemMemoryStateKey.String("free") - // shared - SystemMemoryStateShared = SystemMemoryStateKey.String("shared") - // buffers - SystemMemoryStateBuffers = SystemMemoryStateKey.String("buffers") - // cached - SystemMemoryStateCached = SystemMemoryStateKey.String("cached") -) - -// Describes System Memory Paging attributes -const ( - // SystemPagingDirectionKey is the attribute Key conforming to the - // "system.paging.direction" semantic conventions. It represents the paging - // access direction - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'in' - SystemPagingDirectionKey = attribute.Key("system.paging.direction") - - // SystemPagingStateKey is the attribute Key conforming to the - // "system.paging.state" semantic conventions. It represents the memory - // paging state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'free' - SystemPagingStateKey = attribute.Key("system.paging.state") - - // SystemPagingTypeKey is the attribute Key conforming to the - // "system.paging.type" semantic conventions. It represents the memory - // paging type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'minor' - SystemPagingTypeKey = attribute.Key("system.paging.type") -) - -var ( - // in - SystemPagingDirectionIn = SystemPagingDirectionKey.String("in") - // out - SystemPagingDirectionOut = SystemPagingDirectionKey.String("out") -) - -var ( - // used - SystemPagingStateUsed = SystemPagingStateKey.String("used") - // free - SystemPagingStateFree = SystemPagingStateKey.String("free") -) - -var ( - // major - SystemPagingTypeMajor = SystemPagingTypeKey.String("major") - // minor - SystemPagingTypeMinor = SystemPagingTypeKey.String("minor") -) - -// Describes Filesystem attributes -const ( - // SystemFilesystemModeKey is the attribute Key conforming to the - // "system.filesystem.mode" semantic conventions. It represents the - // filesystem mode - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'rw, ro' - SystemFilesystemModeKey = attribute.Key("system.filesystem.mode") - - // SystemFilesystemMountpointKey is the attribute Key conforming to the - // "system.filesystem.mountpoint" semantic conventions. It represents the - // filesystem mount path - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/mnt/data' - SystemFilesystemMountpointKey = attribute.Key("system.filesystem.mountpoint") - - // SystemFilesystemStateKey is the attribute Key conforming to the - // "system.filesystem.state" semantic conventions. It represents the - // filesystem state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'used' - SystemFilesystemStateKey = attribute.Key("system.filesystem.state") - - // SystemFilesystemTypeKey is the attribute Key conforming to the - // "system.filesystem.type" semantic conventions. It represents the - // filesystem type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ext4' - SystemFilesystemTypeKey = attribute.Key("system.filesystem.type") -) - -var ( - // used - SystemFilesystemStateUsed = SystemFilesystemStateKey.String("used") - // free - SystemFilesystemStateFree = SystemFilesystemStateKey.String("free") - // reserved - SystemFilesystemStateReserved = SystemFilesystemStateKey.String("reserved") -) - -var ( - // fat32 - SystemFilesystemTypeFat32 = SystemFilesystemTypeKey.String("fat32") - // exfat - SystemFilesystemTypeExfat = SystemFilesystemTypeKey.String("exfat") - // ntfs - SystemFilesystemTypeNtfs = SystemFilesystemTypeKey.String("ntfs") - // refs - SystemFilesystemTypeRefs = SystemFilesystemTypeKey.String("refs") - // hfsplus - SystemFilesystemTypeHfsplus = SystemFilesystemTypeKey.String("hfsplus") - // ext4 - SystemFilesystemTypeExt4 = SystemFilesystemTypeKey.String("ext4") -) - -// SystemFilesystemMode returns an attribute KeyValue conforming to the -// "system.filesystem.mode" semantic conventions. It represents the filesystem -// mode -func SystemFilesystemMode(val string) attribute.KeyValue { - return SystemFilesystemModeKey.String(val) -} - -// SystemFilesystemMountpoint returns an attribute KeyValue conforming to -// the "system.filesystem.mountpoint" semantic conventions. It represents the -// filesystem mount path -func SystemFilesystemMountpoint(val string) attribute.KeyValue { - return SystemFilesystemMountpointKey.String(val) -} - -// Describes Network attributes -const ( - // SystemNetworkStateKey is the attribute Key conforming to the - // "system.network.state" semantic conventions. It represents a stateless - // protocol MUST NOT set this attribute - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'close_wait' - SystemNetworkStateKey = attribute.Key("system.network.state") -) - -var ( - // close - SystemNetworkStateClose = SystemNetworkStateKey.String("close") - // close_wait - SystemNetworkStateCloseWait = SystemNetworkStateKey.String("close_wait") - // closing - SystemNetworkStateClosing = SystemNetworkStateKey.String("closing") - // delete - SystemNetworkStateDelete = SystemNetworkStateKey.String("delete") - // established - SystemNetworkStateEstablished = SystemNetworkStateKey.String("established") - // fin_wait_1 - SystemNetworkStateFinWait1 = SystemNetworkStateKey.String("fin_wait_1") - // fin_wait_2 - SystemNetworkStateFinWait2 = SystemNetworkStateKey.String("fin_wait_2") - // last_ack - SystemNetworkStateLastAck = SystemNetworkStateKey.String("last_ack") - // listen - SystemNetworkStateListen = SystemNetworkStateKey.String("listen") - // syn_recv - SystemNetworkStateSynRecv = SystemNetworkStateKey.String("syn_recv") - // syn_sent - SystemNetworkStateSynSent = SystemNetworkStateKey.String("syn_sent") - // time_wait - SystemNetworkStateTimeWait = SystemNetworkStateKey.String("time_wait") -) - -// Describes System Process attributes -const ( - // SystemProcessStatusKey is the attribute Key conforming to the - // "system.process.status" semantic conventions. It represents the process - // state, e.g., [Linux Process State - // Codes](https://man7.org/linux/man-pages/man1/ps.1.html#PROCESS_STATE_CODES) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'running' - SystemProcessStatusKey = attribute.Key("system.process.status") -) - -var ( - // running - SystemProcessStatusRunning = SystemProcessStatusKey.String("running") - // sleeping - SystemProcessStatusSleeping = SystemProcessStatusKey.String("sleeping") - // stopped - SystemProcessStatusStopped = SystemProcessStatusKey.String("stopped") - // defunct - SystemProcessStatusDefunct = SystemProcessStatusKey.String("defunct") -) - -// Attributes for telemetry SDK. -const ( - // TelemetrySDKLanguageKey is the attribute Key conforming to the - // "telemetry.sdk.language" semantic conventions. It represents the - // language of the telemetry SDK. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - TelemetrySDKLanguageKey = attribute.Key("telemetry.sdk.language") - - // TelemetrySDKNameKey is the attribute Key conforming to the - // "telemetry.sdk.name" semantic conventions. It represents the name of the - // telemetry SDK as defined above. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'opentelemetry' - // Note: The OpenTelemetry SDK MUST set the `telemetry.sdk.name` attribute - // to `opentelemetry`. - // If another SDK, like a fork or a vendor-provided implementation, is - // used, this SDK MUST set the - // `telemetry.sdk.name` attribute to the fully-qualified class or module - // name of this SDK's main entry point - // or another suitable identifier depending on the language. - // The identifier `opentelemetry` is reserved and MUST NOT be used in this - // case. - // All custom identifiers SHOULD be stable across different versions of an - // implementation. - TelemetrySDKNameKey = attribute.Key("telemetry.sdk.name") - - // TelemetrySDKVersionKey is the attribute Key conforming to the - // "telemetry.sdk.version" semantic conventions. It represents the version - // string of the telemetry SDK. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '1.2.3' - TelemetrySDKVersionKey = attribute.Key("telemetry.sdk.version") - - // TelemetryDistroNameKey is the attribute Key conforming to the - // "telemetry.distro.name" semantic conventions. It represents the name of - // the auto instrumentation agent or distribution, if used. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'parts-unlimited-java' - // Note: Official auto instrumentation agents and distributions SHOULD set - // the `telemetry.distro.name` attribute to - // a string starting with `opentelemetry-`, e.g. - // `opentelemetry-java-instrumentation`. - TelemetryDistroNameKey = attribute.Key("telemetry.distro.name") - - // TelemetryDistroVersionKey is the attribute Key conforming to the - // "telemetry.distro.version" semantic conventions. It represents the - // version string of the auto instrumentation agent or distribution, if - // used. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.2.3' - TelemetryDistroVersionKey = attribute.Key("telemetry.distro.version") -) - -var ( - // cpp - TelemetrySDKLanguageCPP = TelemetrySDKLanguageKey.String("cpp") - // dotnet - TelemetrySDKLanguageDotnet = TelemetrySDKLanguageKey.String("dotnet") - // erlang - TelemetrySDKLanguageErlang = TelemetrySDKLanguageKey.String("erlang") - // go - TelemetrySDKLanguageGo = TelemetrySDKLanguageKey.String("go") - // java - TelemetrySDKLanguageJava = TelemetrySDKLanguageKey.String("java") - // nodejs - TelemetrySDKLanguageNodejs = TelemetrySDKLanguageKey.String("nodejs") - // php - TelemetrySDKLanguagePHP = TelemetrySDKLanguageKey.String("php") - // python - TelemetrySDKLanguagePython = TelemetrySDKLanguageKey.String("python") - // ruby - TelemetrySDKLanguageRuby = TelemetrySDKLanguageKey.String("ruby") - // rust - TelemetrySDKLanguageRust = TelemetrySDKLanguageKey.String("rust") - // swift - TelemetrySDKLanguageSwift = TelemetrySDKLanguageKey.String("swift") - // webjs - TelemetrySDKLanguageWebjs = TelemetrySDKLanguageKey.String("webjs") -) - -// TelemetrySDKName returns an attribute KeyValue conforming to the -// "telemetry.sdk.name" semantic conventions. It represents the name of the -// telemetry SDK as defined above. -func TelemetrySDKName(val string) attribute.KeyValue { - return TelemetrySDKNameKey.String(val) -} - -// TelemetrySDKVersion returns an attribute KeyValue conforming to the -// "telemetry.sdk.version" semantic conventions. It represents the version -// string of the telemetry SDK. -func TelemetrySDKVersion(val string) attribute.KeyValue { - return TelemetrySDKVersionKey.String(val) -} - -// TelemetryDistroName returns an attribute KeyValue conforming to the -// "telemetry.distro.name" semantic conventions. It represents the name of the -// auto instrumentation agent or distribution, if used. -func TelemetryDistroName(val string) attribute.KeyValue { - return TelemetryDistroNameKey.String(val) -} - -// TelemetryDistroVersion returns an attribute KeyValue conforming to the -// "telemetry.distro.version" semantic conventions. It represents the version -// string of the auto instrumentation agent or distribution, if used. -func TelemetryDistroVersion(val string) attribute.KeyValue { - return TelemetryDistroVersionKey.String(val) -} - -// These attributes may be used for any operation to store information about a -// thread that started a span. -const ( - // ThreadIDKey is the attribute Key conforming to the "thread.id" semantic - // conventions. It represents the current "managed" thread ID (as opposed - // to OS thread ID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - ThreadIDKey = attribute.Key("thread.id") - - // ThreadNameKey is the attribute Key conforming to the "thread.name" - // semantic conventions. It represents the current thread name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'main' - ThreadNameKey = attribute.Key("thread.name") -) - -// ThreadID returns an attribute KeyValue conforming to the "thread.id" -// semantic conventions. It represents the current "managed" thread ID (as -// opposed to OS thread ID). -func ThreadID(val int) attribute.KeyValue { - return ThreadIDKey.Int(val) -} - -// ThreadName returns an attribute KeyValue conforming to the "thread.name" -// semantic conventions. It represents the current thread name. -func ThreadName(val string) attribute.KeyValue { - return ThreadNameKey.String(val) -} - -// Semantic convention attributes in the TLS namespace. -const ( - // TLSCipherKey is the attribute Key conforming to the "tls.cipher" - // semantic conventions. It represents the string indicating the - // [cipher](https://datatracker.ietf.org/doc/html/rfc5246#appendix-A.5) - // used during the current connection. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'TLS_RSA_WITH_3DES_EDE_CBC_SHA', - // 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256' - // Note: The values allowed for `tls.cipher` MUST be one of the - // `Descriptions` of the [registered TLS Cipher - // Suits](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#table-tls-parameters-4). - TLSCipherKey = attribute.Key("tls.cipher") - - // TLSClientCertificateKey is the attribute Key conforming to the - // "tls.client.certificate" semantic conventions. It represents the - // pEM-encoded stand-alone certificate offered by the client. This is - // usually mutually-exclusive of `client.certificate_chain` since this - // value also exists in that list. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...' - TLSClientCertificateKey = attribute.Key("tls.client.certificate") - - // TLSClientCertificateChainKey is the attribute Key conforming to the - // "tls.client.certificate_chain" semantic conventions. It represents the - // array of PEM-encoded certificates that make up the certificate chain - // offered by the client. This is usually mutually-exclusive of - // `client.certificate` since that value should be the first certificate in - // the chain. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...', 'MI...' - TLSClientCertificateChainKey = attribute.Key("tls.client.certificate_chain") - - // TLSClientHashMd5Key is the attribute Key conforming to the - // "tls.client.hash.md5" semantic conventions. It represents the - // certificate fingerprint using the MD5 digest of DER-encoded version of - // certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0F76C7F2C55BFD7D8E8B8F4BFBF0C9EC' - TLSClientHashMd5Key = attribute.Key("tls.client.hash.md5") - - // TLSClientHashSha1Key is the attribute Key conforming to the - // "tls.client.hash.sha1" semantic conventions. It represents the - // certificate fingerprint using the SHA1 digest of DER-encoded version of - // certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '9E393D93138888D288266C2D915214D1D1CCEB2A' - TLSClientHashSha1Key = attribute.Key("tls.client.hash.sha1") - - // TLSClientHashSha256Key is the attribute Key conforming to the - // "tls.client.hash.sha256" semantic conventions. It represents the - // certificate fingerprint using the SHA256 digest of DER-encoded version - // of certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // '0687F666A054EF17A08E2F2162EAB4CBC0D265E1D7875BE74BF3C712CA92DAF0' - TLSClientHashSha256Key = attribute.Key("tls.client.hash.sha256") - - // TLSClientIssuerKey is the attribute Key conforming to the - // "tls.client.issuer" semantic conventions. It represents the - // distinguished name of - // [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) - // of the issuer of the x.509 certificate presented by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=Example Root CA, OU=Infrastructure Team, DC=example, - // DC=com' - TLSClientIssuerKey = attribute.Key("tls.client.issuer") - - // TLSClientJa3Key is the attribute Key conforming to the "tls.client.ja3" - // semantic conventions. It represents a hash that identifies clients based - // on how they perform an SSL/TLS handshake. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'd4e5b18d6b55c71272893221c96ba240' - TLSClientJa3Key = attribute.Key("tls.client.ja3") - - // TLSClientNotAfterKey is the attribute Key conforming to the - // "tls.client.not_after" semantic conventions. It represents the date/Time - // indicating when client certificate is no longer considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021-01-01T00:00:00.000Z' - TLSClientNotAfterKey = attribute.Key("tls.client.not_after") - - // TLSClientNotBeforeKey is the attribute Key conforming to the - // "tls.client.not_before" semantic conventions. It represents the - // date/Time indicating when client certificate is first considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1970-01-01T00:00:00.000Z' - TLSClientNotBeforeKey = attribute.Key("tls.client.not_before") - - // TLSClientServerNameKey is the attribute Key conforming to the - // "tls.client.server_name" semantic conventions. It represents the also - // called an SNI, this tells the server which hostname to which the client - // is attempting to connect to. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry.io' - TLSClientServerNameKey = attribute.Key("tls.client.server_name") - - // TLSClientSubjectKey is the attribute Key conforming to the - // "tls.client.subject" semantic conventions. It represents the - // distinguished name of subject of the x.509 certificate presented by the - // client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=myclient, OU=Documentation Team, DC=example, DC=com' - TLSClientSubjectKey = attribute.Key("tls.client.subject") - - // TLSClientSupportedCiphersKey is the attribute Key conforming to the - // "tls.client.supported_ciphers" semantic conventions. It represents the - // array of ciphers offered by the client during the client hello. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - // "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "..."' - TLSClientSupportedCiphersKey = attribute.Key("tls.client.supported_ciphers") - - // TLSCurveKey is the attribute Key conforming to the "tls.curve" semantic - // conventions. It represents the string indicating the curve used for the - // given cipher, when applicable - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'secp256r1' - TLSCurveKey = attribute.Key("tls.curve") - - // TLSEstablishedKey is the attribute Key conforming to the - // "tls.established" semantic conventions. It represents the boolean flag - // indicating if the TLS negotiation was successful and transitioned to an - // encrypted tunnel. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Examples: True - TLSEstablishedKey = attribute.Key("tls.established") - - // TLSNextProtocolKey is the attribute Key conforming to the - // "tls.next_protocol" semantic conventions. It represents the string - // indicating the protocol being tunneled. Per the values in the [IANA - // registry](https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids), - // this string should be lower case. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'http/1.1' - TLSNextProtocolKey = attribute.Key("tls.next_protocol") - - // TLSProtocolNameKey is the attribute Key conforming to the - // "tls.protocol.name" semantic conventions. It represents the normalized - // lowercase protocol name parsed from original string of the negotiated - // [SSL/TLS protocol - // version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - TLSProtocolNameKey = attribute.Key("tls.protocol.name") - - // TLSProtocolVersionKey is the attribute Key conforming to the - // "tls.protocol.version" semantic conventions. It represents the numeric - // part of the version parsed from the original string of the negotiated - // [SSL/TLS protocol - // version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.2', '3' - TLSProtocolVersionKey = attribute.Key("tls.protocol.version") - - // TLSResumedKey is the attribute Key conforming to the "tls.resumed" - // semantic conventions. It represents the boolean flag indicating if this - // TLS connection was resumed from an existing TLS negotiation. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Examples: True - TLSResumedKey = attribute.Key("tls.resumed") - - // TLSServerCertificateKey is the attribute Key conforming to the - // "tls.server.certificate" semantic conventions. It represents the - // pEM-encoded stand-alone certificate offered by the server. This is - // usually mutually-exclusive of `server.certificate_chain` since this - // value also exists in that list. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...' - TLSServerCertificateKey = attribute.Key("tls.server.certificate") - - // TLSServerCertificateChainKey is the attribute Key conforming to the - // "tls.server.certificate_chain" semantic conventions. It represents the - // array of PEM-encoded certificates that make up the certificate chain - // offered by the server. This is usually mutually-exclusive of - // `server.certificate` since that value should be the first certificate in - // the chain. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...', 'MI...' - TLSServerCertificateChainKey = attribute.Key("tls.server.certificate_chain") - - // TLSServerHashMd5Key is the attribute Key conforming to the - // "tls.server.hash.md5" semantic conventions. It represents the - // certificate fingerprint using the MD5 digest of DER-encoded version of - // certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0F76C7F2C55BFD7D8E8B8F4BFBF0C9EC' - TLSServerHashMd5Key = attribute.Key("tls.server.hash.md5") - - // TLSServerHashSha1Key is the attribute Key conforming to the - // "tls.server.hash.sha1" semantic conventions. It represents the - // certificate fingerprint using the SHA1 digest of DER-encoded version of - // certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '9E393D93138888D288266C2D915214D1D1CCEB2A' - TLSServerHashSha1Key = attribute.Key("tls.server.hash.sha1") - - // TLSServerHashSha256Key is the attribute Key conforming to the - // "tls.server.hash.sha256" semantic conventions. It represents the - // certificate fingerprint using the SHA256 digest of DER-encoded version - // of certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // '0687F666A054EF17A08E2F2162EAB4CBC0D265E1D7875BE74BF3C712CA92DAF0' - TLSServerHashSha256Key = attribute.Key("tls.server.hash.sha256") - - // TLSServerIssuerKey is the attribute Key conforming to the - // "tls.server.issuer" semantic conventions. It represents the - // distinguished name of - // [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) - // of the issuer of the x.509 certificate presented by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=Example Root CA, OU=Infrastructure Team, DC=example, - // DC=com' - TLSServerIssuerKey = attribute.Key("tls.server.issuer") - - // TLSServerJa3sKey is the attribute Key conforming to the - // "tls.server.ja3s" semantic conventions. It represents a hash that - // identifies servers based on how they perform an SSL/TLS handshake. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'd4e5b18d6b55c71272893221c96ba240' - TLSServerJa3sKey = attribute.Key("tls.server.ja3s") - - // TLSServerNotAfterKey is the attribute Key conforming to the - // "tls.server.not_after" semantic conventions. It represents the date/Time - // indicating when server certificate is no longer considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021-01-01T00:00:00.000Z' - TLSServerNotAfterKey = attribute.Key("tls.server.not_after") - - // TLSServerNotBeforeKey is the attribute Key conforming to the - // "tls.server.not_before" semantic conventions. It represents the - // date/Time indicating when server certificate is first considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1970-01-01T00:00:00.000Z' - TLSServerNotBeforeKey = attribute.Key("tls.server.not_before") - - // TLSServerSubjectKey is the attribute Key conforming to the - // "tls.server.subject" semantic conventions. It represents the - // distinguished name of subject of the x.509 certificate presented by the - // server. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=myserver, OU=Documentation Team, DC=example, DC=com' - TLSServerSubjectKey = attribute.Key("tls.server.subject") -) - -var ( - // ssl - TLSProtocolNameSsl = TLSProtocolNameKey.String("ssl") - // tls - TLSProtocolNameTLS = TLSProtocolNameKey.String("tls") -) - -// TLSCipher returns an attribute KeyValue conforming to the "tls.cipher" -// semantic conventions. It represents the string indicating the -// [cipher](https://datatracker.ietf.org/doc/html/rfc5246#appendix-A.5) used -// during the current connection. -func TLSCipher(val string) attribute.KeyValue { - return TLSCipherKey.String(val) -} - -// TLSClientCertificate returns an attribute KeyValue conforming to the -// "tls.client.certificate" semantic conventions. It represents the pEM-encoded -// stand-alone certificate offered by the client. This is usually -// mutually-exclusive of `client.certificate_chain` since this value also -// exists in that list. -func TLSClientCertificate(val string) attribute.KeyValue { - return TLSClientCertificateKey.String(val) -} - -// TLSClientCertificateChain returns an attribute KeyValue conforming to the -// "tls.client.certificate_chain" semantic conventions. It represents the array -// of PEM-encoded certificates that make up the certificate chain offered by -// the client. This is usually mutually-exclusive of `client.certificate` since -// that value should be the first certificate in the chain. -func TLSClientCertificateChain(val ...string) attribute.KeyValue { - return TLSClientCertificateChainKey.StringSlice(val) -} - -// TLSClientHashMd5 returns an attribute KeyValue conforming to the -// "tls.client.hash.md5" semantic conventions. It represents the certificate -// fingerprint using the MD5 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashMd5(val string) attribute.KeyValue { - return TLSClientHashMd5Key.String(val) -} - -// TLSClientHashSha1 returns an attribute KeyValue conforming to the -// "tls.client.hash.sha1" semantic conventions. It represents the certificate -// fingerprint using the SHA1 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashSha1(val string) attribute.KeyValue { - return TLSClientHashSha1Key.String(val) -} - -// TLSClientHashSha256 returns an attribute KeyValue conforming to the -// "tls.client.hash.sha256" semantic conventions. It represents the certificate -// fingerprint using the SHA256 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashSha256(val string) attribute.KeyValue { - return TLSClientHashSha256Key.String(val) -} - -// TLSClientIssuer returns an attribute KeyValue conforming to the -// "tls.client.issuer" semantic conventions. It represents the distinguished -// name of -// [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) of -// the issuer of the x.509 certificate presented by the client. -func TLSClientIssuer(val string) attribute.KeyValue { - return TLSClientIssuerKey.String(val) -} - -// TLSClientJa3 returns an attribute KeyValue conforming to the -// "tls.client.ja3" semantic conventions. It represents a hash that identifies -// clients based on how they perform an SSL/TLS handshake. -func TLSClientJa3(val string) attribute.KeyValue { - return TLSClientJa3Key.String(val) -} - -// TLSClientNotAfter returns an attribute KeyValue conforming to the -// "tls.client.not_after" semantic conventions. It represents the date/Time -// indicating when client certificate is no longer considered valid. -func TLSClientNotAfter(val string) attribute.KeyValue { - return TLSClientNotAfterKey.String(val) -} - -// TLSClientNotBefore returns an attribute KeyValue conforming to the -// "tls.client.not_before" semantic conventions. It represents the date/Time -// indicating when client certificate is first considered valid. -func TLSClientNotBefore(val string) attribute.KeyValue { - return TLSClientNotBeforeKey.String(val) -} - -// TLSClientServerName returns an attribute KeyValue conforming to the -// "tls.client.server_name" semantic conventions. It represents the also called -// an SNI, this tells the server which hostname to which the client is -// attempting to connect to. -func TLSClientServerName(val string) attribute.KeyValue { - return TLSClientServerNameKey.String(val) -} - -// TLSClientSubject returns an attribute KeyValue conforming to the -// "tls.client.subject" semantic conventions. It represents the distinguished -// name of subject of the x.509 certificate presented by the client. -func TLSClientSubject(val string) attribute.KeyValue { - return TLSClientSubjectKey.String(val) -} - -// TLSClientSupportedCiphers returns an attribute KeyValue conforming to the -// "tls.client.supported_ciphers" semantic conventions. It represents the array -// of ciphers offered by the client during the client hello. -func TLSClientSupportedCiphers(val ...string) attribute.KeyValue { - return TLSClientSupportedCiphersKey.StringSlice(val) -} - -// TLSCurve returns an attribute KeyValue conforming to the "tls.curve" -// semantic conventions. It represents the string indicating the curve used for -// the given cipher, when applicable -func TLSCurve(val string) attribute.KeyValue { - return TLSCurveKey.String(val) -} - -// TLSEstablished returns an attribute KeyValue conforming to the -// "tls.established" semantic conventions. It represents the boolean flag -// indicating if the TLS negotiation was successful and transitioned to an -// encrypted tunnel. -func TLSEstablished(val bool) attribute.KeyValue { - return TLSEstablishedKey.Bool(val) -} - -// TLSNextProtocol returns an attribute KeyValue conforming to the -// "tls.next_protocol" semantic conventions. It represents the string -// indicating the protocol being tunneled. Per the values in the [IANA -// registry](https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids), -// this string should be lower case. -func TLSNextProtocol(val string) attribute.KeyValue { - return TLSNextProtocolKey.String(val) -} - -// TLSProtocolVersion returns an attribute KeyValue conforming to the -// "tls.protocol.version" semantic conventions. It represents the numeric part -// of the version parsed from the original string of the negotiated [SSL/TLS -// protocol -// version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) -func TLSProtocolVersion(val string) attribute.KeyValue { - return TLSProtocolVersionKey.String(val) -} - -// TLSResumed returns an attribute KeyValue conforming to the "tls.resumed" -// semantic conventions. It represents the boolean flag indicating if this TLS -// connection was resumed from an existing TLS negotiation. -func TLSResumed(val bool) attribute.KeyValue { - return TLSResumedKey.Bool(val) -} - -// TLSServerCertificate returns an attribute KeyValue conforming to the -// "tls.server.certificate" semantic conventions. It represents the pEM-encoded -// stand-alone certificate offered by the server. This is usually -// mutually-exclusive of `server.certificate_chain` since this value also -// exists in that list. -func TLSServerCertificate(val string) attribute.KeyValue { - return TLSServerCertificateKey.String(val) -} - -// TLSServerCertificateChain returns an attribute KeyValue conforming to the -// "tls.server.certificate_chain" semantic conventions. It represents the array -// of PEM-encoded certificates that make up the certificate chain offered by -// the server. This is usually mutually-exclusive of `server.certificate` since -// that value should be the first certificate in the chain. -func TLSServerCertificateChain(val ...string) attribute.KeyValue { - return TLSServerCertificateChainKey.StringSlice(val) -} - -// TLSServerHashMd5 returns an attribute KeyValue conforming to the -// "tls.server.hash.md5" semantic conventions. It represents the certificate -// fingerprint using the MD5 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashMd5(val string) attribute.KeyValue { - return TLSServerHashMd5Key.String(val) -} - -// TLSServerHashSha1 returns an attribute KeyValue conforming to the -// "tls.server.hash.sha1" semantic conventions. It represents the certificate -// fingerprint using the SHA1 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashSha1(val string) attribute.KeyValue { - return TLSServerHashSha1Key.String(val) -} - -// TLSServerHashSha256 returns an attribute KeyValue conforming to the -// "tls.server.hash.sha256" semantic conventions. It represents the certificate -// fingerprint using the SHA256 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashSha256(val string) attribute.KeyValue { - return TLSServerHashSha256Key.String(val) -} - -// TLSServerIssuer returns an attribute KeyValue conforming to the -// "tls.server.issuer" semantic conventions. It represents the distinguished -// name of -// [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) of -// the issuer of the x.509 certificate presented by the client. -func TLSServerIssuer(val string) attribute.KeyValue { - return TLSServerIssuerKey.String(val) -} - -// TLSServerJa3s returns an attribute KeyValue conforming to the -// "tls.server.ja3s" semantic conventions. It represents a hash that identifies -// servers based on how they perform an SSL/TLS handshake. -func TLSServerJa3s(val string) attribute.KeyValue { - return TLSServerJa3sKey.String(val) -} - -// TLSServerNotAfter returns an attribute KeyValue conforming to the -// "tls.server.not_after" semantic conventions. It represents the date/Time -// indicating when server certificate is no longer considered valid. -func TLSServerNotAfter(val string) attribute.KeyValue { - return TLSServerNotAfterKey.String(val) -} - -// TLSServerNotBefore returns an attribute KeyValue conforming to the -// "tls.server.not_before" semantic conventions. It represents the date/Time -// indicating when server certificate is first considered valid. -func TLSServerNotBefore(val string) attribute.KeyValue { - return TLSServerNotBeforeKey.String(val) -} - -// TLSServerSubject returns an attribute KeyValue conforming to the -// "tls.server.subject" semantic conventions. It represents the distinguished -// name of subject of the x.509 certificate presented by the server. -func TLSServerSubject(val string) attribute.KeyValue { - return TLSServerSubjectKey.String(val) -} - -// Attributes describing URL. -const ( - // URLDomainKey is the attribute Key conforming to the "url.domain" - // semantic conventions. It represents the domain extracted from the - // `url.full`, such as "opentelemetry.io". - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'www.foo.bar', 'opentelemetry.io', '3.12.167.2', - // '[1080:0:0:0:8:800:200C:417A]' - // Note: In some cases a URL may refer to an IP and/or port directly, - // without a domain name. In this case, the IP address would go to the - // domain field. If the URL contains a [literal IPv6 - // address](https://www.rfc-editor.org/rfc/rfc2732#section-2) enclosed by - // `[` and `]`, the `[` and `]` characters should also be captured in the - // domain field. - URLDomainKey = attribute.Key("url.domain") - - // URLExtensionKey is the attribute Key conforming to the "url.extension" - // semantic conventions. It represents the file extension extracted from - // the `url.full`, excluding the leading dot. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'png', 'gz' - // Note: The file extension is only set if it exists, as not every url has - // a file extension. When the file name has multiple extensions - // `example.tar.gz`, only the last one should be captured `gz`, not - // `tar.gz`. - URLExtensionKey = attribute.Key("url.extension") - - // URLFragmentKey is the attribute Key conforming to the "url.fragment" - // semantic conventions. It represents the [URI - // fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'SemConv' - URLFragmentKey = attribute.Key("url.fragment") - - // URLFullKey is the attribute Key conforming to the "url.full" semantic - // conventions. It represents the absolute URL describing a network - // resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv', - // '//localhost' - // Note: For network calls, URL usually has - // `scheme://host[:port][path][?query][#fragment]` format, where the - // fragment is not transmitted over HTTP, but if it is known, it SHOULD be - // included nevertheless. - // `url.full` MUST NOT contain credentials passed via URL in form of - // `https://username:password@www.example.com/`. In such case username and - // password SHOULD be redacted and attribute's value SHOULD be - // `https://REDACTED:REDACTED@www.example.com/`. - // `url.full` SHOULD capture the absolute URL when it is available (or can - // be reconstructed). Sensitive content provided in `url.full` SHOULD be - // scrubbed when instrumentations can identify it. - URLFullKey = attribute.Key("url.full") - - // URLOriginalKey is the attribute Key conforming to the "url.original" - // semantic conventions. It represents the unmodified original URL as seen - // in the event source. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv', - // 'search?q=OpenTelemetry' - // Note: In network monitoring, the observed URL may be a full URL, whereas - // in access logs, the URL is often just represented as a path. This field - // is meant to represent the URL as it was observed, complete or not. - // `url.original` might contain credentials passed via URL in form of - // `https://username:password@www.example.com/`. In such case password and - // username SHOULD NOT be redacted and attribute's value SHOULD remain the - // same. - URLOriginalKey = attribute.Key("url.original") - - // URLPathKey is the attribute Key conforming to the "url.path" semantic - // conventions. It represents the [URI - // path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/search' - // Note: Sensitive content provided in `url.path` SHOULD be scrubbed when - // instrumentations can identify it. - URLPathKey = attribute.Key("url.path") - - // URLPortKey is the attribute Key conforming to the "url.port" semantic - // conventions. It represents the port extracted from the `url.full` - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 443 - URLPortKey = attribute.Key("url.port") - - // URLQueryKey is the attribute Key conforming to the "url.query" semantic - // conventions. It represents the [URI - // query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'q=OpenTelemetry' - // Note: Sensitive content provided in `url.query` SHOULD be scrubbed when - // instrumentations can identify it. - URLQueryKey = attribute.Key("url.query") - - // URLRegisteredDomainKey is the attribute Key conforming to the - // "url.registered_domain" semantic conventions. It represents the highest - // registered url domain, stripped of the subdomain. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'example.com', 'foo.co.uk' - // Note: This value can be determined precisely with the [public suffix - // list](http://publicsuffix.org). For example, the registered domain for - // `foo.example.com` is `example.com`. Trying to approximate this by simply - // taking the last two labels will not work well for TLDs such as `co.uk`. - URLRegisteredDomainKey = attribute.Key("url.registered_domain") - - // URLSchemeKey is the attribute Key conforming to the "url.scheme" - // semantic conventions. It represents the [URI - // scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component - // identifying the used protocol. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'https', 'ftp', 'telnet' - URLSchemeKey = attribute.Key("url.scheme") - - // URLSubdomainKey is the attribute Key conforming to the "url.subdomain" - // semantic conventions. It represents the subdomain portion of a fully - // qualified domain name includes all of the names except the host name - // under the registered_domain. In a partially qualified domain, or if the - // qualification level of the full name cannot be determined, subdomain - // contains all of the names below the registered domain. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'east', 'sub2.sub1' - // Note: The subdomain portion of `www.east.mydomain.co.uk` is `east`. If - // the domain has multiple levels of subdomain, such as - // `sub2.sub1.example.com`, the subdomain field should contain `sub2.sub1`, - // with no trailing period. - URLSubdomainKey = attribute.Key("url.subdomain") - - // URLTemplateKey is the attribute Key conforming to the "url.template" - // semantic conventions. It represents the low-cardinality template of an - // [absolute path - // reference](https://www.rfc-editor.org/rfc/rfc3986#section-4.2). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/users/{id}', '/users/:id', '/users?id={id}' - URLTemplateKey = attribute.Key("url.template") - - // URLTopLevelDomainKey is the attribute Key conforming to the - // "url.top_level_domain" semantic conventions. It represents the effective - // top level domain (eTLD), also known as the domain suffix, is the last - // part of the domain name. For example, the top level domain for - // example.com is `com`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'com', 'co.uk' - // Note: This value can be determined precisely with the [public suffix - // list](http://publicsuffix.org). - URLTopLevelDomainKey = attribute.Key("url.top_level_domain") -) - -// URLDomain returns an attribute KeyValue conforming to the "url.domain" -// semantic conventions. It represents the domain extracted from the -// `url.full`, such as "opentelemetry.io". -func URLDomain(val string) attribute.KeyValue { - return URLDomainKey.String(val) -} - -// URLExtension returns an attribute KeyValue conforming to the -// "url.extension" semantic conventions. It represents the file extension -// extracted from the `url.full`, excluding the leading dot. -func URLExtension(val string) attribute.KeyValue { - return URLExtensionKey.String(val) -} - -// URLFragment returns an attribute KeyValue conforming to the -// "url.fragment" semantic conventions. It represents the [URI -// fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component -func URLFragment(val string) attribute.KeyValue { - return URLFragmentKey.String(val) -} - -// URLFull returns an attribute KeyValue conforming to the "url.full" -// semantic conventions. It represents the absolute URL describing a network -// resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) -func URLFull(val string) attribute.KeyValue { - return URLFullKey.String(val) -} - -// URLOriginal returns an attribute KeyValue conforming to the -// "url.original" semantic conventions. It represents the unmodified original -// URL as seen in the event source. -func URLOriginal(val string) attribute.KeyValue { - return URLOriginalKey.String(val) -} - -// URLPath returns an attribute KeyValue conforming to the "url.path" -// semantic conventions. It represents the [URI -// path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component -func URLPath(val string) attribute.KeyValue { - return URLPathKey.String(val) -} - -// URLPort returns an attribute KeyValue conforming to the "url.port" -// semantic conventions. It represents the port extracted from the `url.full` -func URLPort(val int) attribute.KeyValue { - return URLPortKey.Int(val) -} - -// URLQuery returns an attribute KeyValue conforming to the "url.query" -// semantic conventions. It represents the [URI -// query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component -func URLQuery(val string) attribute.KeyValue { - return URLQueryKey.String(val) -} - -// URLRegisteredDomain returns an attribute KeyValue conforming to the -// "url.registered_domain" semantic conventions. It represents the highest -// registered url domain, stripped of the subdomain. -func URLRegisteredDomain(val string) attribute.KeyValue { - return URLRegisteredDomainKey.String(val) -} - -// URLScheme returns an attribute KeyValue conforming to the "url.scheme" -// semantic conventions. It represents the [URI -// scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component -// identifying the used protocol. -func URLScheme(val string) attribute.KeyValue { - return URLSchemeKey.String(val) -} - -// URLSubdomain returns an attribute KeyValue conforming to the -// "url.subdomain" semantic conventions. It represents the subdomain portion of -// a fully qualified domain name includes all of the names except the host name -// under the registered_domain. In a partially qualified domain, or if the -// qualification level of the full name cannot be determined, subdomain -// contains all of the names below the registered domain. -func URLSubdomain(val string) attribute.KeyValue { - return URLSubdomainKey.String(val) -} - -// URLTemplate returns an attribute KeyValue conforming to the -// "url.template" semantic conventions. It represents the low-cardinality -// template of an [absolute path -// reference](https://www.rfc-editor.org/rfc/rfc3986#section-4.2). -func URLTemplate(val string) attribute.KeyValue { - return URLTemplateKey.String(val) -} - -// URLTopLevelDomain returns an attribute KeyValue conforming to the -// "url.top_level_domain" semantic conventions. It represents the effective top -// level domain (eTLD), also known as the domain suffix, is the last part of -// the domain name. For example, the top level domain for example.com is `com`. -func URLTopLevelDomain(val string) attribute.KeyValue { - return URLTopLevelDomainKey.String(val) -} - -// Describes user-agent attributes. -const ( - // UserAgentNameKey is the attribute Key conforming to the - // "user_agent.name" semantic conventions. It represents the name of the - // user-agent extracted from original. Usually refers to the browser's - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Safari', 'YourApp' - // Note: [Example](https://www.whatsmyua.info) of extracting browser's name - // from original string. In the case of using a user-agent for non-browser - // products, such as microservices with multiple names/versions inside the - // `user_agent.original`, the most significant name SHOULD be selected. In - // such a scenario it should align with `user_agent.version` - UserAgentNameKey = attribute.Key("user_agent.name") - - // UserAgentOriginalKey is the attribute Key conforming to the - // "user_agent.original" semantic conventions. It represents the value of - // the [HTTP - // User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) - // header sent by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'CERN-LineMode/2.15 libwww/2.17b3', 'Mozilla/5.0 (iPhone; CPU - // iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) - // Version/14.1.2 Mobile/15E148 Safari/604.1', 'YourApp/1.0.0 - // grpc-java-okhttp/1.27.2' - UserAgentOriginalKey = attribute.Key("user_agent.original") - - // UserAgentVersionKey is the attribute Key conforming to the - // "user_agent.version" semantic conventions. It represents the version of - // the user-agent extracted from original. Usually refers to the browser's - // version - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '14.1.2', '1.0.0' - // Note: [Example](https://www.whatsmyua.info) of extracting browser's - // version from original string. In the case of using a user-agent for - // non-browser products, such as microservices with multiple names/versions - // inside the `user_agent.original`, the most significant version SHOULD be - // selected. In such a scenario it should align with `user_agent.name` - UserAgentVersionKey = attribute.Key("user_agent.version") -) - -// UserAgentName returns an attribute KeyValue conforming to the -// "user_agent.name" semantic conventions. It represents the name of the -// user-agent extracted from original. Usually refers to the browser's name. -func UserAgentName(val string) attribute.KeyValue { - return UserAgentNameKey.String(val) -} - -// UserAgentOriginal returns an attribute KeyValue conforming to the -// "user_agent.original" semantic conventions. It represents the value of the -// [HTTP -// User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) -// header sent by the client. -func UserAgentOriginal(val string) attribute.KeyValue { - return UserAgentOriginalKey.String(val) -} - -// UserAgentVersion returns an attribute KeyValue conforming to the -// "user_agent.version" semantic conventions. It represents the version of the -// user-agent extracted from original. Usually refers to the browser's version -func UserAgentVersion(val string) attribute.KeyValue { - return UserAgentVersionKey.String(val) -} - -// The attributes used to describe the packaged software running the -// application code. -const ( - // WebEngineDescriptionKey is the attribute Key conforming to the - // "webengine.description" semantic conventions. It represents the - // additional description of the web engine (e.g. detailed version and - // edition information). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - - // 2.2.2.Final' - WebEngineDescriptionKey = attribute.Key("webengine.description") - - // WebEngineNameKey is the attribute Key conforming to the "webengine.name" - // semantic conventions. It represents the name of the web engine. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'WildFly' - WebEngineNameKey = attribute.Key("webengine.name") - - // WebEngineVersionKey is the attribute Key conforming to the - // "webengine.version" semantic conventions. It represents the version of - // the web engine. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '21.0.0' - WebEngineVersionKey = attribute.Key("webengine.version") -) - -// WebEngineDescription returns an attribute KeyValue conforming to the -// "webengine.description" semantic conventions. It represents the additional -// description of the web engine (e.g. detailed version and edition -// information). -func WebEngineDescription(val string) attribute.KeyValue { - return WebEngineDescriptionKey.String(val) -} - -// WebEngineName returns an attribute KeyValue conforming to the -// "webengine.name" semantic conventions. It represents the name of the web -// engine. -func WebEngineName(val string) attribute.KeyValue { - return WebEngineNameKey.String(val) -} - -// WebEngineVersion returns an attribute KeyValue conforming to the -// "webengine.version" semantic conventions. It represents the version of the -// web engine. -func WebEngineVersion(val string) attribute.KeyValue { - return WebEngineVersionKey.String(val) -} diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/doc.go b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/doc.go deleted file mode 100644 index d031bbea7..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconv implements OpenTelemetry semantic conventions. -// -// OpenTelemetry semantic conventions are agreed standardized naming -// patterns for OpenTelemetry things. This package represents the v1.26.0 -// version of the OpenTelemetry semantic conventions. -package semconv // import "go.opentelemetry.io/otel/semconv/v1.26.0" diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/exception.go b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/exception.go deleted file mode 100644 index bfaee0d56..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/exception.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.26.0" - -const ( - // ExceptionEventName is the name of the Span event representing an exception. - ExceptionEventName = "exception" -) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/metric.go b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/metric.go deleted file mode 100644 index fcdb9f485..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/metric.go +++ /dev/null @@ -1,1307 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.26.0" - -const ( - - // ContainerCPUTime is the metric conforming to the "container.cpu.time" - // semantic conventions. It represents the total CPU time consumed. - // Instrument: counter - // Unit: s - // Stability: Experimental - ContainerCPUTimeName = "container.cpu.time" - ContainerCPUTimeUnit = "s" - ContainerCPUTimeDescription = "Total CPU time consumed" - - // ContainerMemoryUsage is the metric conforming to the - // "container.memory.usage" semantic conventions. It represents the memory - // usage of the container. - // Instrument: counter - // Unit: By - // Stability: Experimental - ContainerMemoryUsageName = "container.memory.usage" - ContainerMemoryUsageUnit = "By" - ContainerMemoryUsageDescription = "Memory usage of the container." - - // ContainerDiskIo is the metric conforming to the "container.disk.io" semantic - // conventions. It represents the disk bytes for the container. - // Instrument: counter - // Unit: By - // Stability: Experimental - ContainerDiskIoName = "container.disk.io" - ContainerDiskIoUnit = "By" - ContainerDiskIoDescription = "Disk bytes for the container." - - // ContainerNetworkIo is the metric conforming to the "container.network.io" - // semantic conventions. It represents the network bytes for the container. - // Instrument: counter - // Unit: By - // Stability: Experimental - ContainerNetworkIoName = "container.network.io" - ContainerNetworkIoUnit = "By" - ContainerNetworkIoDescription = "Network bytes for the container." - - // DBClientOperationDuration is the metric conforming to the - // "db.client.operation.duration" semantic conventions. It represents the - // duration of database client operations. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DBClientOperationDurationName = "db.client.operation.duration" - DBClientOperationDurationUnit = "s" - DBClientOperationDurationDescription = "Duration of database client operations." - - // DBClientConnectionCount is the metric conforming to the - // "db.client.connection.count" semantic conventions. It represents the number - // of connections that are currently in state described by the `state` - // attribute. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionCountName = "db.client.connection.count" - DBClientConnectionCountUnit = "{connection}" - DBClientConnectionCountDescription = "The number of connections that are currently in state described by the `state` attribute" - - // DBClientConnectionIdleMax is the metric conforming to the - // "db.client.connection.idle.max" semantic conventions. It represents the - // maximum number of idle open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionIdleMaxName = "db.client.connection.idle.max" - DBClientConnectionIdleMaxUnit = "{connection}" - DBClientConnectionIdleMaxDescription = "The maximum number of idle open connections allowed" - - // DBClientConnectionIdleMin is the metric conforming to the - // "db.client.connection.idle.min" semantic conventions. It represents the - // minimum number of idle open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionIdleMinName = "db.client.connection.idle.min" - DBClientConnectionIdleMinUnit = "{connection}" - DBClientConnectionIdleMinDescription = "The minimum number of idle open connections allowed" - - // DBClientConnectionMax is the metric conforming to the - // "db.client.connection.max" semantic conventions. It represents the maximum - // number of open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionMaxName = "db.client.connection.max" - DBClientConnectionMaxUnit = "{connection}" - DBClientConnectionMaxDescription = "The maximum number of open connections allowed" - - // DBClientConnectionPendingRequests is the metric conforming to the - // "db.client.connection.pending_requests" semantic conventions. It represents - // the number of pending requests for an open connection, cumulative for the - // entire pool. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - DBClientConnectionPendingRequestsName = "db.client.connection.pending_requests" - DBClientConnectionPendingRequestsUnit = "{request}" - DBClientConnectionPendingRequestsDescription = "The number of pending requests for an open connection, cumulative for the entire pool" - - // DBClientConnectionTimeouts is the metric conforming to the - // "db.client.connection.timeouts" semantic conventions. It represents the - // number of connection timeouts that have occurred trying to obtain a - // connection from the pool. - // Instrument: counter - // Unit: {timeout} - // Stability: Experimental - DBClientConnectionTimeoutsName = "db.client.connection.timeouts" - DBClientConnectionTimeoutsUnit = "{timeout}" - DBClientConnectionTimeoutsDescription = "The number of connection timeouts that have occurred trying to obtain a connection from the pool" - - // DBClientConnectionCreateTime is the metric conforming to the - // "db.client.connection.create_time" semantic conventions. It represents the - // time it took to create a new connection. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DBClientConnectionCreateTimeName = "db.client.connection.create_time" - DBClientConnectionCreateTimeUnit = "s" - DBClientConnectionCreateTimeDescription = "The time it took to create a new connection" - - // DBClientConnectionWaitTime is the metric conforming to the - // "db.client.connection.wait_time" semantic conventions. It represents the - // time it took to obtain an open connection from the pool. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DBClientConnectionWaitTimeName = "db.client.connection.wait_time" - DBClientConnectionWaitTimeUnit = "s" - DBClientConnectionWaitTimeDescription = "The time it took to obtain an open connection from the pool" - - // DBClientConnectionUseTime is the metric conforming to the - // "db.client.connection.use_time" semantic conventions. It represents the time - // between borrowing a connection and returning it to the pool. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DBClientConnectionUseTimeName = "db.client.connection.use_time" - DBClientConnectionUseTimeUnit = "s" - DBClientConnectionUseTimeDescription = "The time between borrowing a connection and returning it to the pool" - - // DBClientConnectionsUsage is the metric conforming to the - // "db.client.connections.usage" semantic conventions. It represents the - // deprecated, use `db.client.connection.count` instead. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsUsageName = "db.client.connections.usage" - DBClientConnectionsUsageUnit = "{connection}" - DBClientConnectionsUsageDescription = "Deprecated, use `db.client.connection.count` instead." - - // DBClientConnectionsIdleMax is the metric conforming to the - // "db.client.connections.idle.max" semantic conventions. It represents the - // deprecated, use `db.client.connection.idle.max` instead. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsIdleMaxName = "db.client.connections.idle.max" - DBClientConnectionsIdleMaxUnit = "{connection}" - DBClientConnectionsIdleMaxDescription = "Deprecated, use `db.client.connection.idle.max` instead." - - // DBClientConnectionsIdleMin is the metric conforming to the - // "db.client.connections.idle.min" semantic conventions. It represents the - // deprecated, use `db.client.connection.idle.min` instead. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsIdleMinName = "db.client.connections.idle.min" - DBClientConnectionsIdleMinUnit = "{connection}" - DBClientConnectionsIdleMinDescription = "Deprecated, use `db.client.connection.idle.min` instead." - - // DBClientConnectionsMax is the metric conforming to the - // "db.client.connections.max" semantic conventions. It represents the - // deprecated, use `db.client.connection.max` instead. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsMaxName = "db.client.connections.max" - DBClientConnectionsMaxUnit = "{connection}" - DBClientConnectionsMaxDescription = "Deprecated, use `db.client.connection.max` instead." - - // DBClientConnectionsPendingRequests is the metric conforming to the - // "db.client.connections.pending_requests" semantic conventions. It represents - // the deprecated, use `db.client.connection.pending_requests` instead. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - DBClientConnectionsPendingRequestsName = "db.client.connections.pending_requests" - DBClientConnectionsPendingRequestsUnit = "{request}" - DBClientConnectionsPendingRequestsDescription = "Deprecated, use `db.client.connection.pending_requests` instead." - - // DBClientConnectionsTimeouts is the metric conforming to the - // "db.client.connections.timeouts" semantic conventions. It represents the - // deprecated, use `db.client.connection.timeouts` instead. - // Instrument: counter - // Unit: {timeout} - // Stability: Experimental - DBClientConnectionsTimeoutsName = "db.client.connections.timeouts" - DBClientConnectionsTimeoutsUnit = "{timeout}" - DBClientConnectionsTimeoutsDescription = "Deprecated, use `db.client.connection.timeouts` instead." - - // DBClientConnectionsCreateTime is the metric conforming to the - // "db.client.connections.create_time" semantic conventions. It represents the - // deprecated, use `db.client.connection.create_time` instead. Note: the unit - // also changed from `ms` to `s`. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsCreateTimeName = "db.client.connections.create_time" - DBClientConnectionsCreateTimeUnit = "ms" - DBClientConnectionsCreateTimeDescription = "Deprecated, use `db.client.connection.create_time` instead. Note: the unit also changed from `ms` to `s`." - - // DBClientConnectionsWaitTime is the metric conforming to the - // "db.client.connections.wait_time" semantic conventions. It represents the - // deprecated, use `db.client.connection.wait_time` instead. Note: the unit - // also changed from `ms` to `s`. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsWaitTimeName = "db.client.connections.wait_time" - DBClientConnectionsWaitTimeUnit = "ms" - DBClientConnectionsWaitTimeDescription = "Deprecated, use `db.client.connection.wait_time` instead. Note: the unit also changed from `ms` to `s`." - - // DBClientConnectionsUseTime is the metric conforming to the - // "db.client.connections.use_time" semantic conventions. It represents the - // deprecated, use `db.client.connection.use_time` instead. Note: the unit also - // changed from `ms` to `s`. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsUseTimeName = "db.client.connections.use_time" - DBClientConnectionsUseTimeUnit = "ms" - DBClientConnectionsUseTimeDescription = "Deprecated, use `db.client.connection.use_time` instead. Note: the unit also changed from `ms` to `s`." - - // DNSLookupDuration is the metric conforming to the "dns.lookup.duration" - // semantic conventions. It represents the measures the time taken to perform a - // DNS lookup. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DNSLookupDurationName = "dns.lookup.duration" - DNSLookupDurationUnit = "s" - DNSLookupDurationDescription = "Measures the time taken to perform a DNS lookup." - - // AspnetcoreRoutingMatchAttempts is the metric conforming to the - // "aspnetcore.routing.match_attempts" semantic conventions. It represents the - // number of requests that were attempted to be matched to an endpoint. - // Instrument: counter - // Unit: {match_attempt} - // Stability: Stable - AspnetcoreRoutingMatchAttemptsName = "aspnetcore.routing.match_attempts" - AspnetcoreRoutingMatchAttemptsUnit = "{match_attempt}" - AspnetcoreRoutingMatchAttemptsDescription = "Number of requests that were attempted to be matched to an endpoint." - - // AspnetcoreDiagnosticsExceptions is the metric conforming to the - // "aspnetcore.diagnostics.exceptions" semantic conventions. It represents the - // number of exceptions caught by exception handling middleware. - // Instrument: counter - // Unit: {exception} - // Stability: Stable - AspnetcoreDiagnosticsExceptionsName = "aspnetcore.diagnostics.exceptions" - AspnetcoreDiagnosticsExceptionsUnit = "{exception}" - AspnetcoreDiagnosticsExceptionsDescription = "Number of exceptions caught by exception handling middleware." - - // AspnetcoreRateLimitingActiveRequestLeases is the metric conforming to the - // "aspnetcore.rate_limiting.active_request_leases" semantic conventions. It - // represents the number of requests that are currently active on the server - // that hold a rate limiting lease. - // Instrument: updowncounter - // Unit: {request} - // Stability: Stable - AspnetcoreRateLimitingActiveRequestLeasesName = "aspnetcore.rate_limiting.active_request_leases" - AspnetcoreRateLimitingActiveRequestLeasesUnit = "{request}" - AspnetcoreRateLimitingActiveRequestLeasesDescription = "Number of requests that are currently active on the server that hold a rate limiting lease." - - // AspnetcoreRateLimitingRequestLeaseDuration is the metric conforming to the - // "aspnetcore.rate_limiting.request_lease.duration" semantic conventions. It - // represents the duration of rate limiting lease held by requests on the - // server. - // Instrument: histogram - // Unit: s - // Stability: Stable - AspnetcoreRateLimitingRequestLeaseDurationName = "aspnetcore.rate_limiting.request_lease.duration" - AspnetcoreRateLimitingRequestLeaseDurationUnit = "s" - AspnetcoreRateLimitingRequestLeaseDurationDescription = "The duration of rate limiting lease held by requests on the server." - - // AspnetcoreRateLimitingRequestTimeInQueue is the metric conforming to the - // "aspnetcore.rate_limiting.request.time_in_queue" semantic conventions. It - // represents the time the request spent in a queue waiting to acquire a rate - // limiting lease. - // Instrument: histogram - // Unit: s - // Stability: Stable - AspnetcoreRateLimitingRequestTimeInQueueName = "aspnetcore.rate_limiting.request.time_in_queue" - AspnetcoreRateLimitingRequestTimeInQueueUnit = "s" - AspnetcoreRateLimitingRequestTimeInQueueDescription = "The time the request spent in a queue waiting to acquire a rate limiting lease." - - // AspnetcoreRateLimitingQueuedRequests is the metric conforming to the - // "aspnetcore.rate_limiting.queued_requests" semantic conventions. It - // represents the number of requests that are currently queued, waiting to - // acquire a rate limiting lease. - // Instrument: updowncounter - // Unit: {request} - // Stability: Stable - AspnetcoreRateLimitingQueuedRequestsName = "aspnetcore.rate_limiting.queued_requests" - AspnetcoreRateLimitingQueuedRequestsUnit = "{request}" - AspnetcoreRateLimitingQueuedRequestsDescription = "Number of requests that are currently queued, waiting to acquire a rate limiting lease." - - // AspnetcoreRateLimitingRequests is the metric conforming to the - // "aspnetcore.rate_limiting.requests" semantic conventions. It represents the - // number of requests that tried to acquire a rate limiting lease. - // Instrument: counter - // Unit: {request} - // Stability: Stable - AspnetcoreRateLimitingRequestsName = "aspnetcore.rate_limiting.requests" - AspnetcoreRateLimitingRequestsUnit = "{request}" - AspnetcoreRateLimitingRequestsDescription = "Number of requests that tried to acquire a rate limiting lease." - - // KestrelActiveConnections is the metric conforming to the - // "kestrel.active_connections" semantic conventions. It represents the number - // of connections that are currently active on the server. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Stable - KestrelActiveConnectionsName = "kestrel.active_connections" - KestrelActiveConnectionsUnit = "{connection}" - KestrelActiveConnectionsDescription = "Number of connections that are currently active on the server." - - // KestrelConnectionDuration is the metric conforming to the - // "kestrel.connection.duration" semantic conventions. It represents the - // duration of connections on the server. - // Instrument: histogram - // Unit: s - // Stability: Stable - KestrelConnectionDurationName = "kestrel.connection.duration" - KestrelConnectionDurationUnit = "s" - KestrelConnectionDurationDescription = "The duration of connections on the server." - - // KestrelRejectedConnections is the metric conforming to the - // "kestrel.rejected_connections" semantic conventions. It represents the - // number of connections rejected by the server. - // Instrument: counter - // Unit: {connection} - // Stability: Stable - KestrelRejectedConnectionsName = "kestrel.rejected_connections" - KestrelRejectedConnectionsUnit = "{connection}" - KestrelRejectedConnectionsDescription = "Number of connections rejected by the server." - - // KestrelQueuedConnections is the metric conforming to the - // "kestrel.queued_connections" semantic conventions. It represents the number - // of connections that are currently queued and are waiting to start. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Stable - KestrelQueuedConnectionsName = "kestrel.queued_connections" - KestrelQueuedConnectionsUnit = "{connection}" - KestrelQueuedConnectionsDescription = "Number of connections that are currently queued and are waiting to start." - - // KestrelQueuedRequests is the metric conforming to the - // "kestrel.queued_requests" semantic conventions. It represents the number of - // HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are - // currently queued and are waiting to start. - // Instrument: updowncounter - // Unit: {request} - // Stability: Stable - KestrelQueuedRequestsName = "kestrel.queued_requests" - KestrelQueuedRequestsUnit = "{request}" - KestrelQueuedRequestsDescription = "Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start." - - // KestrelUpgradedConnections is the metric conforming to the - // "kestrel.upgraded_connections" semantic conventions. It represents the - // number of connections that are currently upgraded (WebSockets). . - // Instrument: updowncounter - // Unit: {connection} - // Stability: Stable - KestrelUpgradedConnectionsName = "kestrel.upgraded_connections" - KestrelUpgradedConnectionsUnit = "{connection}" - KestrelUpgradedConnectionsDescription = "Number of connections that are currently upgraded (WebSockets). ." - - // KestrelTLSHandshakeDuration is the metric conforming to the - // "kestrel.tls_handshake.duration" semantic conventions. It represents the - // duration of TLS handshakes on the server. - // Instrument: histogram - // Unit: s - // Stability: Stable - KestrelTLSHandshakeDurationName = "kestrel.tls_handshake.duration" - KestrelTLSHandshakeDurationUnit = "s" - KestrelTLSHandshakeDurationDescription = "The duration of TLS handshakes on the server." - - // KestrelActiveTLSHandshakes is the metric conforming to the - // "kestrel.active_tls_handshakes" semantic conventions. It represents the - // number of TLS handshakes that are currently in progress on the server. - // Instrument: updowncounter - // Unit: {handshake} - // Stability: Stable - KestrelActiveTLSHandshakesName = "kestrel.active_tls_handshakes" - KestrelActiveTLSHandshakesUnit = "{handshake}" - KestrelActiveTLSHandshakesDescription = "Number of TLS handshakes that are currently in progress on the server." - - // SignalrServerConnectionDuration is the metric conforming to the - // "signalr.server.connection.duration" semantic conventions. It represents the - // duration of connections on the server. - // Instrument: histogram - // Unit: s - // Stability: Stable - SignalrServerConnectionDurationName = "signalr.server.connection.duration" - SignalrServerConnectionDurationUnit = "s" - SignalrServerConnectionDurationDescription = "The duration of connections on the server." - - // SignalrServerActiveConnections is the metric conforming to the - // "signalr.server.active_connections" semantic conventions. It represents the - // number of connections that are currently active on the server. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Stable - SignalrServerActiveConnectionsName = "signalr.server.active_connections" - SignalrServerActiveConnectionsUnit = "{connection}" - SignalrServerActiveConnectionsDescription = "Number of connections that are currently active on the server." - - // FaaSInvokeDuration is the metric conforming to the "faas.invoke_duration" - // semantic conventions. It represents the measures the duration of the - // function's logic execution. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSInvokeDurationName = "faas.invoke_duration" - FaaSInvokeDurationUnit = "s" - FaaSInvokeDurationDescription = "Measures the duration of the function's logic execution" - - // FaaSInitDuration is the metric conforming to the "faas.init_duration" - // semantic conventions. It represents the measures the duration of the - // function's initialization, such as a cold start. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSInitDurationName = "faas.init_duration" - FaaSInitDurationUnit = "s" - FaaSInitDurationDescription = "Measures the duration of the function's initialization, such as a cold start" - - // FaaSColdstarts is the metric conforming to the "faas.coldstarts" semantic - // conventions. It represents the number of invocation cold starts. - // Instrument: counter - // Unit: {coldstart} - // Stability: Experimental - FaaSColdstartsName = "faas.coldstarts" - FaaSColdstartsUnit = "{coldstart}" - FaaSColdstartsDescription = "Number of invocation cold starts" - - // FaaSErrors is the metric conforming to the "faas.errors" semantic - // conventions. It represents the number of invocation errors. - // Instrument: counter - // Unit: {error} - // Stability: Experimental - FaaSErrorsName = "faas.errors" - FaaSErrorsUnit = "{error}" - FaaSErrorsDescription = "Number of invocation errors" - - // FaaSInvocations is the metric conforming to the "faas.invocations" semantic - // conventions. It represents the number of successful invocations. - // Instrument: counter - // Unit: {invocation} - // Stability: Experimental - FaaSInvocationsName = "faas.invocations" - FaaSInvocationsUnit = "{invocation}" - FaaSInvocationsDescription = "Number of successful invocations" - - // FaaSTimeouts is the metric conforming to the "faas.timeouts" semantic - // conventions. It represents the number of invocation timeouts. - // Instrument: counter - // Unit: {timeout} - // Stability: Experimental - FaaSTimeoutsName = "faas.timeouts" - FaaSTimeoutsUnit = "{timeout}" - FaaSTimeoutsDescription = "Number of invocation timeouts" - - // FaaSMemUsage is the metric conforming to the "faas.mem_usage" semantic - // conventions. It represents the distribution of max memory usage per - // invocation. - // Instrument: histogram - // Unit: By - // Stability: Experimental - FaaSMemUsageName = "faas.mem_usage" - FaaSMemUsageUnit = "By" - FaaSMemUsageDescription = "Distribution of max memory usage per invocation" - - // FaaSCPUUsage is the metric conforming to the "faas.cpu_usage" semantic - // conventions. It represents the distribution of CPU usage per invocation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSCPUUsageName = "faas.cpu_usage" - FaaSCPUUsageUnit = "s" - FaaSCPUUsageDescription = "Distribution of CPU usage per invocation" - - // FaaSNetIo is the metric conforming to the "faas.net_io" semantic - // conventions. It represents the distribution of net I/O usage per invocation. - // Instrument: histogram - // Unit: By - // Stability: Experimental - FaaSNetIoName = "faas.net_io" - FaaSNetIoUnit = "By" - FaaSNetIoDescription = "Distribution of net I/O usage per invocation" - - // HTTPServerRequestDuration is the metric conforming to the - // "http.server.request.duration" semantic conventions. It represents the - // duration of HTTP server requests. - // Instrument: histogram - // Unit: s - // Stability: Stable - HTTPServerRequestDurationName = "http.server.request.duration" - HTTPServerRequestDurationUnit = "s" - HTTPServerRequestDurationDescription = "Duration of HTTP server requests." - - // HTTPServerActiveRequests is the metric conforming to the - // "http.server.active_requests" semantic conventions. It represents the number - // of active HTTP server requests. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - HTTPServerActiveRequestsName = "http.server.active_requests" - HTTPServerActiveRequestsUnit = "{request}" - HTTPServerActiveRequestsDescription = "Number of active HTTP server requests." - - // HTTPServerRequestBodySize is the metric conforming to the - // "http.server.request.body.size" semantic conventions. It represents the size - // of HTTP server request bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPServerRequestBodySizeName = "http.server.request.body.size" - HTTPServerRequestBodySizeUnit = "By" - HTTPServerRequestBodySizeDescription = "Size of HTTP server request bodies." - - // HTTPServerResponseBodySize is the metric conforming to the - // "http.server.response.body.size" semantic conventions. It represents the - // size of HTTP server response bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPServerResponseBodySizeName = "http.server.response.body.size" - HTTPServerResponseBodySizeUnit = "By" - HTTPServerResponseBodySizeDescription = "Size of HTTP server response bodies." - - // HTTPClientRequestDuration is the metric conforming to the - // "http.client.request.duration" semantic conventions. It represents the - // duration of HTTP client requests. - // Instrument: histogram - // Unit: s - // Stability: Stable - HTTPClientRequestDurationName = "http.client.request.duration" - HTTPClientRequestDurationUnit = "s" - HTTPClientRequestDurationDescription = "Duration of HTTP client requests." - - // HTTPClientRequestBodySize is the metric conforming to the - // "http.client.request.body.size" semantic conventions. It represents the size - // of HTTP client request bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPClientRequestBodySizeName = "http.client.request.body.size" - HTTPClientRequestBodySizeUnit = "By" - HTTPClientRequestBodySizeDescription = "Size of HTTP client request bodies." - - // HTTPClientResponseBodySize is the metric conforming to the - // "http.client.response.body.size" semantic conventions. It represents the - // size of HTTP client response bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPClientResponseBodySizeName = "http.client.response.body.size" - HTTPClientResponseBodySizeUnit = "By" - HTTPClientResponseBodySizeDescription = "Size of HTTP client response bodies." - - // HTTPClientOpenConnections is the metric conforming to the - // "http.client.open_connections" semantic conventions. It represents the - // number of outbound HTTP connections that are currently active or idle on the - // client. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - HTTPClientOpenConnectionsName = "http.client.open_connections" - HTTPClientOpenConnectionsUnit = "{connection}" - HTTPClientOpenConnectionsDescription = "Number of outbound HTTP connections that are currently active or idle on the client." - - // HTTPClientConnectionDuration is the metric conforming to the - // "http.client.connection.duration" semantic conventions. It represents the - // duration of the successfully established outbound HTTP connections. - // Instrument: histogram - // Unit: s - // Stability: Experimental - HTTPClientConnectionDurationName = "http.client.connection.duration" - HTTPClientConnectionDurationUnit = "s" - HTTPClientConnectionDurationDescription = "The duration of the successfully established outbound HTTP connections." - - // HTTPClientActiveRequests is the metric conforming to the - // "http.client.active_requests" semantic conventions. It represents the number - // of active HTTP requests. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - HTTPClientActiveRequestsName = "http.client.active_requests" - HTTPClientActiveRequestsUnit = "{request}" - HTTPClientActiveRequestsDescription = "Number of active HTTP requests." - - // JvmMemoryInit is the metric conforming to the "jvm.memory.init" semantic - // conventions. It represents the measure of initial memory requested. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmMemoryInitName = "jvm.memory.init" - JvmMemoryInitUnit = "By" - JvmMemoryInitDescription = "Measure of initial memory requested." - - // JvmSystemCPUUtilization is the metric conforming to the - // "jvm.system.cpu.utilization" semantic conventions. It represents the recent - // CPU utilization for the whole system as reported by the JVM. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - JvmSystemCPUUtilizationName = "jvm.system.cpu.utilization" - JvmSystemCPUUtilizationUnit = "1" - JvmSystemCPUUtilizationDescription = "Recent CPU utilization for the whole system as reported by the JVM." - - // JvmSystemCPULoad1m is the metric conforming to the "jvm.system.cpu.load_1m" - // semantic conventions. It represents the average CPU load of the whole system - // for the last minute as reported by the JVM. - // Instrument: gauge - // Unit: {run_queue_item} - // Stability: Experimental - JvmSystemCPULoad1mName = "jvm.system.cpu.load_1m" - JvmSystemCPULoad1mUnit = "{run_queue_item}" - JvmSystemCPULoad1mDescription = "Average CPU load of the whole system for the last minute as reported by the JVM." - - // JvmBufferMemoryUsage is the metric conforming to the - // "jvm.buffer.memory.usage" semantic conventions. It represents the measure of - // memory used by buffers. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmBufferMemoryUsageName = "jvm.buffer.memory.usage" - JvmBufferMemoryUsageUnit = "By" - JvmBufferMemoryUsageDescription = "Measure of memory used by buffers." - - // JvmBufferMemoryLimit is the metric conforming to the - // "jvm.buffer.memory.limit" semantic conventions. It represents the measure of - // total memory capacity of buffers. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmBufferMemoryLimitName = "jvm.buffer.memory.limit" - JvmBufferMemoryLimitUnit = "By" - JvmBufferMemoryLimitDescription = "Measure of total memory capacity of buffers." - - // JvmBufferCount is the metric conforming to the "jvm.buffer.count" semantic - // conventions. It represents the number of buffers in the pool. - // Instrument: updowncounter - // Unit: {buffer} - // Stability: Experimental - JvmBufferCountName = "jvm.buffer.count" - JvmBufferCountUnit = "{buffer}" - JvmBufferCountDescription = "Number of buffers in the pool." - - // JvmMemoryUsed is the metric conforming to the "jvm.memory.used" semantic - // conventions. It represents the measure of memory used. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryUsedName = "jvm.memory.used" - JvmMemoryUsedUnit = "By" - JvmMemoryUsedDescription = "Measure of memory used." - - // JvmMemoryCommitted is the metric conforming to the "jvm.memory.committed" - // semantic conventions. It represents the measure of memory committed. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryCommittedName = "jvm.memory.committed" - JvmMemoryCommittedUnit = "By" - JvmMemoryCommittedDescription = "Measure of memory committed." - - // JvmMemoryLimit is the metric conforming to the "jvm.memory.limit" semantic - // conventions. It represents the measure of max obtainable memory. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryLimitName = "jvm.memory.limit" - JvmMemoryLimitUnit = "By" - JvmMemoryLimitDescription = "Measure of max obtainable memory." - - // JvmMemoryUsedAfterLastGc is the metric conforming to the - // "jvm.memory.used_after_last_gc" semantic conventions. It represents the - // measure of memory used, as measured after the most recent garbage collection - // event on this pool. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryUsedAfterLastGcName = "jvm.memory.used_after_last_gc" - JvmMemoryUsedAfterLastGcUnit = "By" - JvmMemoryUsedAfterLastGcDescription = "Measure of memory used, as measured after the most recent garbage collection event on this pool." - - // JvmGcDuration is the metric conforming to the "jvm.gc.duration" semantic - // conventions. It represents the duration of JVM garbage collection actions. - // Instrument: histogram - // Unit: s - // Stability: Stable - JvmGcDurationName = "jvm.gc.duration" - JvmGcDurationUnit = "s" - JvmGcDurationDescription = "Duration of JVM garbage collection actions." - - // JvmThreadCount is the metric conforming to the "jvm.thread.count" semantic - // conventions. It represents the number of executing platform threads. - // Instrument: updowncounter - // Unit: {thread} - // Stability: Stable - JvmThreadCountName = "jvm.thread.count" - JvmThreadCountUnit = "{thread}" - JvmThreadCountDescription = "Number of executing platform threads." - - // JvmClassLoaded is the metric conforming to the "jvm.class.loaded" semantic - // conventions. It represents the number of classes loaded since JVM start. - // Instrument: counter - // Unit: {class} - // Stability: Stable - JvmClassLoadedName = "jvm.class.loaded" - JvmClassLoadedUnit = "{class}" - JvmClassLoadedDescription = "Number of classes loaded since JVM start." - - // JvmClassUnloaded is the metric conforming to the "jvm.class.unloaded" - // semantic conventions. It represents the number of classes unloaded since JVM - // start. - // Instrument: counter - // Unit: {class} - // Stability: Stable - JvmClassUnloadedName = "jvm.class.unloaded" - JvmClassUnloadedUnit = "{class}" - JvmClassUnloadedDescription = "Number of classes unloaded since JVM start." - - // JvmClassCount is the metric conforming to the "jvm.class.count" semantic - // conventions. It represents the number of classes currently loaded. - // Instrument: updowncounter - // Unit: {class} - // Stability: Stable - JvmClassCountName = "jvm.class.count" - JvmClassCountUnit = "{class}" - JvmClassCountDescription = "Number of classes currently loaded." - - // JvmCPUCount is the metric conforming to the "jvm.cpu.count" semantic - // conventions. It represents the number of processors available to the Java - // virtual machine. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Stable - JvmCPUCountName = "jvm.cpu.count" - JvmCPUCountUnit = "{cpu}" - JvmCPUCountDescription = "Number of processors available to the Java virtual machine." - - // JvmCPUTime is the metric conforming to the "jvm.cpu.time" semantic - // conventions. It represents the cPU time used by the process as reported by - // the JVM. - // Instrument: counter - // Unit: s - // Stability: Stable - JvmCPUTimeName = "jvm.cpu.time" - JvmCPUTimeUnit = "s" - JvmCPUTimeDescription = "CPU time used by the process as reported by the JVM." - - // JvmCPURecentUtilization is the metric conforming to the - // "jvm.cpu.recent_utilization" semantic conventions. It represents the recent - // CPU utilization for the process as reported by the JVM. - // Instrument: gauge - // Unit: 1 - // Stability: Stable - JvmCPURecentUtilizationName = "jvm.cpu.recent_utilization" - JvmCPURecentUtilizationUnit = "1" - JvmCPURecentUtilizationDescription = "Recent CPU utilization for the process as reported by the JVM." - - // MessagingPublishDuration is the metric conforming to the - // "messaging.publish.duration" semantic conventions. It represents the - // measures the duration of publish operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingPublishDurationName = "messaging.publish.duration" - MessagingPublishDurationUnit = "s" - MessagingPublishDurationDescription = "Measures the duration of publish operation." - - // MessagingReceiveDuration is the metric conforming to the - // "messaging.receive.duration" semantic conventions. It represents the - // measures the duration of receive operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingReceiveDurationName = "messaging.receive.duration" - MessagingReceiveDurationUnit = "s" - MessagingReceiveDurationDescription = "Measures the duration of receive operation." - - // MessagingProcessDuration is the metric conforming to the - // "messaging.process.duration" semantic conventions. It represents the - // measures the duration of process operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingProcessDurationName = "messaging.process.duration" - MessagingProcessDurationUnit = "s" - MessagingProcessDurationDescription = "Measures the duration of process operation." - - // MessagingPublishMessages is the metric conforming to the - // "messaging.publish.messages" semantic conventions. It represents the - // measures the number of published messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingPublishMessagesName = "messaging.publish.messages" - MessagingPublishMessagesUnit = "{message}" - MessagingPublishMessagesDescription = "Measures the number of published messages." - - // MessagingReceiveMessages is the metric conforming to the - // "messaging.receive.messages" semantic conventions. It represents the - // measures the number of received messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingReceiveMessagesName = "messaging.receive.messages" - MessagingReceiveMessagesUnit = "{message}" - MessagingReceiveMessagesDescription = "Measures the number of received messages." - - // MessagingProcessMessages is the metric conforming to the - // "messaging.process.messages" semantic conventions. It represents the - // measures the number of processed messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingProcessMessagesName = "messaging.process.messages" - MessagingProcessMessagesUnit = "{message}" - MessagingProcessMessagesDescription = "Measures the number of processed messages." - - // ProcessCPUTime is the metric conforming to the "process.cpu.time" semantic - // conventions. It represents the total CPU seconds broken down by different - // states. - // Instrument: counter - // Unit: s - // Stability: Experimental - ProcessCPUTimeName = "process.cpu.time" - ProcessCPUTimeUnit = "s" - ProcessCPUTimeDescription = "Total CPU seconds broken down by different states." - - // ProcessCPUUtilization is the metric conforming to the - // "process.cpu.utilization" semantic conventions. It represents the difference - // in process.cpu.time since the last measurement, divided by the elapsed time - // and number of CPUs available to the process. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - ProcessCPUUtilizationName = "process.cpu.utilization" - ProcessCPUUtilizationUnit = "1" - ProcessCPUUtilizationDescription = "Difference in process.cpu.time since the last measurement, divided by the elapsed time and number of CPUs available to the process." - - // ProcessMemoryUsage is the metric conforming to the "process.memory.usage" - // semantic conventions. It represents the amount of physical memory in use. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - ProcessMemoryUsageName = "process.memory.usage" - ProcessMemoryUsageUnit = "By" - ProcessMemoryUsageDescription = "The amount of physical memory in use." - - // ProcessMemoryVirtual is the metric conforming to the - // "process.memory.virtual" semantic conventions. It represents the amount of - // committed virtual memory. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - ProcessMemoryVirtualName = "process.memory.virtual" - ProcessMemoryVirtualUnit = "By" - ProcessMemoryVirtualDescription = "The amount of committed virtual memory." - - // ProcessDiskIo is the metric conforming to the "process.disk.io" semantic - // conventions. It represents the disk bytes transferred. - // Instrument: counter - // Unit: By - // Stability: Experimental - ProcessDiskIoName = "process.disk.io" - ProcessDiskIoUnit = "By" - ProcessDiskIoDescription = "Disk bytes transferred." - - // ProcessNetworkIo is the metric conforming to the "process.network.io" - // semantic conventions. It represents the network bytes transferred. - // Instrument: counter - // Unit: By - // Stability: Experimental - ProcessNetworkIoName = "process.network.io" - ProcessNetworkIoUnit = "By" - ProcessNetworkIoDescription = "Network bytes transferred." - - // ProcessThreadCount is the metric conforming to the "process.thread.count" - // semantic conventions. It represents the process threads count. - // Instrument: updowncounter - // Unit: {thread} - // Stability: Experimental - ProcessThreadCountName = "process.thread.count" - ProcessThreadCountUnit = "{thread}" - ProcessThreadCountDescription = "Process threads count." - - // ProcessOpenFileDescriptorCount is the metric conforming to the - // "process.open_file_descriptor.count" semantic conventions. It represents the - // number of file descriptors in use by the process. - // Instrument: updowncounter - // Unit: {count} - // Stability: Experimental - ProcessOpenFileDescriptorCountName = "process.open_file_descriptor.count" - ProcessOpenFileDescriptorCountUnit = "{count}" - ProcessOpenFileDescriptorCountDescription = "Number of file descriptors in use by the process." - - // ProcessContextSwitches is the metric conforming to the - // "process.context_switches" semantic conventions. It represents the number of - // times the process has been context switched. - // Instrument: counter - // Unit: {count} - // Stability: Experimental - ProcessContextSwitchesName = "process.context_switches" - ProcessContextSwitchesUnit = "{count}" - ProcessContextSwitchesDescription = "Number of times the process has been context switched." - - // ProcessPagingFaults is the metric conforming to the "process.paging.faults" - // semantic conventions. It represents the number of page faults the process - // has made. - // Instrument: counter - // Unit: {fault} - // Stability: Experimental - ProcessPagingFaultsName = "process.paging.faults" - ProcessPagingFaultsUnit = "{fault}" - ProcessPagingFaultsDescription = "Number of page faults the process has made." - - // RPCServerDuration is the metric conforming to the "rpc.server.duration" - // semantic conventions. It represents the measures the duration of inbound - // RPC. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - RPCServerDurationName = "rpc.server.duration" - RPCServerDurationUnit = "ms" - RPCServerDurationDescription = "Measures the duration of inbound RPC." - - // RPCServerRequestSize is the metric conforming to the - // "rpc.server.request.size" semantic conventions. It represents the measures - // the size of RPC request messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCServerRequestSizeName = "rpc.server.request.size" - RPCServerRequestSizeUnit = "By" - RPCServerRequestSizeDescription = "Measures the size of RPC request messages (uncompressed)." - - // RPCServerResponseSize is the metric conforming to the - // "rpc.server.response.size" semantic conventions. It represents the measures - // the size of RPC response messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCServerResponseSizeName = "rpc.server.response.size" - RPCServerResponseSizeUnit = "By" - RPCServerResponseSizeDescription = "Measures the size of RPC response messages (uncompressed)." - - // RPCServerRequestsPerRPC is the metric conforming to the - // "rpc.server.requests_per_rpc" semantic conventions. It represents the - // measures the number of messages received per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCServerRequestsPerRPCName = "rpc.server.requests_per_rpc" - RPCServerRequestsPerRPCUnit = "{count}" - RPCServerRequestsPerRPCDescription = "Measures the number of messages received per RPC." - - // RPCServerResponsesPerRPC is the metric conforming to the - // "rpc.server.responses_per_rpc" semantic conventions. It represents the - // measures the number of messages sent per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCServerResponsesPerRPCName = "rpc.server.responses_per_rpc" - RPCServerResponsesPerRPCUnit = "{count}" - RPCServerResponsesPerRPCDescription = "Measures the number of messages sent per RPC." - - // RPCClientDuration is the metric conforming to the "rpc.client.duration" - // semantic conventions. It represents the measures the duration of outbound - // RPC. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - RPCClientDurationName = "rpc.client.duration" - RPCClientDurationUnit = "ms" - RPCClientDurationDescription = "Measures the duration of outbound RPC." - - // RPCClientRequestSize is the metric conforming to the - // "rpc.client.request.size" semantic conventions. It represents the measures - // the size of RPC request messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCClientRequestSizeName = "rpc.client.request.size" - RPCClientRequestSizeUnit = "By" - RPCClientRequestSizeDescription = "Measures the size of RPC request messages (uncompressed)." - - // RPCClientResponseSize is the metric conforming to the - // "rpc.client.response.size" semantic conventions. It represents the measures - // the size of RPC response messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCClientResponseSizeName = "rpc.client.response.size" - RPCClientResponseSizeUnit = "By" - RPCClientResponseSizeDescription = "Measures the size of RPC response messages (uncompressed)." - - // RPCClientRequestsPerRPC is the metric conforming to the - // "rpc.client.requests_per_rpc" semantic conventions. It represents the - // measures the number of messages received per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCClientRequestsPerRPCName = "rpc.client.requests_per_rpc" - RPCClientRequestsPerRPCUnit = "{count}" - RPCClientRequestsPerRPCDescription = "Measures the number of messages received per RPC." - - // RPCClientResponsesPerRPC is the metric conforming to the - // "rpc.client.responses_per_rpc" semantic conventions. It represents the - // measures the number of messages sent per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCClientResponsesPerRPCName = "rpc.client.responses_per_rpc" - RPCClientResponsesPerRPCUnit = "{count}" - RPCClientResponsesPerRPCDescription = "Measures the number of messages sent per RPC." - - // SystemCPUTime is the metric conforming to the "system.cpu.time" semantic - // conventions. It represents the seconds each logical CPU spent on each mode. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemCPUTimeName = "system.cpu.time" - SystemCPUTimeUnit = "s" - SystemCPUTimeDescription = "Seconds each logical CPU spent on each mode" - - // SystemCPUUtilization is the metric conforming to the - // "system.cpu.utilization" semantic conventions. It represents the difference - // in system.cpu.time since the last measurement, divided by the elapsed time - // and number of logical CPUs. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - SystemCPUUtilizationName = "system.cpu.utilization" - SystemCPUUtilizationUnit = "1" - SystemCPUUtilizationDescription = "Difference in system.cpu.time since the last measurement, divided by the elapsed time and number of logical CPUs" - - // SystemCPUFrequency is the metric conforming to the "system.cpu.frequency" - // semantic conventions. It represents the reports the current frequency of the - // CPU in Hz. - // Instrument: gauge - // Unit: {Hz} - // Stability: Experimental - SystemCPUFrequencyName = "system.cpu.frequency" - SystemCPUFrequencyUnit = "{Hz}" - SystemCPUFrequencyDescription = "Reports the current frequency of the CPU in Hz" - - // SystemCPUPhysicalCount is the metric conforming to the - // "system.cpu.physical.count" semantic conventions. It represents the reports - // the number of actual physical processor cores on the hardware. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Experimental - SystemCPUPhysicalCountName = "system.cpu.physical.count" - SystemCPUPhysicalCountUnit = "{cpu}" - SystemCPUPhysicalCountDescription = "Reports the number of actual physical processor cores on the hardware" - - // SystemCPULogicalCount is the metric conforming to the - // "system.cpu.logical.count" semantic conventions. It represents the reports - // the number of logical (virtual) processor cores created by the operating - // system to manage multitasking. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Experimental - SystemCPULogicalCountName = "system.cpu.logical.count" - SystemCPULogicalCountUnit = "{cpu}" - SystemCPULogicalCountDescription = "Reports the number of logical (virtual) processor cores created by the operating system to manage multitasking" - - // SystemMemoryUsage is the metric conforming to the "system.memory.usage" - // semantic conventions. It represents the reports memory in use by state. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemMemoryUsageName = "system.memory.usage" - SystemMemoryUsageUnit = "By" - SystemMemoryUsageDescription = "Reports memory in use by state." - - // SystemMemoryLimit is the metric conforming to the "system.memory.limit" - // semantic conventions. It represents the total memory available in the - // system. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemMemoryLimitName = "system.memory.limit" - SystemMemoryLimitUnit = "By" - SystemMemoryLimitDescription = "Total memory available in the system." - - // SystemMemoryShared is the metric conforming to the "system.memory.shared" - // semantic conventions. It represents the shared memory used (mostly by - // tmpfs). - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemMemorySharedName = "system.memory.shared" - SystemMemorySharedUnit = "By" - SystemMemorySharedDescription = "Shared memory used (mostly by tmpfs)." - - // SystemMemoryUtilization is the metric conforming to the - // "system.memory.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemMemoryUtilizationName = "system.memory.utilization" - SystemMemoryUtilizationUnit = "1" - - // SystemPagingUsage is the metric conforming to the "system.paging.usage" - // semantic conventions. It represents the unix swap or windows pagefile usage. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemPagingUsageName = "system.paging.usage" - SystemPagingUsageUnit = "By" - SystemPagingUsageDescription = "Unix swap or windows pagefile usage" - - // SystemPagingUtilization is the metric conforming to the - // "system.paging.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingUtilizationName = "system.paging.utilization" - SystemPagingUtilizationUnit = "1" - - // SystemPagingFaults is the metric conforming to the "system.paging.faults" - // semantic conventions. - // Instrument: counter - // Unit: {fault} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingFaultsName = "system.paging.faults" - SystemPagingFaultsUnit = "{fault}" - - // SystemPagingOperations is the metric conforming to the - // "system.paging.operations" semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingOperationsName = "system.paging.operations" - SystemPagingOperationsUnit = "{operation}" - - // SystemDiskIo is the metric conforming to the "system.disk.io" semantic - // conventions. - // Instrument: counter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskIoName = "system.disk.io" - SystemDiskIoUnit = "By" - - // SystemDiskOperations is the metric conforming to the - // "system.disk.operations" semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskOperationsName = "system.disk.operations" - SystemDiskOperationsUnit = "{operation}" - - // SystemDiskIoTime is the metric conforming to the "system.disk.io_time" - // semantic conventions. It represents the time disk spent activated. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemDiskIoTimeName = "system.disk.io_time" - SystemDiskIoTimeUnit = "s" - SystemDiskIoTimeDescription = "Time disk spent activated" - - // SystemDiskOperationTime is the metric conforming to the - // "system.disk.operation_time" semantic conventions. It represents the sum of - // the time each operation took to complete. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemDiskOperationTimeName = "system.disk.operation_time" - SystemDiskOperationTimeUnit = "s" - SystemDiskOperationTimeDescription = "Sum of the time each operation took to complete" - - // SystemDiskMerged is the metric conforming to the "system.disk.merged" - // semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskMergedName = "system.disk.merged" - SystemDiskMergedUnit = "{operation}" - - // SystemFilesystemUsage is the metric conforming to the - // "system.filesystem.usage" semantic conventions. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemFilesystemUsageName = "system.filesystem.usage" - SystemFilesystemUsageUnit = "By" - - // SystemFilesystemUtilization is the metric conforming to the - // "system.filesystem.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemFilesystemUtilizationName = "system.filesystem.utilization" - SystemFilesystemUtilizationUnit = "1" - - // SystemNetworkDropped is the metric conforming to the - // "system.network.dropped" semantic conventions. It represents the count of - // packets that are dropped or discarded even though there was no error. - // Instrument: counter - // Unit: {packet} - // Stability: Experimental - SystemNetworkDroppedName = "system.network.dropped" - SystemNetworkDroppedUnit = "{packet}" - SystemNetworkDroppedDescription = "Count of packets that are dropped or discarded even though there was no error" - - // SystemNetworkPackets is the metric conforming to the - // "system.network.packets" semantic conventions. - // Instrument: counter - // Unit: {packet} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkPacketsName = "system.network.packets" - SystemNetworkPacketsUnit = "{packet}" - - // SystemNetworkErrors is the metric conforming to the "system.network.errors" - // semantic conventions. It represents the count of network errors detected. - // Instrument: counter - // Unit: {error} - // Stability: Experimental - SystemNetworkErrorsName = "system.network.errors" - SystemNetworkErrorsUnit = "{error}" - SystemNetworkErrorsDescription = "Count of network errors detected" - - // SystemNetworkIo is the metric conforming to the "system.network.io" semantic - // conventions. - // Instrument: counter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkIoName = "system.network.io" - SystemNetworkIoUnit = "By" - - // SystemNetworkConnections is the metric conforming to the - // "system.network.connections" semantic conventions. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkConnectionsName = "system.network.connections" - SystemNetworkConnectionsUnit = "{connection}" - - // SystemProcessCount is the metric conforming to the "system.process.count" - // semantic conventions. It represents the total number of processes in each - // state. - // Instrument: updowncounter - // Unit: {process} - // Stability: Experimental - SystemProcessCountName = "system.process.count" - SystemProcessCountUnit = "{process}" - SystemProcessCountDescription = "Total number of processes in each state" - - // SystemProcessCreated is the metric conforming to the - // "system.process.created" semantic conventions. It represents the total - // number of processes created over uptime of the host. - // Instrument: counter - // Unit: {process} - // Stability: Experimental - SystemProcessCreatedName = "system.process.created" - SystemProcessCreatedUnit = "{process}" - SystemProcessCreatedDescription = "Total number of processes created over uptime of the host" - - // SystemLinuxMemoryAvailable is the metric conforming to the - // "system.linux.memory.available" semantic conventions. It represents an - // estimate of how much memory is available for starting new applications, - // without causing swapping. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemLinuxMemoryAvailableName = "system.linux.memory.available" - SystemLinuxMemoryAvailableUnit = "By" - SystemLinuxMemoryAvailableDescription = "An estimate of how much memory is available for starting new applications, without causing swapping" -) diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/schema.go b/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/schema.go deleted file mode 100644 index 4c87c7adc..000000000 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.26.0/schema.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.26.0" - -// SchemaURL is the schema URL that matches the version of the semantic conventions -// that this package defines. Semconv packages starting from v1.4.0 must declare -// non-empty schema URL in the form https://opentelemetry.io/schemas/ -const SchemaURL = "https://opentelemetry.io/schemas/1.26.0" diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/httpconv/metric.go b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/httpconv/metric.go new file mode 100644 index 000000000..a0ddf652d --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/httpconv/metric.go @@ -0,0 +1,1728 @@ +// Code generated from semantic convention specification. DO NOT EDIT. + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package httpconv provides types and functionality for OpenTelemetry semantic +// conventions in the "http" namespace. +package httpconv + +import ( + "context" + "sync" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/noop" +) + +var ( + addOptPool = &sync.Pool{New: func() any { return &[]metric.AddOption{} }} + recOptPool = &sync.Pool{New: func() any { return &[]metric.RecordOption{} }} +) + +// ErrorTypeAttr is an attribute conforming to the error.type semantic +// conventions. It represents the describes a class of error the operation ended +// with. +type ErrorTypeAttr string + +var ( + // ErrorTypeOther is a fallback error value to be used when the instrumentation + // doesn't define a custom value. + ErrorTypeOther ErrorTypeAttr = "_OTHER" +) + +// ConnectionStateAttr is an attribute conforming to the http.connection.state +// semantic conventions. It represents the state of the HTTP connection in the +// HTTP connection pool. +type ConnectionStateAttr string + +var ( + // ConnectionStateActive is the active state. + ConnectionStateActive ConnectionStateAttr = "active" + // ConnectionStateIdle is the idle state. + ConnectionStateIdle ConnectionStateAttr = "idle" +) + +// RequestMethodAttr is an attribute conforming to the http.request.method +// semantic conventions. It represents the HTTP request method. +type RequestMethodAttr string + +var ( + // RequestMethodConnect is the CONNECT method. + RequestMethodConnect RequestMethodAttr = "CONNECT" + // RequestMethodDelete is the DELETE method. + RequestMethodDelete RequestMethodAttr = "DELETE" + // RequestMethodGet is the GET method. + RequestMethodGet RequestMethodAttr = "GET" + // RequestMethodHead is the HEAD method. + RequestMethodHead RequestMethodAttr = "HEAD" + // RequestMethodOptions is the OPTIONS method. + RequestMethodOptions RequestMethodAttr = "OPTIONS" + // RequestMethodPatch is the PATCH method. + RequestMethodPatch RequestMethodAttr = "PATCH" + // RequestMethodPost is the POST method. + RequestMethodPost RequestMethodAttr = "POST" + // RequestMethodPut is the PUT method. + RequestMethodPut RequestMethodAttr = "PUT" + // RequestMethodTrace is the TRACE method. + RequestMethodTrace RequestMethodAttr = "TRACE" + // RequestMethodOther is the any HTTP method that the instrumentation has no + // prior knowledge of. + RequestMethodOther RequestMethodAttr = "_OTHER" +) + +// UserAgentSyntheticTypeAttr is an attribute conforming to the +// user_agent.synthetic.type semantic conventions. It represents the specifies +// the category of synthetic traffic, such as tests or bots. +type UserAgentSyntheticTypeAttr string + +var ( + // UserAgentSyntheticTypeBot is the bot source. + UserAgentSyntheticTypeBot UserAgentSyntheticTypeAttr = "bot" + // UserAgentSyntheticTypeTest is the synthetic test source. + UserAgentSyntheticTypeTest UserAgentSyntheticTypeAttr = "test" +) + +// ClientActiveRequests is an instrument used to record metric values conforming +// to the "http.client.active_requests" semantic conventions. It represents the +// number of active HTTP requests. +type ClientActiveRequests struct { + metric.Int64UpDownCounter +} + +var newClientActiveRequestsOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("Number of active HTTP requests."), + metric.WithUnit("{request}"), +} + +// NewClientActiveRequests returns a new ClientActiveRequests instrument. +func NewClientActiveRequests( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (ClientActiveRequests, error) { + // Check if the meter is nil. + if m == nil { + return ClientActiveRequests{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newClientActiveRequestsOpts + } else { + opt = append(opt, newClientActiveRequestsOpts...) + } + + i, err := m.Int64UpDownCounter( + "http.client.active_requests", + opt..., + ) + if err != nil { + return ClientActiveRequests{noop.Int64UpDownCounter{}}, err + } + return ClientActiveRequests{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientActiveRequests) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (ClientActiveRequests) Name() string { + return "http.client.active_requests" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientActiveRequests) Unit() string { + return "{request}" +} + +// Description returns the semantic convention description of the instrument +func (ClientActiveRequests) Description() string { + return "Number of active HTTP requests." +} + +// Add adds incr to the existing count for attrs. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +func (m ClientActiveRequests) Add( + ctx context.Context, + incr int64, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +func (m ClientActiveRequests) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrURLTemplate returns an optional attribute for the "url.template" semantic +// convention. It represents the low-cardinality template of an +// [absolute path reference]. +// +// [absolute path reference]: https://www.rfc-editor.org/rfc/rfc3986#section-4.2 +func (ClientActiveRequests) AttrURLTemplate(val string) attribute.KeyValue { + return attribute.String("url.template", val) +} + +// AttrRequestMethod returns an optional attribute for the "http.request.method" +// semantic convention. It represents the HTTP request method. +func (ClientActiveRequests) AttrRequestMethod(val RequestMethodAttr) attribute.KeyValue { + return attribute.String("http.request.method", string(val)) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientActiveRequests) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// ClientConnectionDuration is an instrument used to record metric values +// conforming to the "http.client.connection.duration" semantic conventions. It +// represents the duration of the successfully established outbound HTTP +// connections. +type ClientConnectionDuration struct { + metric.Float64Histogram +} + +var newClientConnectionDurationOpts = []metric.Float64HistogramOption{ + metric.WithDescription("The duration of the successfully established outbound HTTP connections."), + metric.WithUnit("s"), +} + +// NewClientConnectionDuration returns a new ClientConnectionDuration instrument. +func NewClientConnectionDuration( + m metric.Meter, + opt ...metric.Float64HistogramOption, +) (ClientConnectionDuration, error) { + // Check if the meter is nil. + if m == nil { + return ClientConnectionDuration{noop.Float64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newClientConnectionDurationOpts + } else { + opt = append(opt, newClientConnectionDurationOpts...) + } + + i, err := m.Float64Histogram( + "http.client.connection.duration", + opt..., + ) + if err != nil { + return ClientConnectionDuration{noop.Float64Histogram{}}, err + } + return ClientConnectionDuration{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientConnectionDuration) Inst() metric.Float64Histogram { + return m.Float64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ClientConnectionDuration) Name() string { + return "http.client.connection.duration" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientConnectionDuration) Unit() string { + return "s" +} + +// Description returns the semantic convention description of the instrument +func (ClientConnectionDuration) Description() string { + return "The duration of the successfully established outbound HTTP connections." +} + +// Record records val to the current distribution for attrs. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +func (m ClientConnectionDuration) Record( + ctx context.Context, + val float64, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Float64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +func (m ClientConnectionDuration) RecordSet(ctx context.Context, val float64, set attribute.Set) { + if set.Len() == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Float64Histogram.Record(ctx, val, *o...) +} + +// AttrNetworkPeerAddress returns an optional attribute for the +// "network.peer.address" semantic convention. It represents the peer address of +// the network connection - IP address or Unix domain socket name. +func (ClientConnectionDuration) AttrNetworkPeerAddress(val string) attribute.KeyValue { + return attribute.String("network.peer.address", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ClientConnectionDuration) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientConnectionDuration) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// ClientOpenConnections is an instrument used to record metric values conforming +// to the "http.client.open_connections" semantic conventions. It represents the +// number of outbound HTTP connections that are currently active or idle on the +// client. +type ClientOpenConnections struct { + metric.Int64UpDownCounter +} + +var newClientOpenConnectionsOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("Number of outbound HTTP connections that are currently active or idle on the client."), + metric.WithUnit("{connection}"), +} + +// NewClientOpenConnections returns a new ClientOpenConnections instrument. +func NewClientOpenConnections( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (ClientOpenConnections, error) { + // Check if the meter is nil. + if m == nil { + return ClientOpenConnections{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newClientOpenConnectionsOpts + } else { + opt = append(opt, newClientOpenConnectionsOpts...) + } + + i, err := m.Int64UpDownCounter( + "http.client.open_connections", + opt..., + ) + if err != nil { + return ClientOpenConnections{noop.Int64UpDownCounter{}}, err + } + return ClientOpenConnections{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientOpenConnections) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (ClientOpenConnections) Name() string { + return "http.client.open_connections" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientOpenConnections) Unit() string { + return "{connection}" +} + +// Description returns the semantic convention description of the instrument +func (ClientOpenConnections) Description() string { + return "Number of outbound HTTP connections that are currently active or idle on the client." +} + +// Add adds incr to the existing count for attrs. +// +// The connectionState is the state of the HTTP connection in the HTTP connection +// pool. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +func (m ClientOpenConnections) Add( + ctx context.Context, + incr int64, + connectionState ConnectionStateAttr, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.connection.state", string(connectionState)), + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +func (m ClientOpenConnections) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrNetworkPeerAddress returns an optional attribute for the +// "network.peer.address" semantic convention. It represents the peer address of +// the network connection - IP address or Unix domain socket name. +func (ClientOpenConnections) AttrNetworkPeerAddress(val string) attribute.KeyValue { + return attribute.String("network.peer.address", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ClientOpenConnections) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientOpenConnections) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// ClientRequestBodySize is an instrument used to record metric values conforming +// to the "http.client.request.body.size" semantic conventions. It represents the +// size of HTTP client request bodies. +type ClientRequestBodySize struct { + metric.Int64Histogram +} + +var newClientRequestBodySizeOpts = []metric.Int64HistogramOption{ + metric.WithDescription("Size of HTTP client request bodies."), + metric.WithUnit("By"), +} + +// NewClientRequestBodySize returns a new ClientRequestBodySize instrument. +func NewClientRequestBodySize( + m metric.Meter, + opt ...metric.Int64HistogramOption, +) (ClientRequestBodySize, error) { + // Check if the meter is nil. + if m == nil { + return ClientRequestBodySize{noop.Int64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newClientRequestBodySizeOpts + } else { + opt = append(opt, newClientRequestBodySizeOpts...) + } + + i, err := m.Int64Histogram( + "http.client.request.body.size", + opt..., + ) + if err != nil { + return ClientRequestBodySize{noop.Int64Histogram{}}, err + } + return ClientRequestBodySize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientRequestBodySize) Inst() metric.Int64Histogram { + return m.Int64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ClientRequestBodySize) Name() string { + return "http.client.request.body.size" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientRequestBodySize) Unit() string { + return "By" +} + +// Description returns the semantic convention description of the instrument +func (ClientRequestBodySize) Description() string { + return "Size of HTTP client request bodies." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +// +// The size of the request payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ClientRequestBodySize) Record( + ctx context.Context, + val int64, + requestMethod RequestMethodAttr, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Int64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// The size of the request payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ClientRequestBodySize) RecordSet(ctx context.Context, val int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ClientRequestBodySize) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ClientRequestBodySize) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ClientRequestBodySize) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrURLTemplate returns an optional attribute for the "url.template" semantic +// convention. It represents the low-cardinality template of an +// [absolute path reference]. +// +// [absolute path reference]: https://www.rfc-editor.org/rfc/rfc3986#section-4.2 +func (ClientRequestBodySize) AttrURLTemplate(val string) attribute.KeyValue { + return attribute.String("url.template", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ClientRequestBodySize) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientRequestBodySize) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// ClientRequestDuration is an instrument used to record metric values conforming +// to the "http.client.request.duration" semantic conventions. It represents the +// duration of HTTP client requests. +type ClientRequestDuration struct { + metric.Float64Histogram +} + +var newClientRequestDurationOpts = []metric.Float64HistogramOption{ + metric.WithDescription("Duration of HTTP client requests."), + metric.WithUnit("s"), +} + +// NewClientRequestDuration returns a new ClientRequestDuration instrument. +func NewClientRequestDuration( + m metric.Meter, + opt ...metric.Float64HistogramOption, +) (ClientRequestDuration, error) { + // Check if the meter is nil. + if m == nil { + return ClientRequestDuration{noop.Float64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newClientRequestDurationOpts + } else { + opt = append(opt, newClientRequestDurationOpts...) + } + + i, err := m.Float64Histogram( + "http.client.request.duration", + opt..., + ) + if err != nil { + return ClientRequestDuration{noop.Float64Histogram{}}, err + } + return ClientRequestDuration{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientRequestDuration) Inst() metric.Float64Histogram { + return m.Float64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ClientRequestDuration) Name() string { + return "http.client.request.duration" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientRequestDuration) Unit() string { + return "s" +} + +// Description returns the semantic convention description of the instrument +func (ClientRequestDuration) Description() string { + return "Duration of HTTP client requests." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +func (m ClientRequestDuration) Record( + ctx context.Context, + val float64, + requestMethod RequestMethodAttr, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Float64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +func (m ClientRequestDuration) RecordSet(ctx context.Context, val float64, set attribute.Set) { + if set.Len() == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Float64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ClientRequestDuration) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ClientRequestDuration) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ClientRequestDuration) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ClientRequestDuration) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientRequestDuration) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// AttrURLTemplate returns an optional attribute for the "url.template" semantic +// convention. It represents the low-cardinality template of an +// [absolute path reference]. +// +// [absolute path reference]: https://www.rfc-editor.org/rfc/rfc3986#section-4.2 +func (ClientRequestDuration) AttrURLTemplate(val string) attribute.KeyValue { + return attribute.String("url.template", val) +} + +// ClientResponseBodySize is an instrument used to record metric values +// conforming to the "http.client.response.body.size" semantic conventions. It +// represents the size of HTTP client response bodies. +type ClientResponseBodySize struct { + metric.Int64Histogram +} + +var newClientResponseBodySizeOpts = []metric.Int64HistogramOption{ + metric.WithDescription("Size of HTTP client response bodies."), + metric.WithUnit("By"), +} + +// NewClientResponseBodySize returns a new ClientResponseBodySize instrument. +func NewClientResponseBodySize( + m metric.Meter, + opt ...metric.Int64HistogramOption, +) (ClientResponseBodySize, error) { + // Check if the meter is nil. + if m == nil { + return ClientResponseBodySize{noop.Int64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newClientResponseBodySizeOpts + } else { + opt = append(opt, newClientResponseBodySizeOpts...) + } + + i, err := m.Int64Histogram( + "http.client.response.body.size", + opt..., + ) + if err != nil { + return ClientResponseBodySize{noop.Int64Histogram{}}, err + } + return ClientResponseBodySize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ClientResponseBodySize) Inst() metric.Int64Histogram { + return m.Int64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ClientResponseBodySize) Name() string { + return "http.client.response.body.size" +} + +// Unit returns the semantic convention unit of the instrument +func (ClientResponseBodySize) Unit() string { + return "By" +} + +// Description returns the semantic convention description of the instrument +func (ClientResponseBodySize) Description() string { + return "Size of HTTP client response bodies." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The serverAddress is the server domain name if available without reverse DNS +// lookup; otherwise, IP address or Unix domain socket name. +// +// The serverPort is the server port number. +// +// All additional attrs passed are included in the recorded value. +// +// The size of the response payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ClientResponseBodySize) Record( + ctx context.Context, + val int64, + requestMethod RequestMethodAttr, + serverAddress string, + serverPort int, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("server.address", serverAddress), + attribute.Int("server.port", serverPort), + )..., + ), + ) + + m.Int64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// The size of the response payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ClientResponseBodySize) RecordSet(ctx context.Context, val int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ClientResponseBodySize) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ClientResponseBodySize) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ClientResponseBodySize) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrURLTemplate returns an optional attribute for the "url.template" semantic +// convention. It represents the low-cardinality template of an +// [absolute path reference]. +// +// [absolute path reference]: https://www.rfc-editor.org/rfc/rfc3986#section-4.2 +func (ClientResponseBodySize) AttrURLTemplate(val string) attribute.KeyValue { + return attribute.String("url.template", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ClientResponseBodySize) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrURLScheme returns an optional attribute for the "url.scheme" semantic +// convention. It represents the [URI scheme] component identifying the used +// protocol. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (ClientResponseBodySize) AttrURLScheme(val string) attribute.KeyValue { + return attribute.String("url.scheme", val) +} + +// ServerActiveRequests is an instrument used to record metric values conforming +// to the "http.server.active_requests" semantic conventions. It represents the +// number of active HTTP server requests. +type ServerActiveRequests struct { + metric.Int64UpDownCounter +} + +var newServerActiveRequestsOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("Number of active HTTP server requests."), + metric.WithUnit("{request}"), +} + +// NewServerActiveRequests returns a new ServerActiveRequests instrument. +func NewServerActiveRequests( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (ServerActiveRequests, error) { + // Check if the meter is nil. + if m == nil { + return ServerActiveRequests{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newServerActiveRequestsOpts + } else { + opt = append(opt, newServerActiveRequestsOpts...) + } + + i, err := m.Int64UpDownCounter( + "http.server.active_requests", + opt..., + ) + if err != nil { + return ServerActiveRequests{noop.Int64UpDownCounter{}}, err + } + return ServerActiveRequests{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ServerActiveRequests) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (ServerActiveRequests) Name() string { + return "http.server.active_requests" +} + +// Unit returns the semantic convention unit of the instrument +func (ServerActiveRequests) Unit() string { + return "{request}" +} + +// Description returns the semantic convention description of the instrument +func (ServerActiveRequests) Description() string { + return "Number of active HTTP server requests." +} + +// Add adds incr to the existing count for attrs. +// +// The requestMethod is the HTTP request method. +// +// The urlScheme is the the [URI scheme] component identifying the used protocol. +// +// All additional attrs passed are included in the recorded value. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (m ServerActiveRequests) Add( + ctx context.Context, + incr int64, + requestMethod RequestMethodAttr, + urlScheme string, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("url.scheme", urlScheme), + )..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +func (m ServerActiveRequests) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the name of the local HTTP server that +// received the request. +func (ServerActiveRequests) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the port of the local HTTP server that received the +// request. +func (ServerActiveRequests) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// ServerRequestBodySize is an instrument used to record metric values conforming +// to the "http.server.request.body.size" semantic conventions. It represents the +// size of HTTP server request bodies. +type ServerRequestBodySize struct { + metric.Int64Histogram +} + +var newServerRequestBodySizeOpts = []metric.Int64HistogramOption{ + metric.WithDescription("Size of HTTP server request bodies."), + metric.WithUnit("By"), +} + +// NewServerRequestBodySize returns a new ServerRequestBodySize instrument. +func NewServerRequestBodySize( + m metric.Meter, + opt ...metric.Int64HistogramOption, +) (ServerRequestBodySize, error) { + // Check if the meter is nil. + if m == nil { + return ServerRequestBodySize{noop.Int64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newServerRequestBodySizeOpts + } else { + opt = append(opt, newServerRequestBodySizeOpts...) + } + + i, err := m.Int64Histogram( + "http.server.request.body.size", + opt..., + ) + if err != nil { + return ServerRequestBodySize{noop.Int64Histogram{}}, err + } + return ServerRequestBodySize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ServerRequestBodySize) Inst() metric.Int64Histogram { + return m.Int64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ServerRequestBodySize) Name() string { + return "http.server.request.body.size" +} + +// Unit returns the semantic convention unit of the instrument +func (ServerRequestBodySize) Unit() string { + return "By" +} + +// Description returns the semantic convention description of the instrument +func (ServerRequestBodySize) Description() string { + return "Size of HTTP server request bodies." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The urlScheme is the the [URI scheme] component identifying the used protocol. +// +// All additional attrs passed are included in the recorded value. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +// +// The size of the request payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ServerRequestBodySize) Record( + ctx context.Context, + val int64, + requestMethod RequestMethodAttr, + urlScheme string, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("url.scheme", urlScheme), + )..., + ), + ) + + m.Int64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// The size of the request payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ServerRequestBodySize) RecordSet(ctx context.Context, val int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ServerRequestBodySize) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ServerRequestBodySize) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrRoute returns an optional attribute for the "http.route" semantic +// convention. It represents the matched route, that is, the path template in the +// format used by the respective server framework. +func (ServerRequestBodySize) AttrRoute(val string) attribute.KeyValue { + return attribute.String("http.route", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ServerRequestBodySize) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ServerRequestBodySize) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the name of the local HTTP server that +// received the request. +func (ServerRequestBodySize) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the port of the local HTTP server that received the +// request. +func (ServerRequestBodySize) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// AttrUserAgentSyntheticType returns an optional attribute for the +// "user_agent.synthetic.type" semantic convention. It represents the specifies +// the category of synthetic traffic, such as tests or bots. +func (ServerRequestBodySize) AttrUserAgentSyntheticType(val UserAgentSyntheticTypeAttr) attribute.KeyValue { + return attribute.String("user_agent.synthetic.type", string(val)) +} + +// ServerRequestDuration is an instrument used to record metric values conforming +// to the "http.server.request.duration" semantic conventions. It represents the +// duration of HTTP server requests. +type ServerRequestDuration struct { + metric.Float64Histogram +} + +var newServerRequestDurationOpts = []metric.Float64HistogramOption{ + metric.WithDescription("Duration of HTTP server requests."), + metric.WithUnit("s"), +} + +// NewServerRequestDuration returns a new ServerRequestDuration instrument. +func NewServerRequestDuration( + m metric.Meter, + opt ...metric.Float64HistogramOption, +) (ServerRequestDuration, error) { + // Check if the meter is nil. + if m == nil { + return ServerRequestDuration{noop.Float64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newServerRequestDurationOpts + } else { + opt = append(opt, newServerRequestDurationOpts...) + } + + i, err := m.Float64Histogram( + "http.server.request.duration", + opt..., + ) + if err != nil { + return ServerRequestDuration{noop.Float64Histogram{}}, err + } + return ServerRequestDuration{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ServerRequestDuration) Inst() metric.Float64Histogram { + return m.Float64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ServerRequestDuration) Name() string { + return "http.server.request.duration" +} + +// Unit returns the semantic convention unit of the instrument +func (ServerRequestDuration) Unit() string { + return "s" +} + +// Description returns the semantic convention description of the instrument +func (ServerRequestDuration) Description() string { + return "Duration of HTTP server requests." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The urlScheme is the the [URI scheme] component identifying the used protocol. +// +// All additional attrs passed are included in the recorded value. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +func (m ServerRequestDuration) Record( + ctx context.Context, + val float64, + requestMethod RequestMethodAttr, + urlScheme string, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("url.scheme", urlScheme), + )..., + ), + ) + + m.Float64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +func (m ServerRequestDuration) RecordSet(ctx context.Context, val float64, set attribute.Set) { + if set.Len() == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Float64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ServerRequestDuration) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ServerRequestDuration) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrRoute returns an optional attribute for the "http.route" semantic +// convention. It represents the matched route, that is, the path template in the +// format used by the respective server framework. +func (ServerRequestDuration) AttrRoute(val string) attribute.KeyValue { + return attribute.String("http.route", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ServerRequestDuration) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ServerRequestDuration) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the name of the local HTTP server that +// received the request. +func (ServerRequestDuration) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the port of the local HTTP server that received the +// request. +func (ServerRequestDuration) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// AttrUserAgentSyntheticType returns an optional attribute for the +// "user_agent.synthetic.type" semantic convention. It represents the specifies +// the category of synthetic traffic, such as tests or bots. +func (ServerRequestDuration) AttrUserAgentSyntheticType(val UserAgentSyntheticTypeAttr) attribute.KeyValue { + return attribute.String("user_agent.synthetic.type", string(val)) +} + +// ServerResponseBodySize is an instrument used to record metric values +// conforming to the "http.server.response.body.size" semantic conventions. It +// represents the size of HTTP server response bodies. +type ServerResponseBodySize struct { + metric.Int64Histogram +} + +var newServerResponseBodySizeOpts = []metric.Int64HistogramOption{ + metric.WithDescription("Size of HTTP server response bodies."), + metric.WithUnit("By"), +} + +// NewServerResponseBodySize returns a new ServerResponseBodySize instrument. +func NewServerResponseBodySize( + m metric.Meter, + opt ...metric.Int64HistogramOption, +) (ServerResponseBodySize, error) { + // Check if the meter is nil. + if m == nil { + return ServerResponseBodySize{noop.Int64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newServerResponseBodySizeOpts + } else { + opt = append(opt, newServerResponseBodySizeOpts...) + } + + i, err := m.Int64Histogram( + "http.server.response.body.size", + opt..., + ) + if err != nil { + return ServerResponseBodySize{noop.Int64Histogram{}}, err + } + return ServerResponseBodySize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m ServerResponseBodySize) Inst() metric.Int64Histogram { + return m.Int64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (ServerResponseBodySize) Name() string { + return "http.server.response.body.size" +} + +// Unit returns the semantic convention unit of the instrument +func (ServerResponseBodySize) Unit() string { + return "By" +} + +// Description returns the semantic convention description of the instrument +func (ServerResponseBodySize) Description() string { + return "Size of HTTP server response bodies." +} + +// Record records val to the current distribution for attrs. +// +// The requestMethod is the HTTP request method. +// +// The urlScheme is the the [URI scheme] component identifying the used protocol. +// +// All additional attrs passed are included in the recorded value. +// +// [URI scheme]: https://www.rfc-editor.org/rfc/rfc3986#section-3.1 +// +// The size of the response payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ServerResponseBodySize) Record( + ctx context.Context, + val int64, + requestMethod RequestMethodAttr, + urlScheme string, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + append( + attrs, + attribute.String("http.request.method", string(requestMethod)), + attribute.String("url.scheme", urlScheme), + )..., + ), + ) + + m.Int64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// The size of the response payload body in bytes. This is the number of bytes +// transferred excluding headers and is often, but not always, present as the +// [Content-Length] header. For requests using transport encoding, this should be +// the compressed size. +// +// [Content-Length]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length +func (m ServerResponseBodySize) RecordSet(ctx context.Context, val int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (ServerResponseBodySize) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the +// [HTTP response status code]. +// +// [HTTP response status code]: https://tools.ietf.org/html/rfc7231#section-6 +func (ServerResponseBodySize) AttrResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrRoute returns an optional attribute for the "http.route" semantic +// convention. It represents the matched route, that is, the path template in the +// format used by the respective server framework. +func (ServerResponseBodySize) AttrRoute(val string) attribute.KeyValue { + return attribute.String("http.route", val) +} + +// AttrNetworkProtocolName returns an optional attribute for the +// "network.protocol.name" semantic convention. It represents the +// [OSI application layer] or non-OSI equivalent. +// +// [OSI application layer]: https://wikipedia.org/wiki/Application_layer +func (ServerResponseBodySize) AttrNetworkProtocolName(val string) attribute.KeyValue { + return attribute.String("network.protocol.name", val) +} + +// AttrNetworkProtocolVersion returns an optional attribute for the +// "network.protocol.version" semantic convention. It represents the actual +// version of the protocol used for network communication. +func (ServerResponseBodySize) AttrNetworkProtocolVersion(val string) attribute.KeyValue { + return attribute.String("network.protocol.version", val) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the name of the local HTTP server that +// received the request. +func (ServerResponseBodySize) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the port of the local HTTP server that received the +// request. +func (ServerResponseBodySize) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// AttrUserAgentSyntheticType returns an optional attribute for the +// "user_agent.synthetic.type" semantic convention. It represents the specifies +// the category of synthetic traffic, such as tests or bots. +func (ServerResponseBodySize) AttrUserAgentSyntheticType(val UserAgentSyntheticTypeAttr) attribute.KeyValue { + return attribute.String("user_agent.synthetic.type", string(val)) +} diff --git a/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go b/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go new file mode 100644 index 000000000..1fe600ad0 --- /dev/null +++ b/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go @@ -0,0 +1,173 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package secretbox encrypts and authenticates small messages. + +Secretbox uses XSalsa20 and Poly1305 to encrypt and authenticate messages with +secret-key cryptography. The length of messages is not hidden. + +It is the caller's responsibility to ensure the uniqueness of nonces—for +example, by using nonce 1 for the first message, nonce 2 for the second +message, etc. Nonces are long enough that randomly generated nonces have +negligible risk of collision. + +Messages should be small because: + +1. The whole message needs to be held in memory to be processed. + +2. Using large messages pressures implementations on small machines to decrypt +and process plaintext before authenticating it. This is very dangerous, and +this API does not allow it, but a protocol that uses excessive message sizes +might present some implementations with no other choice. + +3. Fixed overheads will be sufficiently amortised by messages as small as 8KB. + +4. Performance may be improved by working with messages that fit into data caches. + +Thus large amounts of data should be chunked so that each message is small. +(Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable +chunk size. + +This package is interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html. +*/ +package secretbox + +import ( + "golang.org/x/crypto/internal/alias" + "golang.org/x/crypto/internal/poly1305" + "golang.org/x/crypto/salsa20/salsa" +) + +// Overhead is the number of bytes of overhead when boxing a message. +const Overhead = poly1305.TagSize + +// setup produces a sub-key and Salsa20 counter given a nonce and key. +func setup(subKey *[32]byte, counter *[16]byte, nonce *[24]byte, key *[32]byte) { + // We use XSalsa20 for encryption so first we need to generate a + // key and nonce with HSalsa20. + var hNonce [16]byte + copy(hNonce[:], nonce[:]) + salsa.HSalsa20(subKey, &hNonce, key, &salsa.Sigma) + + // The final 8 bytes of the original nonce form the new nonce. + copy(counter[:], nonce[16:]) +} + +// sliceForAppend takes a slice and a requested number of bytes. It returns a +// slice with the contents of the given slice followed by that many bytes and a +// second slice that aliases into it and contains only the extra bytes. If the +// original slice has sufficient capacity then no allocation is performed. +func sliceForAppend(in []byte, n int) (head, tail []byte) { + if total := len(in) + n; cap(in) >= total { + head = in[:total] + } else { + head = make([]byte, total) + copy(head, in) + } + tail = head[len(in):] + return +} + +// Seal appends an encrypted and authenticated copy of message to out, which +// must not overlap message. The key and nonce pair must be unique for each +// distinct message and the output will be Overhead bytes longer than message. +func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte { + var subKey [32]byte + var counter [16]byte + setup(&subKey, &counter, nonce, key) + + // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since + // Salsa20 works with 64-byte blocks, we also generate 32 bytes of + // keystream as a side effect. + var firstBlock [64]byte + salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey) + + var poly1305Key [32]byte + copy(poly1305Key[:], firstBlock[:]) + + ret, out := sliceForAppend(out, len(message)+poly1305.TagSize) + if alias.AnyOverlap(out, message) { + panic("nacl: invalid buffer overlap") + } + + // We XOR up to 32 bytes of message with the keystream generated from + // the first block. + firstMessageBlock := message + if len(firstMessageBlock) > 32 { + firstMessageBlock = firstMessageBlock[:32] + } + + tagOut := out + out = out[poly1305.TagSize:] + for i, x := range firstMessageBlock { + out[i] = firstBlock[32+i] ^ x + } + message = message[len(firstMessageBlock):] + ciphertext := out + out = out[len(firstMessageBlock):] + + // Now encrypt the rest. + counter[8] = 1 + salsa.XORKeyStream(out, message, &counter, &subKey) + + var tag [poly1305.TagSize]byte + poly1305.Sum(&tag, ciphertext, &poly1305Key) + copy(tagOut, tag[:]) + + return ret +} + +// Open authenticates and decrypts a box produced by Seal and appends the +// message to out, which must not overlap box. The output will be Overhead +// bytes smaller than box. +func Open(out, box []byte, nonce *[24]byte, key *[32]byte) ([]byte, bool) { + if len(box) < Overhead { + return nil, false + } + + var subKey [32]byte + var counter [16]byte + setup(&subKey, &counter, nonce, key) + + // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since + // Salsa20 works with 64-byte blocks, we also generate 32 bytes of + // keystream as a side effect. + var firstBlock [64]byte + salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey) + + var poly1305Key [32]byte + copy(poly1305Key[:], firstBlock[:]) + var tag [poly1305.TagSize]byte + copy(tag[:], box) + + if !poly1305.Verify(&tag, box[poly1305.TagSize:], &poly1305Key) { + return nil, false + } + + ret, out := sliceForAppend(out, len(box)-Overhead) + if alias.AnyOverlap(out, box) { + panic("nacl: invalid buffer overlap") + } + + // We XOR up to 32 bytes of box with the keystream generated from + // the first block. + box = box[Overhead:] + firstMessageBlock := box + if len(firstMessageBlock) > 32 { + firstMessageBlock = firstMessageBlock[:32] + } + for i, x := range firstMessageBlock { + out[i] = firstBlock[32+i] ^ x + } + + box = box[len(firstMessageBlock):] + out = out[len(firstMessageBlock):] + + // Now decrypt the rest. + counter[8] = 1 + salsa.XORKeyStream(out, box, &counter, &subKey) + + return ret, true +} diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go b/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go new file mode 100644 index 000000000..75df77406 --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go @@ -0,0 +1,150 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package salsa provides low-level access to functions in the Salsa family. +// +// Deprecated: this package exposes unsafe low-level operations. New applications +// should consider using the AEAD construction in golang.org/x/crypto/chacha20poly1305 +// instead. Existing users should migrate to golang.org/x/crypto/salsa20. +package salsa + +import "math/bits" + +// Sigma is the Salsa20 constant for 256-bit keys. +var Sigma = [16]byte{'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k'} + +// HSalsa20 applies the HSalsa20 core function to a 16-byte input in, 32-byte +// key k, and 16-byte constant c, and puts the result into the 32-byte array +// out. +func HSalsa20(out *[32]byte, in *[16]byte, k *[32]byte, c *[16]byte) { + x0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24 + x1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24 + x2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24 + x3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24 + x4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24 + x5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24 + x6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 + x7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 + x8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 + x9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 + x10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24 + x11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24 + x12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24 + x13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24 + x14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24 + x15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24 + + for i := 0; i < 20; i += 2 { + u := x0 + x12 + x4 ^= bits.RotateLeft32(u, 7) + u = x4 + x0 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x4 + x12 ^= bits.RotateLeft32(u, 13) + u = x12 + x8 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x1 + x9 ^= bits.RotateLeft32(u, 7) + u = x9 + x5 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x9 + x1 ^= bits.RotateLeft32(u, 13) + u = x1 + x13 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x6 + x14 ^= bits.RotateLeft32(u, 7) + u = x14 + x10 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x14 + x6 ^= bits.RotateLeft32(u, 13) + u = x6 + x2 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x11 + x3 ^= bits.RotateLeft32(u, 7) + u = x3 + x15 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x3 + x11 ^= bits.RotateLeft32(u, 13) + u = x11 + x7 + x15 ^= bits.RotateLeft32(u, 18) + + u = x0 + x3 + x1 ^= bits.RotateLeft32(u, 7) + u = x1 + x0 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x1 + x3 ^= bits.RotateLeft32(u, 13) + u = x3 + x2 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x4 + x6 ^= bits.RotateLeft32(u, 7) + u = x6 + x5 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x6 + x4 ^= bits.RotateLeft32(u, 13) + u = x4 + x7 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x9 + x11 ^= bits.RotateLeft32(u, 7) + u = x11 + x10 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x11 + x9 ^= bits.RotateLeft32(u, 13) + u = x9 + x8 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x14 + x12 ^= bits.RotateLeft32(u, 7) + u = x12 + x15 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x12 + x14 ^= bits.RotateLeft32(u, 13) + u = x14 + x13 + x15 ^= bits.RotateLeft32(u, 18) + } + out[0] = byte(x0) + out[1] = byte(x0 >> 8) + out[2] = byte(x0 >> 16) + out[3] = byte(x0 >> 24) + + out[4] = byte(x5) + out[5] = byte(x5 >> 8) + out[6] = byte(x5 >> 16) + out[7] = byte(x5 >> 24) + + out[8] = byte(x10) + out[9] = byte(x10 >> 8) + out[10] = byte(x10 >> 16) + out[11] = byte(x10 >> 24) + + out[12] = byte(x15) + out[13] = byte(x15 >> 8) + out[14] = byte(x15 >> 16) + out[15] = byte(x15 >> 24) + + out[16] = byte(x6) + out[17] = byte(x6 >> 8) + out[18] = byte(x6 >> 16) + out[19] = byte(x6 >> 24) + + out[20] = byte(x7) + out[21] = byte(x7 >> 8) + out[22] = byte(x7 >> 16) + out[23] = byte(x7 >> 24) + + out[24] = byte(x8) + out[25] = byte(x8 >> 8) + out[26] = byte(x8 >> 16) + out[27] = byte(x8 >> 24) + + out[28] = byte(x9) + out[29] = byte(x9 >> 8) + out[30] = byte(x9 >> 16) + out[31] = byte(x9 >> 24) +} diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go new file mode 100644 index 000000000..7ec7bb39b --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go @@ -0,0 +1,201 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package salsa + +import "math/bits" + +// Core208 applies the Salsa20/8 core function to the 64-byte array in and puts +// the result into the 64-byte array out. The input and output may be the same array. +func Core208(out *[64]byte, in *[64]byte) { + j0 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 + j1 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 + j2 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 + j3 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 + j4 := uint32(in[16]) | uint32(in[17])<<8 | uint32(in[18])<<16 | uint32(in[19])<<24 + j5 := uint32(in[20]) | uint32(in[21])<<8 | uint32(in[22])<<16 | uint32(in[23])<<24 + j6 := uint32(in[24]) | uint32(in[25])<<8 | uint32(in[26])<<16 | uint32(in[27])<<24 + j7 := uint32(in[28]) | uint32(in[29])<<8 | uint32(in[30])<<16 | uint32(in[31])<<24 + j8 := uint32(in[32]) | uint32(in[33])<<8 | uint32(in[34])<<16 | uint32(in[35])<<24 + j9 := uint32(in[36]) | uint32(in[37])<<8 | uint32(in[38])<<16 | uint32(in[39])<<24 + j10 := uint32(in[40]) | uint32(in[41])<<8 | uint32(in[42])<<16 | uint32(in[43])<<24 + j11 := uint32(in[44]) | uint32(in[45])<<8 | uint32(in[46])<<16 | uint32(in[47])<<24 + j12 := uint32(in[48]) | uint32(in[49])<<8 | uint32(in[50])<<16 | uint32(in[51])<<24 + j13 := uint32(in[52]) | uint32(in[53])<<8 | uint32(in[54])<<16 | uint32(in[55])<<24 + j14 := uint32(in[56]) | uint32(in[57])<<8 | uint32(in[58])<<16 | uint32(in[59])<<24 + j15 := uint32(in[60]) | uint32(in[61])<<8 | uint32(in[62])<<16 | uint32(in[63])<<24 + + x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8 + x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15 + + for i := 0; i < 8; i += 2 { + u := x0 + x12 + x4 ^= bits.RotateLeft32(u, 7) + u = x4 + x0 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x4 + x12 ^= bits.RotateLeft32(u, 13) + u = x12 + x8 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x1 + x9 ^= bits.RotateLeft32(u, 7) + u = x9 + x5 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x9 + x1 ^= bits.RotateLeft32(u, 13) + u = x1 + x13 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x6 + x14 ^= bits.RotateLeft32(u, 7) + u = x14 + x10 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x14 + x6 ^= bits.RotateLeft32(u, 13) + u = x6 + x2 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x11 + x3 ^= bits.RotateLeft32(u, 7) + u = x3 + x15 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x3 + x11 ^= bits.RotateLeft32(u, 13) + u = x11 + x7 + x15 ^= bits.RotateLeft32(u, 18) + + u = x0 + x3 + x1 ^= bits.RotateLeft32(u, 7) + u = x1 + x0 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x1 + x3 ^= bits.RotateLeft32(u, 13) + u = x3 + x2 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x4 + x6 ^= bits.RotateLeft32(u, 7) + u = x6 + x5 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x6 + x4 ^= bits.RotateLeft32(u, 13) + u = x4 + x7 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x9 + x11 ^= bits.RotateLeft32(u, 7) + u = x11 + x10 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x11 + x9 ^= bits.RotateLeft32(u, 13) + u = x9 + x8 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x14 + x12 ^= bits.RotateLeft32(u, 7) + u = x12 + x15 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x12 + x14 ^= bits.RotateLeft32(u, 13) + u = x14 + x13 + x15 ^= bits.RotateLeft32(u, 18) + } + x0 += j0 + x1 += j1 + x2 += j2 + x3 += j3 + x4 += j4 + x5 += j5 + x6 += j6 + x7 += j7 + x8 += j8 + x9 += j9 + x10 += j10 + x11 += j11 + x12 += j12 + x13 += j13 + x14 += j14 + x15 += j15 + + out[0] = byte(x0) + out[1] = byte(x0 >> 8) + out[2] = byte(x0 >> 16) + out[3] = byte(x0 >> 24) + + out[4] = byte(x1) + out[5] = byte(x1 >> 8) + out[6] = byte(x1 >> 16) + out[7] = byte(x1 >> 24) + + out[8] = byte(x2) + out[9] = byte(x2 >> 8) + out[10] = byte(x2 >> 16) + out[11] = byte(x2 >> 24) + + out[12] = byte(x3) + out[13] = byte(x3 >> 8) + out[14] = byte(x3 >> 16) + out[15] = byte(x3 >> 24) + + out[16] = byte(x4) + out[17] = byte(x4 >> 8) + out[18] = byte(x4 >> 16) + out[19] = byte(x4 >> 24) + + out[20] = byte(x5) + out[21] = byte(x5 >> 8) + out[22] = byte(x5 >> 16) + out[23] = byte(x5 >> 24) + + out[24] = byte(x6) + out[25] = byte(x6 >> 8) + out[26] = byte(x6 >> 16) + out[27] = byte(x6 >> 24) + + out[28] = byte(x7) + out[29] = byte(x7 >> 8) + out[30] = byte(x7 >> 16) + out[31] = byte(x7 >> 24) + + out[32] = byte(x8) + out[33] = byte(x8 >> 8) + out[34] = byte(x8 >> 16) + out[35] = byte(x8 >> 24) + + out[36] = byte(x9) + out[37] = byte(x9 >> 8) + out[38] = byte(x9 >> 16) + out[39] = byte(x9 >> 24) + + out[40] = byte(x10) + out[41] = byte(x10 >> 8) + out[42] = byte(x10 >> 16) + out[43] = byte(x10 >> 24) + + out[44] = byte(x11) + out[45] = byte(x11 >> 8) + out[46] = byte(x11 >> 16) + out[47] = byte(x11 >> 24) + + out[48] = byte(x12) + out[49] = byte(x12 >> 8) + out[50] = byte(x12 >> 16) + out[51] = byte(x12 >> 24) + + out[52] = byte(x13) + out[53] = byte(x13 >> 8) + out[54] = byte(x13 >> 16) + out[55] = byte(x13 >> 24) + + out[56] = byte(x14) + out[57] = byte(x14 >> 8) + out[58] = byte(x14 >> 16) + out[59] = byte(x14 >> 24) + + out[60] = byte(x15) + out[61] = byte(x15 >> 8) + out[62] = byte(x15 >> 16) + out[63] = byte(x15 >> 24) +} diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go new file mode 100644 index 000000000..e76b44fe5 --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go @@ -0,0 +1,23 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build amd64 && !purego && gc + +package salsa + +//go:noescape + +// salsa2020XORKeyStream is implemented in salsa20_amd64.s. +func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte) + +// XORKeyStream crypts bytes from in to out using the given key and counters. +// In and out must overlap entirely or not at all. Counter +// contains the raw salsa20 counter bytes (both nonce and block counter). +func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { + if len(in) == 0 { + return + } + _ = out[len(in)-1] + salsa2020XORKeyStream(&out[0], &in[0], uint64(len(in)), &counter[0], &key[0]) +} diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s new file mode 100644 index 000000000..3883e0ec2 --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s @@ -0,0 +1,880 @@ +// Code generated by command: go run salsa20_amd64_asm.go -out ../salsa20_amd64.s -pkg salsa. DO NOT EDIT. + +//go:build amd64 && !purego && gc + +// func salsa2020XORKeyStream(out *byte, in *byte, n uint64, nonce *byte, key *byte) +// Requires: SSE2 +TEXT ·salsa2020XORKeyStream(SB), $456-40 + // This needs up to 64 bytes at 360(R12); hence the non-obvious frame size. + MOVQ out+0(FP), DI + MOVQ in+8(FP), SI + MOVQ n+16(FP), DX + MOVQ nonce+24(FP), CX + MOVQ key+32(FP), R8 + MOVQ SP, R12 + ADDQ $0x1f, R12 + ANDQ $-32, R12 + MOVQ DX, R9 + MOVQ CX, DX + MOVQ R8, R10 + CMPQ R9, $0x00 + JBE DONE + MOVL 20(R10), CX + MOVL (R10), R8 + MOVL (DX), AX + MOVL 16(R10), R11 + MOVL CX, (R12) + MOVL R8, 4(R12) + MOVL AX, 8(R12) + MOVL R11, 12(R12) + MOVL 8(DX), CX + MOVL 24(R10), R8 + MOVL 4(R10), AX + MOVL 4(DX), R11 + MOVL CX, 16(R12) + MOVL R8, 20(R12) + MOVL AX, 24(R12) + MOVL R11, 28(R12) + MOVL 12(DX), CX + MOVL 12(R10), DX + MOVL 28(R10), R8 + MOVL 8(R10), AX + MOVL DX, 32(R12) + MOVL CX, 36(R12) + MOVL R8, 40(R12) + MOVL AX, 44(R12) + MOVQ $0x61707865, DX + MOVQ $0x3320646e, CX + MOVQ $0x79622d32, R8 + MOVQ $0x6b206574, AX + MOVL DX, 48(R12) + MOVL CX, 52(R12) + MOVL R8, 56(R12) + MOVL AX, 60(R12) + CMPQ R9, $0x00000100 + JB BYTESBETWEEN1AND255 + MOVOA 48(R12), X0 + PSHUFL $0x55, X0, X1 + PSHUFL $0xaa, X0, X2 + PSHUFL $0xff, X0, X3 + PSHUFL $0x00, X0, X0 + MOVOA X1, 64(R12) + MOVOA X2, 80(R12) + MOVOA X3, 96(R12) + MOVOA X0, 112(R12) + MOVOA (R12), X0 + PSHUFL $0xaa, X0, X1 + PSHUFL $0xff, X0, X2 + PSHUFL $0x00, X0, X3 + PSHUFL $0x55, X0, X0 + MOVOA X1, 128(R12) + MOVOA X2, 144(R12) + MOVOA X3, 160(R12) + MOVOA X0, 176(R12) + MOVOA 16(R12), X0 + PSHUFL $0xff, X0, X1 + PSHUFL $0x55, X0, X2 + PSHUFL $0xaa, X0, X0 + MOVOA X1, 192(R12) + MOVOA X2, 208(R12) + MOVOA X0, 224(R12) + MOVOA 32(R12), X0 + PSHUFL $0x00, X0, X1 + PSHUFL $0xaa, X0, X2 + PSHUFL $0xff, X0, X0 + MOVOA X1, 240(R12) + MOVOA X2, 256(R12) + MOVOA X0, 272(R12) + +BYTESATLEAST256: + MOVL 16(R12), DX + MOVL 36(R12), CX + MOVL DX, 288(R12) + MOVL CX, 304(R12) + SHLQ $0x20, CX + ADDQ CX, DX + ADDQ $0x01, DX + MOVQ DX, CX + SHRQ $0x20, CX + MOVL DX, 292(R12) + MOVL CX, 308(R12) + ADDQ $0x01, DX + MOVQ DX, CX + SHRQ $0x20, CX + MOVL DX, 296(R12) + MOVL CX, 312(R12) + ADDQ $0x01, DX + MOVQ DX, CX + SHRQ $0x20, CX + MOVL DX, 300(R12) + MOVL CX, 316(R12) + ADDQ $0x01, DX + MOVQ DX, CX + SHRQ $0x20, CX + MOVL DX, 16(R12) + MOVL CX, 36(R12) + MOVQ R9, 352(R12) + MOVQ $0x00000014, DX + MOVOA 64(R12), X0 + MOVOA 80(R12), X1 + MOVOA 96(R12), X2 + MOVOA 256(R12), X3 + MOVOA 272(R12), X4 + MOVOA 128(R12), X5 + MOVOA 144(R12), X6 + MOVOA 176(R12), X7 + MOVOA 192(R12), X8 + MOVOA 208(R12), X9 + MOVOA 224(R12), X10 + MOVOA 304(R12), X11 + MOVOA 112(R12), X12 + MOVOA 160(R12), X13 + MOVOA 240(R12), X14 + MOVOA 288(R12), X15 + +MAINLOOP1: + MOVOA X1, 320(R12) + MOVOA X2, 336(R12) + MOVOA X13, X1 + PADDL X12, X1 + MOVOA X1, X2 + PSLLL $0x07, X1 + PXOR X1, X14 + PSRLL $0x19, X2 + PXOR X2, X14 + MOVOA X7, X1 + PADDL X0, X1 + MOVOA X1, X2 + PSLLL $0x07, X1 + PXOR X1, X11 + PSRLL $0x19, X2 + PXOR X2, X11 + MOVOA X12, X1 + PADDL X14, X1 + MOVOA X1, X2 + PSLLL $0x09, X1 + PXOR X1, X15 + PSRLL $0x17, X2 + PXOR X2, X15 + MOVOA X0, X1 + PADDL X11, X1 + MOVOA X1, X2 + PSLLL $0x09, X1 + PXOR X1, X9 + PSRLL $0x17, X2 + PXOR X2, X9 + MOVOA X14, X1 + PADDL X15, X1 + MOVOA X1, X2 + PSLLL $0x0d, X1 + PXOR X1, X13 + PSRLL $0x13, X2 + PXOR X2, X13 + MOVOA X11, X1 + PADDL X9, X1 + MOVOA X1, X2 + PSLLL $0x0d, X1 + PXOR X1, X7 + PSRLL $0x13, X2 + PXOR X2, X7 + MOVOA X15, X1 + PADDL X13, X1 + MOVOA X1, X2 + PSLLL $0x12, X1 + PXOR X1, X12 + PSRLL $0x0e, X2 + PXOR X2, X12 + MOVOA 320(R12), X1 + MOVOA X12, 320(R12) + MOVOA X9, X2 + PADDL X7, X2 + MOVOA X2, X12 + PSLLL $0x12, X2 + PXOR X2, X0 + PSRLL $0x0e, X12 + PXOR X12, X0 + MOVOA X5, X2 + PADDL X1, X2 + MOVOA X2, X12 + PSLLL $0x07, X2 + PXOR X2, X3 + PSRLL $0x19, X12 + PXOR X12, X3 + MOVOA 336(R12), X2 + MOVOA X0, 336(R12) + MOVOA X6, X0 + PADDL X2, X0 + MOVOA X0, X12 + PSLLL $0x07, X0 + PXOR X0, X4 + PSRLL $0x19, X12 + PXOR X12, X4 + MOVOA X1, X0 + PADDL X3, X0 + MOVOA X0, X12 + PSLLL $0x09, X0 + PXOR X0, X10 + PSRLL $0x17, X12 + PXOR X12, X10 + MOVOA X2, X0 + PADDL X4, X0 + MOVOA X0, X12 + PSLLL $0x09, X0 + PXOR X0, X8 + PSRLL $0x17, X12 + PXOR X12, X8 + MOVOA X3, X0 + PADDL X10, X0 + MOVOA X0, X12 + PSLLL $0x0d, X0 + PXOR X0, X5 + PSRLL $0x13, X12 + PXOR X12, X5 + MOVOA X4, X0 + PADDL X8, X0 + MOVOA X0, X12 + PSLLL $0x0d, X0 + PXOR X0, X6 + PSRLL $0x13, X12 + PXOR X12, X6 + MOVOA X10, X0 + PADDL X5, X0 + MOVOA X0, X12 + PSLLL $0x12, X0 + PXOR X0, X1 + PSRLL $0x0e, X12 + PXOR X12, X1 + MOVOA 320(R12), X0 + MOVOA X1, 320(R12) + MOVOA X4, X1 + PADDL X0, X1 + MOVOA X1, X12 + PSLLL $0x07, X1 + PXOR X1, X7 + PSRLL $0x19, X12 + PXOR X12, X7 + MOVOA X8, X1 + PADDL X6, X1 + MOVOA X1, X12 + PSLLL $0x12, X1 + PXOR X1, X2 + PSRLL $0x0e, X12 + PXOR X12, X2 + MOVOA 336(R12), X12 + MOVOA X2, 336(R12) + MOVOA X14, X1 + PADDL X12, X1 + MOVOA X1, X2 + PSLLL $0x07, X1 + PXOR X1, X5 + PSRLL $0x19, X2 + PXOR X2, X5 + MOVOA X0, X1 + PADDL X7, X1 + MOVOA X1, X2 + PSLLL $0x09, X1 + PXOR X1, X10 + PSRLL $0x17, X2 + PXOR X2, X10 + MOVOA X12, X1 + PADDL X5, X1 + MOVOA X1, X2 + PSLLL $0x09, X1 + PXOR X1, X8 + PSRLL $0x17, X2 + PXOR X2, X8 + MOVOA X7, X1 + PADDL X10, X1 + MOVOA X1, X2 + PSLLL $0x0d, X1 + PXOR X1, X4 + PSRLL $0x13, X2 + PXOR X2, X4 + MOVOA X5, X1 + PADDL X8, X1 + MOVOA X1, X2 + PSLLL $0x0d, X1 + PXOR X1, X14 + PSRLL $0x13, X2 + PXOR X2, X14 + MOVOA X10, X1 + PADDL X4, X1 + MOVOA X1, X2 + PSLLL $0x12, X1 + PXOR X1, X0 + PSRLL $0x0e, X2 + PXOR X2, X0 + MOVOA 320(R12), X1 + MOVOA X0, 320(R12) + MOVOA X8, X0 + PADDL X14, X0 + MOVOA X0, X2 + PSLLL $0x12, X0 + PXOR X0, X12 + PSRLL $0x0e, X2 + PXOR X2, X12 + MOVOA X11, X0 + PADDL X1, X0 + MOVOA X0, X2 + PSLLL $0x07, X0 + PXOR X0, X6 + PSRLL $0x19, X2 + PXOR X2, X6 + MOVOA 336(R12), X2 + MOVOA X12, 336(R12) + MOVOA X3, X0 + PADDL X2, X0 + MOVOA X0, X12 + PSLLL $0x07, X0 + PXOR X0, X13 + PSRLL $0x19, X12 + PXOR X12, X13 + MOVOA X1, X0 + PADDL X6, X0 + MOVOA X0, X12 + PSLLL $0x09, X0 + PXOR X0, X15 + PSRLL $0x17, X12 + PXOR X12, X15 + MOVOA X2, X0 + PADDL X13, X0 + MOVOA X0, X12 + PSLLL $0x09, X0 + PXOR X0, X9 + PSRLL $0x17, X12 + PXOR X12, X9 + MOVOA X6, X0 + PADDL X15, X0 + MOVOA X0, X12 + PSLLL $0x0d, X0 + PXOR X0, X11 + PSRLL $0x13, X12 + PXOR X12, X11 + MOVOA X13, X0 + PADDL X9, X0 + MOVOA X0, X12 + PSLLL $0x0d, X0 + PXOR X0, X3 + PSRLL $0x13, X12 + PXOR X12, X3 + MOVOA X15, X0 + PADDL X11, X0 + MOVOA X0, X12 + PSLLL $0x12, X0 + PXOR X0, X1 + PSRLL $0x0e, X12 + PXOR X12, X1 + MOVOA X9, X0 + PADDL X3, X0 + MOVOA X0, X12 + PSLLL $0x12, X0 + PXOR X0, X2 + PSRLL $0x0e, X12 + PXOR X12, X2 + MOVOA 320(R12), X12 + MOVOA 336(R12), X0 + SUBQ $0x02, DX + JA MAINLOOP1 + PADDL 112(R12), X12 + PADDL 176(R12), X7 + PADDL 224(R12), X10 + PADDL 272(R12), X4 + MOVD X12, DX + MOVD X7, CX + MOVD X10, R8 + MOVD X4, R9 + PSHUFL $0x39, X12, X12 + PSHUFL $0x39, X7, X7 + PSHUFL $0x39, X10, X10 + PSHUFL $0x39, X4, X4 + XORL (SI), DX + XORL 4(SI), CX + XORL 8(SI), R8 + XORL 12(SI), R9 + MOVL DX, (DI) + MOVL CX, 4(DI) + MOVL R8, 8(DI) + MOVL R9, 12(DI) + MOVD X12, DX + MOVD X7, CX + MOVD X10, R8 + MOVD X4, R9 + PSHUFL $0x39, X12, X12 + PSHUFL $0x39, X7, X7 + PSHUFL $0x39, X10, X10 + PSHUFL $0x39, X4, X4 + XORL 64(SI), DX + XORL 68(SI), CX + XORL 72(SI), R8 + XORL 76(SI), R9 + MOVL DX, 64(DI) + MOVL CX, 68(DI) + MOVL R8, 72(DI) + MOVL R9, 76(DI) + MOVD X12, DX + MOVD X7, CX + MOVD X10, R8 + MOVD X4, R9 + PSHUFL $0x39, X12, X12 + PSHUFL $0x39, X7, X7 + PSHUFL $0x39, X10, X10 + PSHUFL $0x39, X4, X4 + XORL 128(SI), DX + XORL 132(SI), CX + XORL 136(SI), R8 + XORL 140(SI), R9 + MOVL DX, 128(DI) + MOVL CX, 132(DI) + MOVL R8, 136(DI) + MOVL R9, 140(DI) + MOVD X12, DX + MOVD X7, CX + MOVD X10, R8 + MOVD X4, R9 + XORL 192(SI), DX + XORL 196(SI), CX + XORL 200(SI), R8 + XORL 204(SI), R9 + MOVL DX, 192(DI) + MOVL CX, 196(DI) + MOVL R8, 200(DI) + MOVL R9, 204(DI) + PADDL 240(R12), X14 + PADDL 64(R12), X0 + PADDL 128(R12), X5 + PADDL 192(R12), X8 + MOVD X14, DX + MOVD X0, CX + MOVD X5, R8 + MOVD X8, R9 + PSHUFL $0x39, X14, X14 + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X5, X5 + PSHUFL $0x39, X8, X8 + XORL 16(SI), DX + XORL 20(SI), CX + XORL 24(SI), R8 + XORL 28(SI), R9 + MOVL DX, 16(DI) + MOVL CX, 20(DI) + MOVL R8, 24(DI) + MOVL R9, 28(DI) + MOVD X14, DX + MOVD X0, CX + MOVD X5, R8 + MOVD X8, R9 + PSHUFL $0x39, X14, X14 + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X5, X5 + PSHUFL $0x39, X8, X8 + XORL 80(SI), DX + XORL 84(SI), CX + XORL 88(SI), R8 + XORL 92(SI), R9 + MOVL DX, 80(DI) + MOVL CX, 84(DI) + MOVL R8, 88(DI) + MOVL R9, 92(DI) + MOVD X14, DX + MOVD X0, CX + MOVD X5, R8 + MOVD X8, R9 + PSHUFL $0x39, X14, X14 + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X5, X5 + PSHUFL $0x39, X8, X8 + XORL 144(SI), DX + XORL 148(SI), CX + XORL 152(SI), R8 + XORL 156(SI), R9 + MOVL DX, 144(DI) + MOVL CX, 148(DI) + MOVL R8, 152(DI) + MOVL R9, 156(DI) + MOVD X14, DX + MOVD X0, CX + MOVD X5, R8 + MOVD X8, R9 + XORL 208(SI), DX + XORL 212(SI), CX + XORL 216(SI), R8 + XORL 220(SI), R9 + MOVL DX, 208(DI) + MOVL CX, 212(DI) + MOVL R8, 216(DI) + MOVL R9, 220(DI) + PADDL 288(R12), X15 + PADDL 304(R12), X11 + PADDL 80(R12), X1 + PADDL 144(R12), X6 + MOVD X15, DX + MOVD X11, CX + MOVD X1, R8 + MOVD X6, R9 + PSHUFL $0x39, X15, X15 + PSHUFL $0x39, X11, X11 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X6, X6 + XORL 32(SI), DX + XORL 36(SI), CX + XORL 40(SI), R8 + XORL 44(SI), R9 + MOVL DX, 32(DI) + MOVL CX, 36(DI) + MOVL R8, 40(DI) + MOVL R9, 44(DI) + MOVD X15, DX + MOVD X11, CX + MOVD X1, R8 + MOVD X6, R9 + PSHUFL $0x39, X15, X15 + PSHUFL $0x39, X11, X11 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X6, X6 + XORL 96(SI), DX + XORL 100(SI), CX + XORL 104(SI), R8 + XORL 108(SI), R9 + MOVL DX, 96(DI) + MOVL CX, 100(DI) + MOVL R8, 104(DI) + MOVL R9, 108(DI) + MOVD X15, DX + MOVD X11, CX + MOVD X1, R8 + MOVD X6, R9 + PSHUFL $0x39, X15, X15 + PSHUFL $0x39, X11, X11 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X6, X6 + XORL 160(SI), DX + XORL 164(SI), CX + XORL 168(SI), R8 + XORL 172(SI), R9 + MOVL DX, 160(DI) + MOVL CX, 164(DI) + MOVL R8, 168(DI) + MOVL R9, 172(DI) + MOVD X15, DX + MOVD X11, CX + MOVD X1, R8 + MOVD X6, R9 + XORL 224(SI), DX + XORL 228(SI), CX + XORL 232(SI), R8 + XORL 236(SI), R9 + MOVL DX, 224(DI) + MOVL CX, 228(DI) + MOVL R8, 232(DI) + MOVL R9, 236(DI) + PADDL 160(R12), X13 + PADDL 208(R12), X9 + PADDL 256(R12), X3 + PADDL 96(R12), X2 + MOVD X13, DX + MOVD X9, CX + MOVD X3, R8 + MOVD X2, R9 + PSHUFL $0x39, X13, X13 + PSHUFL $0x39, X9, X9 + PSHUFL $0x39, X3, X3 + PSHUFL $0x39, X2, X2 + XORL 48(SI), DX + XORL 52(SI), CX + XORL 56(SI), R8 + XORL 60(SI), R9 + MOVL DX, 48(DI) + MOVL CX, 52(DI) + MOVL R8, 56(DI) + MOVL R9, 60(DI) + MOVD X13, DX + MOVD X9, CX + MOVD X3, R8 + MOVD X2, R9 + PSHUFL $0x39, X13, X13 + PSHUFL $0x39, X9, X9 + PSHUFL $0x39, X3, X3 + PSHUFL $0x39, X2, X2 + XORL 112(SI), DX + XORL 116(SI), CX + XORL 120(SI), R8 + XORL 124(SI), R9 + MOVL DX, 112(DI) + MOVL CX, 116(DI) + MOVL R8, 120(DI) + MOVL R9, 124(DI) + MOVD X13, DX + MOVD X9, CX + MOVD X3, R8 + MOVD X2, R9 + PSHUFL $0x39, X13, X13 + PSHUFL $0x39, X9, X9 + PSHUFL $0x39, X3, X3 + PSHUFL $0x39, X2, X2 + XORL 176(SI), DX + XORL 180(SI), CX + XORL 184(SI), R8 + XORL 188(SI), R9 + MOVL DX, 176(DI) + MOVL CX, 180(DI) + MOVL R8, 184(DI) + MOVL R9, 188(DI) + MOVD X13, DX + MOVD X9, CX + MOVD X3, R8 + MOVD X2, R9 + XORL 240(SI), DX + XORL 244(SI), CX + XORL 248(SI), R8 + XORL 252(SI), R9 + MOVL DX, 240(DI) + MOVL CX, 244(DI) + MOVL R8, 248(DI) + MOVL R9, 252(DI) + MOVQ 352(R12), R9 + SUBQ $0x00000100, R9 + ADDQ $0x00000100, SI + ADDQ $0x00000100, DI + CMPQ R9, $0x00000100 + JAE BYTESATLEAST256 + CMPQ R9, $0x00 + JBE DONE + +BYTESBETWEEN1AND255: + CMPQ R9, $0x40 + JAE NOCOPY + MOVQ DI, DX + LEAQ 360(R12), DI + MOVQ R9, CX + REP; MOVSB + LEAQ 360(R12), DI + LEAQ 360(R12), SI + +NOCOPY: + MOVQ R9, 352(R12) + MOVOA 48(R12), X0 + MOVOA (R12), X1 + MOVOA 16(R12), X2 + MOVOA 32(R12), X3 + MOVOA X1, X4 + MOVQ $0x00000014, CX + +MAINLOOP2: + PADDL X0, X4 + MOVOA X0, X5 + MOVOA X4, X6 + PSLLL $0x07, X4 + PSRLL $0x19, X6 + PXOR X4, X3 + PXOR X6, X3 + PADDL X3, X5 + MOVOA X3, X4 + MOVOA X5, X6 + PSLLL $0x09, X5 + PSRLL $0x17, X6 + PXOR X5, X2 + PSHUFL $0x93, X3, X3 + PXOR X6, X2 + PADDL X2, X4 + MOVOA X2, X5 + MOVOA X4, X6 + PSLLL $0x0d, X4 + PSRLL $0x13, X6 + PXOR X4, X1 + PSHUFL $0x4e, X2, X2 + PXOR X6, X1 + PADDL X1, X5 + MOVOA X3, X4 + MOVOA X5, X6 + PSLLL $0x12, X5 + PSRLL $0x0e, X6 + PXOR X5, X0 + PSHUFL $0x39, X1, X1 + PXOR X6, X0 + PADDL X0, X4 + MOVOA X0, X5 + MOVOA X4, X6 + PSLLL $0x07, X4 + PSRLL $0x19, X6 + PXOR X4, X1 + PXOR X6, X1 + PADDL X1, X5 + MOVOA X1, X4 + MOVOA X5, X6 + PSLLL $0x09, X5 + PSRLL $0x17, X6 + PXOR X5, X2 + PSHUFL $0x93, X1, X1 + PXOR X6, X2 + PADDL X2, X4 + MOVOA X2, X5 + MOVOA X4, X6 + PSLLL $0x0d, X4 + PSRLL $0x13, X6 + PXOR X4, X3 + PSHUFL $0x4e, X2, X2 + PXOR X6, X3 + PADDL X3, X5 + MOVOA X1, X4 + MOVOA X5, X6 + PSLLL $0x12, X5 + PSRLL $0x0e, X6 + PXOR X5, X0 + PSHUFL $0x39, X3, X3 + PXOR X6, X0 + PADDL X0, X4 + MOVOA X0, X5 + MOVOA X4, X6 + PSLLL $0x07, X4 + PSRLL $0x19, X6 + PXOR X4, X3 + PXOR X6, X3 + PADDL X3, X5 + MOVOA X3, X4 + MOVOA X5, X6 + PSLLL $0x09, X5 + PSRLL $0x17, X6 + PXOR X5, X2 + PSHUFL $0x93, X3, X3 + PXOR X6, X2 + PADDL X2, X4 + MOVOA X2, X5 + MOVOA X4, X6 + PSLLL $0x0d, X4 + PSRLL $0x13, X6 + PXOR X4, X1 + PSHUFL $0x4e, X2, X2 + PXOR X6, X1 + PADDL X1, X5 + MOVOA X3, X4 + MOVOA X5, X6 + PSLLL $0x12, X5 + PSRLL $0x0e, X6 + PXOR X5, X0 + PSHUFL $0x39, X1, X1 + PXOR X6, X0 + PADDL X0, X4 + MOVOA X0, X5 + MOVOA X4, X6 + PSLLL $0x07, X4 + PSRLL $0x19, X6 + PXOR X4, X1 + PXOR X6, X1 + PADDL X1, X5 + MOVOA X1, X4 + MOVOA X5, X6 + PSLLL $0x09, X5 + PSRLL $0x17, X6 + PXOR X5, X2 + PSHUFL $0x93, X1, X1 + PXOR X6, X2 + PADDL X2, X4 + MOVOA X2, X5 + MOVOA X4, X6 + PSLLL $0x0d, X4 + PSRLL $0x13, X6 + PXOR X4, X3 + PSHUFL $0x4e, X2, X2 + PXOR X6, X3 + SUBQ $0x04, CX + PADDL X3, X5 + MOVOA X1, X4 + MOVOA X5, X6 + PSLLL $0x12, X5 + PXOR X7, X7 + PSRLL $0x0e, X6 + PXOR X5, X0 + PSHUFL $0x39, X3, X3 + PXOR X6, X0 + JA MAINLOOP2 + PADDL 48(R12), X0 + PADDL (R12), X1 + PADDL 16(R12), X2 + PADDL 32(R12), X3 + MOVD X0, CX + MOVD X1, R8 + MOVD X2, R9 + MOVD X3, AX + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X2, X2 + PSHUFL $0x39, X3, X3 + XORL (SI), CX + XORL 48(SI), R8 + XORL 32(SI), R9 + XORL 16(SI), AX + MOVL CX, (DI) + MOVL R8, 48(DI) + MOVL R9, 32(DI) + MOVL AX, 16(DI) + MOVD X0, CX + MOVD X1, R8 + MOVD X2, R9 + MOVD X3, AX + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X2, X2 + PSHUFL $0x39, X3, X3 + XORL 20(SI), CX + XORL 4(SI), R8 + XORL 52(SI), R9 + XORL 36(SI), AX + MOVL CX, 20(DI) + MOVL R8, 4(DI) + MOVL R9, 52(DI) + MOVL AX, 36(DI) + MOVD X0, CX + MOVD X1, R8 + MOVD X2, R9 + MOVD X3, AX + PSHUFL $0x39, X0, X0 + PSHUFL $0x39, X1, X1 + PSHUFL $0x39, X2, X2 + PSHUFL $0x39, X3, X3 + XORL 40(SI), CX + XORL 24(SI), R8 + XORL 8(SI), R9 + XORL 56(SI), AX + MOVL CX, 40(DI) + MOVL R8, 24(DI) + MOVL R9, 8(DI) + MOVL AX, 56(DI) + MOVD X0, CX + MOVD X1, R8 + MOVD X2, R9 + MOVD X3, AX + XORL 60(SI), CX + XORL 44(SI), R8 + XORL 28(SI), R9 + XORL 12(SI), AX + MOVL CX, 60(DI) + MOVL R8, 44(DI) + MOVL R9, 28(DI) + MOVL AX, 12(DI) + MOVQ 352(R12), R9 + MOVL 16(R12), CX + MOVL 36(R12), R8 + ADDQ $0x01, CX + SHLQ $0x20, R8 + ADDQ R8, CX + MOVQ CX, R8 + SHRQ $0x20, R8 + MOVL CX, 16(R12) + MOVL R8, 36(R12) + CMPQ R9, $0x40 + JA BYTESATLEAST65 + JAE BYTESATLEAST64 + MOVQ DI, SI + MOVQ DX, DI + MOVQ R9, CX + REP; MOVSB + +BYTESATLEAST64: +DONE: + RET + +BYTESATLEAST65: + SUBQ $0x40, R9 + ADDQ $0x40, DI + ADDQ $0x40, SI + JMP BYTESBETWEEN1AND255 diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go new file mode 100644 index 000000000..9448760f2 --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go @@ -0,0 +1,14 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !amd64 || purego || !gc + +package salsa + +// XORKeyStream crypts bytes from in to out using the given key and counters. +// In and out must overlap entirely or not at all. Counter +// contains the raw salsa20 counter bytes (both nonce and block counter). +func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { + genericXORKeyStream(out, in, counter, key) +} diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go new file mode 100644 index 000000000..e5cdb9a25 --- /dev/null +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go @@ -0,0 +1,233 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package salsa + +import "math/bits" + +const rounds = 20 + +// core applies the Salsa20 core function to 16-byte input in, 32-byte key k, +// and 16-byte constant c, and puts the result into 64-byte array out. +func core(out *[64]byte, in *[16]byte, k *[32]byte, c *[16]byte) { + j0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24 + j1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24 + j2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24 + j3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24 + j4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24 + j5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24 + j6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 + j7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 + j8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 + j9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 + j10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24 + j11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24 + j12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24 + j13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24 + j14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24 + j15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24 + + x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8 + x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15 + + for i := 0; i < rounds; i += 2 { + u := x0 + x12 + x4 ^= bits.RotateLeft32(u, 7) + u = x4 + x0 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x4 + x12 ^= bits.RotateLeft32(u, 13) + u = x12 + x8 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x1 + x9 ^= bits.RotateLeft32(u, 7) + u = x9 + x5 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x9 + x1 ^= bits.RotateLeft32(u, 13) + u = x1 + x13 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x6 + x14 ^= bits.RotateLeft32(u, 7) + u = x14 + x10 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x14 + x6 ^= bits.RotateLeft32(u, 13) + u = x6 + x2 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x11 + x3 ^= bits.RotateLeft32(u, 7) + u = x3 + x15 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x3 + x11 ^= bits.RotateLeft32(u, 13) + u = x11 + x7 + x15 ^= bits.RotateLeft32(u, 18) + + u = x0 + x3 + x1 ^= bits.RotateLeft32(u, 7) + u = x1 + x0 + x2 ^= bits.RotateLeft32(u, 9) + u = x2 + x1 + x3 ^= bits.RotateLeft32(u, 13) + u = x3 + x2 + x0 ^= bits.RotateLeft32(u, 18) + + u = x5 + x4 + x6 ^= bits.RotateLeft32(u, 7) + u = x6 + x5 + x7 ^= bits.RotateLeft32(u, 9) + u = x7 + x6 + x4 ^= bits.RotateLeft32(u, 13) + u = x4 + x7 + x5 ^= bits.RotateLeft32(u, 18) + + u = x10 + x9 + x11 ^= bits.RotateLeft32(u, 7) + u = x11 + x10 + x8 ^= bits.RotateLeft32(u, 9) + u = x8 + x11 + x9 ^= bits.RotateLeft32(u, 13) + u = x9 + x8 + x10 ^= bits.RotateLeft32(u, 18) + + u = x15 + x14 + x12 ^= bits.RotateLeft32(u, 7) + u = x12 + x15 + x13 ^= bits.RotateLeft32(u, 9) + u = x13 + x12 + x14 ^= bits.RotateLeft32(u, 13) + u = x14 + x13 + x15 ^= bits.RotateLeft32(u, 18) + } + x0 += j0 + x1 += j1 + x2 += j2 + x3 += j3 + x4 += j4 + x5 += j5 + x6 += j6 + x7 += j7 + x8 += j8 + x9 += j9 + x10 += j10 + x11 += j11 + x12 += j12 + x13 += j13 + x14 += j14 + x15 += j15 + + out[0] = byte(x0) + out[1] = byte(x0 >> 8) + out[2] = byte(x0 >> 16) + out[3] = byte(x0 >> 24) + + out[4] = byte(x1) + out[5] = byte(x1 >> 8) + out[6] = byte(x1 >> 16) + out[7] = byte(x1 >> 24) + + out[8] = byte(x2) + out[9] = byte(x2 >> 8) + out[10] = byte(x2 >> 16) + out[11] = byte(x2 >> 24) + + out[12] = byte(x3) + out[13] = byte(x3 >> 8) + out[14] = byte(x3 >> 16) + out[15] = byte(x3 >> 24) + + out[16] = byte(x4) + out[17] = byte(x4 >> 8) + out[18] = byte(x4 >> 16) + out[19] = byte(x4 >> 24) + + out[20] = byte(x5) + out[21] = byte(x5 >> 8) + out[22] = byte(x5 >> 16) + out[23] = byte(x5 >> 24) + + out[24] = byte(x6) + out[25] = byte(x6 >> 8) + out[26] = byte(x6 >> 16) + out[27] = byte(x6 >> 24) + + out[28] = byte(x7) + out[29] = byte(x7 >> 8) + out[30] = byte(x7 >> 16) + out[31] = byte(x7 >> 24) + + out[32] = byte(x8) + out[33] = byte(x8 >> 8) + out[34] = byte(x8 >> 16) + out[35] = byte(x8 >> 24) + + out[36] = byte(x9) + out[37] = byte(x9 >> 8) + out[38] = byte(x9 >> 16) + out[39] = byte(x9 >> 24) + + out[40] = byte(x10) + out[41] = byte(x10 >> 8) + out[42] = byte(x10 >> 16) + out[43] = byte(x10 >> 24) + + out[44] = byte(x11) + out[45] = byte(x11 >> 8) + out[46] = byte(x11 >> 16) + out[47] = byte(x11 >> 24) + + out[48] = byte(x12) + out[49] = byte(x12 >> 8) + out[50] = byte(x12 >> 16) + out[51] = byte(x12 >> 24) + + out[52] = byte(x13) + out[53] = byte(x13 >> 8) + out[54] = byte(x13 >> 16) + out[55] = byte(x13 >> 24) + + out[56] = byte(x14) + out[57] = byte(x14 >> 8) + out[58] = byte(x14 >> 16) + out[59] = byte(x14 >> 24) + + out[60] = byte(x15) + out[61] = byte(x15 >> 8) + out[62] = byte(x15 >> 16) + out[63] = byte(x15 >> 24) +} + +// genericXORKeyStream is the generic implementation of XORKeyStream to be used +// when no assembly implementation is available. +func genericXORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { + var block [64]byte + var counterCopy [16]byte + copy(counterCopy[:], counter[:]) + + for len(in) >= 64 { + core(&block, &counterCopy, key, &Sigma) + for i, x := range block { + out[i] = in[i] ^ x + } + u := uint32(1) + for i := 8; i < 16; i++ { + u += uint32(counterCopy[i]) + counterCopy[i] = byte(u) + u >>= 8 + } + in = in[64:] + out = out[64:] + } + + if len(in) > 0 { + core(&block, &counterCopy, key, &Sigma) + for i, v := range in { + out[i] = v ^ block[i] + } + } +} diff --git a/vendor/golang.org/x/sync/errgroup/errgroup.go b/vendor/golang.org/x/sync/errgroup/errgroup.go new file mode 100644 index 000000000..f69fd7546 --- /dev/null +++ b/vendor/golang.org/x/sync/errgroup/errgroup.go @@ -0,0 +1,151 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package errgroup provides synchronization, error propagation, and Context +// cancellation for groups of goroutines working on subtasks of a common task. +// +// [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks +// returning errors. +package errgroup + +import ( + "context" + "fmt" + "sync" +) + +type token struct{} + +// A Group is a collection of goroutines working on subtasks that are part of +// the same overall task. A Group should not be reused for different tasks. +// +// A zero Group is valid, has no limit on the number of active goroutines, +// and does not cancel on error. +type Group struct { + cancel func(error) + + wg sync.WaitGroup + + sem chan token + + errOnce sync.Once + err error +} + +func (g *Group) done() { + if g.sem != nil { + <-g.sem + } + g.wg.Done() +} + +// WithContext returns a new Group and an associated Context derived from ctx. +// +// The derived Context is canceled the first time a function passed to Go +// returns a non-nil error or the first time Wait returns, whichever occurs +// first. +func WithContext(ctx context.Context) (*Group, context.Context) { + ctx, cancel := context.WithCancelCause(ctx) + return &Group{cancel: cancel}, ctx +} + +// Wait blocks until all function calls from the Go method have returned, then +// returns the first non-nil error (if any) from them. +func (g *Group) Wait() error { + g.wg.Wait() + if g.cancel != nil { + g.cancel(g.err) + } + return g.err +} + +// Go calls the given function in a new goroutine. +// +// The first call to Go must happen before a Wait. +// It blocks until the new goroutine can be added without the number of +// goroutines in the group exceeding the configured limit. +// +// The first goroutine in the group that returns a non-nil error will +// cancel the associated Context, if any. The error will be returned +// by Wait. +func (g *Group) Go(f func() error) { + if g.sem != nil { + g.sem <- token{} + } + + g.wg.Add(1) + go func() { + defer g.done() + + // It is tempting to propagate panics from f() + // up to the goroutine that calls Wait, but + // it creates more problems than it solves: + // - it delays panics arbitrarily, + // making bugs harder to detect; + // - it turns f's panic stack into a mere value, + // hiding it from crash-monitoring tools; + // - it risks deadlocks that hide the panic entirely, + // if f's panic leaves the program in a state + // that prevents the Wait call from being reached. + // See #53757, #74275, #74304, #74306. + + if err := f(); err != nil { + g.errOnce.Do(func() { + g.err = err + if g.cancel != nil { + g.cancel(g.err) + } + }) + } + }() +} + +// TryGo calls the given function in a new goroutine only if the number of +// active goroutines in the group is currently below the configured limit. +// +// The return value reports whether the goroutine was started. +func (g *Group) TryGo(f func() error) bool { + if g.sem != nil { + select { + case g.sem <- token{}: + // Note: this allows barging iff channels in general allow barging. + default: + return false + } + } + + g.wg.Add(1) + go func() { + defer g.done() + + if err := f(); err != nil { + g.errOnce.Do(func() { + g.err = err + if g.cancel != nil { + g.cancel(g.err) + } + }) + } + }() + return true +} + +// SetLimit limits the number of active goroutines in this group to at most n. +// A negative value indicates no limit. +// A limit of zero will prevent any new goroutines from being added. +// +// Any subsequent call to the Go method will block until it can add an active +// goroutine without exceeding the configured limit. +// +// The limit must not be modified while any goroutines in the group are active. +func (g *Group) SetLimit(n int) { + if n < 0 { + g.sem = nil + return + } + if active := len(g.sem); active != 0 { + panic(fmt.Errorf("errgroup: modify limit while %v goroutines in the group are still active", active)) + } + g.sem = make(chan token, n) +} diff --git a/vendor/google.golang.org/grpc/internal/xds/xdsdepmgr/watch_service.go b/vendor/google.golang.org/grpc/internal/xds/xdsdepmgr/watch_service.go deleted file mode 100644 index 73f1b7035..000000000 --- a/vendor/google.golang.org/grpc/internal/xds/xdsdepmgr/watch_service.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Copyright 2025 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package xdsdepmgr - -import "google.golang.org/grpc/internal/xds/xdsclient/xdsresource" - -type listenerWatcher struct { - resourceName string - cancel func() - depMgr *DependencyManager -} - -func newListenerWatcher(resourceName string, depMgr *DependencyManager) *listenerWatcher { - lw := &listenerWatcher{resourceName: resourceName, depMgr: depMgr} - lw.cancel = xdsresource.WatchListener(depMgr.xdsClient, resourceName, lw) - return lw -} - -func (l *listenerWatcher) ResourceChanged(update *xdsresource.ListenerUpdate, onDone func()) { - l.depMgr.onListenerResourceUpdate(update, onDone) -} - -func (l *listenerWatcher) ResourceError(err error, onDone func()) { - l.depMgr.onListenerResourceError(err, onDone) -} - -func (l *listenerWatcher) AmbientError(err error, onDone func()) { - l.depMgr.onListenerResourceAmbientError(err, onDone) -} - -func (l *listenerWatcher) stop() { - l.cancel() - if l.depMgr.logger.V(2) { - l.depMgr.logger.Infof("Canceling watch on Listener resource %q", l.resourceName) - } -} - -type routeConfigWatcher struct { - resourceName string - cancel func() - depMgr *DependencyManager -} - -func newRouteConfigWatcher(resourceName string, depMgr *DependencyManager) *routeConfigWatcher { - rw := &routeConfigWatcher{resourceName: resourceName, depMgr: depMgr} - rw.cancel = xdsresource.WatchRouteConfig(depMgr.xdsClient, resourceName, rw) - return rw -} - -func (r *routeConfigWatcher) ResourceChanged(u *xdsresource.RouteConfigUpdate, onDone func()) { - r.depMgr.onRouteConfigResourceUpdate(r.resourceName, u, onDone) -} - -func (r *routeConfigWatcher) ResourceError(err error, onDone func()) { - r.depMgr.onRouteConfigResourceError(r.resourceName, err, onDone) -} - -func (r *routeConfigWatcher) AmbientError(err error, onDone func()) { - r.depMgr.onRouteConfigResourceAmbientError(r.resourceName, err, onDone) -} - -func (r *routeConfigWatcher) stop() { - r.cancel() - if r.depMgr.logger.V(2) { - r.depMgr.logger.Infof("Canceling watch on RouteConfiguration resource %q", r.resourceName) - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 4fe3b51c5..8f0a6ad41 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -79,6 +79,11 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric # github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 ## explicit; go 1.24.0 github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping +# github.com/atc0005/go-teams-notify/v2 v2.14.0 +## explicit; go 1.14 +github.com/atc0005/go-teams-notify/v2 +github.com/atc0005/go-teams-notify/v2/adaptivecard +github.com/atc0005/go-teams-notify/v2/internal/validator # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 github.com/beorn7/perks/quantile @@ -87,6 +92,9 @@ github.com/beorn7/perks/quantile github.com/boombuler/barcode github.com/boombuler/barcode/qr github.com/boombuler/barcode/utils +# github.com/bwmarrin/discordgo v0.29.0 +## explicit; go 1.13 +github.com/bwmarrin/discordgo # github.com/camathieu/pb v1.0.29-0.20190403132434-889de99fc8d5 ## explicit github.com/camathieu/pb @@ -182,6 +190,9 @@ github.com/go-logr/stdr # github.com/go-sql-driver/mysql v1.8.1 ## explicit; go 1.18 github.com/go-sql-driver/mysql +# github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible +## explicit +github.com/go-telegram-bot-api/telegram-bot-api # github.com/golang-jwt/jwt/v5 v5.3.1 ## explicit; go 1.21 github.com/golang-jwt/jwt/v5 @@ -235,6 +246,9 @@ github.com/googleapis/gax-go/v2/iterator # github.com/gorilla/mux v1.8.1 ## explicit; go 1.20 github.com/gorilla/mux +# github.com/gorilla/websocket v1.5.3 +## explicit; go 1.12 +github.com/gorilla/websocket # github.com/iancoleman/strcase v0.3.0 ## explicit; go 1.16 github.com/iancoleman/strcase @@ -335,6 +349,14 @@ github.com/munnerz/goautoneg # github.com/ncw/swift v1.0.53 ## explicit github.com/ncw/swift +# github.com/nikoksr/notify v1.5.0 +## explicit; go 1.24.0 +github.com/nikoksr/notify +github.com/nikoksr/notify/service/discord +github.com/nikoksr/notify/service/http +github.com/nikoksr/notify/service/msteams +github.com/nikoksr/notify/service/slack +github.com/nikoksr/notify/service/telegram # github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d ## explicit github.com/nu7hatch/gouuid @@ -408,6 +430,13 @@ github.com/segmentio/asm/keyset github.com/segmentio/encoding/ascii github.com/segmentio/encoding/iso8601 github.com/segmentio/encoding/json +# github.com/slack-go/slack v0.17.3 +## explicit; go 1.22 +github.com/slack-go/slack +github.com/slack-go/slack/internal/backoff +github.com/slack-go/slack/internal/errorsx +github.com/slack-go/slack/internal/timex +github.com/slack-go/slack/slackutilsx # github.com/spf13/cobra v1.10.2 ## explicit; go 1.15 github.com/spf13/cobra @@ -424,11 +453,18 @@ github.com/spiffe/go-spiffe/v2/internal/jwtutil github.com/spiffe/go-spiffe/v2/internal/pemutil github.com/spiffe/go-spiffe/v2/internal/x509util github.com/spiffe/go-spiffe/v2/spiffeid +# github.com/stretchr/objx v0.5.3 +## explicit; go 1.20 +github.com/stretchr/objx # github.com/stretchr/testify v1.11.1 ## explicit; go 1.17 github.com/stretchr/testify/assert github.com/stretchr/testify/assert/yaml +github.com/stretchr/testify/mock github.com/stretchr/testify/require +# github.com/technoweenie/multipartstreamer v1.0.1 +## explicit +github.com/technoweenie/multipartstreamer # github.com/tinylib/msgp v1.6.1 ## explicit; go 1.24 github.com/tinylib/msgp/msgp @@ -446,16 +482,15 @@ go.opentelemetry.io/auto/sdk/internal/telemetry # go.opentelemetry.io/contrib/detectors/gcp v1.39.0 ## explicit; go 1.24.0 go.opentelemetry.io/contrib/detectors/gcp -# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0 +## explicit; go 1.24.0 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 +## explicit; go 1.24.0 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil # go.opentelemetry.io/otel v1.40.0 ## explicit; go 1.24.0 go.opentelemetry.io/otel @@ -467,9 +502,8 @@ go.opentelemetry.io/otel/codes go.opentelemetry.io/otel/internal/baggage go.opentelemetry.io/otel/internal/global go.opentelemetry.io/otel/propagation -go.opentelemetry.io/otel/semconv/v1.20.0 -go.opentelemetry.io/otel/semconv/v1.26.0 go.opentelemetry.io/otel/semconv/v1.37.0 +go.opentelemetry.io/otel/semconv/v1.37.0/httpconv go.opentelemetry.io/otel/semconv/v1.37.0/rpcconv go.opentelemetry.io/otel/semconv/v1.39.0 go.opentelemetry.io/otel/semconv/v1.39.0/otelconv @@ -520,6 +554,7 @@ golang.org/x/crypto/curve25519 golang.org/x/crypto/hkdf golang.org/x/crypto/internal/alias golang.org/x/crypto/internal/poly1305 +golang.org/x/crypto/nacl/secretbox golang.org/x/crypto/openpgp golang.org/x/crypto/openpgp/armor golang.org/x/crypto/openpgp/elgamal @@ -527,6 +562,7 @@ golang.org/x/crypto/openpgp/errors golang.org/x/crypto/openpgp/packet golang.org/x/crypto/openpgp/s2k golang.org/x/crypto/pbkdf2 +golang.org/x/crypto/salsa20/salsa golang.org/x/crypto/scrypt golang.org/x/crypto/ssh golang.org/x/crypto/ssh/internal/bcrypt_pbkdf @@ -554,6 +590,7 @@ golang.org/x/oauth2/jws golang.org/x/oauth2/jwt # golang.org/x/sync v0.19.0 ## explicit; go 1.24.0 +golang.org/x/sync/errgroup golang.org/x/sync/semaphore # golang.org/x/sys v0.41.0 ## explicit; go 1.24.0 diff --git a/webapp/src/components/DownloadSidebar.vue b/webapp/src/components/DownloadSidebar.vue index d32cb8844..27b2aae83 100644 --- a/webapp/src/components/DownloadSidebar.vue +++ b/webapp/src/components/DownloadSidebar.vue @@ -191,6 +191,26 @@ const canAddFiles = computed(() => props.upload.admin && !props.upload.stream) + + + + + + diff --git a/webapp/src/config.js b/webapp/src/config.js index 997f6631a..701154307 100644 --- a/webapp/src/config.js +++ b/webapp/src/config.js @@ -30,6 +30,10 @@ export const config = reactive({ feature_github: 'default', feature_text: 'default', feature_e2ee: 'enabled', + feature_notification: 'disabled', + + // Notification limits + maxUploadReceivers: 5, // Download domain downloadDomain: '', diff --git a/webapp/src/views/UploadView.vue b/webapp/src/views/UploadView.vue index 858d7f780..a386faea5 100644 --- a/webapp/src/views/UploadView.vue +++ b/webapp/src/views/UploadView.vue @@ -52,6 +52,8 @@ const settings = reactive({ extendTTL: isFeatureDefaultOn('extend_ttl'), e2eeEnabled: isFeatureDefaultOn('e2ee'), e2eePassphrase: '', + notifyCreator: false, + receivers: [], // When both defaultTTL and maxTTL are 0 (no limit), default to "never expires" ON (opt-out) neverExpires: config.defaultTTL <= 0 && effectiveMaxTTL.value <= 0, ttlValue: defaultTTL.value.value || 15, @@ -217,6 +219,16 @@ function buildUploadParams() { params.e2ee = 'age' } + // Notification params + if (isFeatureEnabled('notification')) { + if (settings.notifyCreator) { + params.notifyCreator = true + } + if (settings.receivers && settings.receivers.length > 0) { + params.receivers = settings.receivers + } + } + // Pre-populate files so the server assigns IDs (matched back via reference) params.files = files.value.map(f => ({ fileName: f.fileName, @@ -314,6 +326,7 @@ async function doUpload() {