├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md ├── dependabot.yml ├── pull_request_template.md └── workflows │ └── ci.yml ├── .gitignore ├── .golangci.yml ├── LICENSE ├── Makefile ├── README.md ├── assets ├── demo_gif.png ├── demo_gifs.png ├── demo_post.png ├── demo_preview.png ├── demo_preview_with_previous.png ├── icon-inkscape.svg ├── icon.png └── icon.svg ├── build ├── .gitignore ├── custom.mk ├── legacy.mk ├── manifest │ └── main.go ├── pluginctl │ └── main.go └── setup.mk ├── go.mod ├── go.sum ├── plugin.go ├── plugin.json ├── public └── powered-by-giphy.png └── server ├── .gitignore ├── commands.go ├── commands_test.go ├── configuration.go ├── configuration_test.go ├── httpHandler.go ├── httpHandler_test.go ├── internal ├── configuration │ └── configuration.go ├── error │ └── plugin_error.go ├── pluginapi │ ├── mock_pluginapi │ │ └── mock_pluginapi.go │ └── pluginapi.go ├── provider │ ├── gif_provider.go │ ├── gif_provider_test.go │ ├── giphy.go │ ├── giphy_test.go │ ├── tenor.go │ ├── tenor_test.go │ └── utils_test.go └── test │ └── helpers.go ├── main.go ├── plugin.go └── plugin_test.go /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Mattermost information** 27 | - server version (e.g. 5.20.1) 28 | - client version (e.g. Desktop Client 4.4, or Android app 1.29.0) 29 | - plugin version (e.g. 2.1.0) 30 | - add any relevant server logs (after removing any private data from the logs, such as your IP). They can be found in the Admin console > Server Logs. 31 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" # Location of package manifests 5 | schedule: 6 | interval: "quarterly" 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Summary 2 | 3 | 4 | Fixes #XXX 5 | 6 | 7 | 8 | ## Screenshots 9 | 10 | 11 | 12 | ## Checklist 13 | 14 | - [ ] updated/completed the unit tests 15 | - [ ] tested on a Mattermost server: _indicate tested version(s) here_ (you can use the [mattermost-preview Docker image](https://docs.mattermost.com/install/docker-local-machine.html) for a quick and painless install) 16 | - [ ] updated the docs 17 | - [ ] cleaned the branch git history 18 | - [ ] **rebased** branch on the target branch (must be up-to-date at the time of merge) 19 | 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Build CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - develop 8 | - release/** 9 | pull_request: 10 | types: [opened, synchronize, reopened] 11 | release: 12 | types: [published] 13 | 14 | env: 15 | GO111MODULE: on 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | 25 | - name: Setup Go environment 26 | uses: actions/setup-go@v5 27 | with: 28 | go-version-file: 'go.mod' 29 | 30 | - name: Install golangci-lint 31 | uses: golangci/golangci-lint-action@v8 32 | 33 | - name: Build 34 | run: make 35 | 36 | - name: Publish 37 | if: github.event_name == 'release' 38 | uses: softprops/action-gh-release@v2 39 | with: 40 | files: dist/* 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | plugin 2 | plugin.exe 3 | debug 4 | debug.test* 5 | plugin.tar.gz 6 | mattermost-plugin-giphy.exe 7 | mattermost-plugin-giphy.tar.gz 8 | vendor/ 9 | dist/ 10 | .vscode/ 11 | coverage.txt 12 | TODO.txt 13 | Debug.txt 14 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | run: 3 | modules-download-mode: readonly 4 | linters: 5 | default: none 6 | enable: 7 | - bodyclose 8 | - errcheck 9 | - gocritic 10 | - gosec 11 | - govet 12 | - ineffassign 13 | - misspell 14 | - nakedret 15 | - revive 16 | - staticcheck 17 | - unconvert 18 | - unused 19 | - whitespace 20 | settings: 21 | govet: 22 | disable: 23 | - fieldalignment 24 | enable-all: true 25 | misspell: 26 | locale: US 27 | exclusions: 28 | generated: lax 29 | presets: 30 | - comments 31 | - common-false-positives 32 | - legacy 33 | - std-error-handling 34 | rules: 35 | - linters: 36 | - unused 37 | path: server/configuration.go 38 | - linters: 39 | - bodyclose 40 | - scopelint 41 | path: _test\.go 42 | paths: 43 | - third_party$ 44 | - builtin$ 45 | - examples$ 46 | formatters: 47 | enable: 48 | - gofmt 49 | - goimports 50 | settings: 51 | gofmt: 52 | simplify: true 53 | goimports: 54 | local-prefixes: 55 | - github.com/mattermost/mattermost-starter-template 56 | exclusions: 57 | generated: lax 58 | paths: 59 | - third_party$ 60 | - builtin$ 61 | - examples$ 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GO ?= $(shell command -v go 2> /dev/null) 2 | NPM ?= $(shell command -v npm 2> /dev/null) 3 | CURL ?= $(shell command -v curl 2> /dev/null) 4 | MM_DEBUG ?= 5 | MANIFEST_FILE ?= plugin.json 6 | GOPATH ?= $(shell go env GOPATH) 7 | GO_TEST_FLAGS ?= -race 8 | GO_BUILD_FLAGS ?= 9 | MM_UTILITIES_DIR ?= ../mattermost-utilities 10 | DLV_DEBUG_PORT := 2346 11 | DEFAULT_GOOS := $(shell go env GOOS) 12 | DEFAULT_GOARCH := $(shell go env GOARCH) 13 | 14 | export GO111MODULE=on 15 | 16 | # You can include assets this directory into the bundle. This can be e.g. used to include profile pictures. 17 | ASSETS_DIR ?= assets 18 | 19 | ## Define the default target (make all) 20 | .PHONY: default 21 | default: all 22 | 23 | # Verify environment, and define PLUGIN_ID, PLUGIN_VERSION, HAS_SERVER and HAS_WEBAPP as needed. 24 | include build/setup.mk 25 | include build/legacy.mk 26 | 27 | BUNDLE_NAME ?= $(PLUGIN_ID)-$(PLUGIN_VERSION).tar.gz 28 | 29 | # Include custom makefile, if present 30 | ifneq ($(wildcard build/custom.mk),) 31 | include build/custom.mk 32 | endif 33 | 34 | ifneq ($(MM_DEBUG),) 35 | GO_BUILD_GCFLAGS = -gcflags "all=-N -l" 36 | else 37 | GO_BUILD_GCFLAGS = 38 | endif 39 | 40 | ## Checks the code style, tests, builds and bundles the plugin. 41 | .PHONY: all 42 | all: check-style test dist 43 | 44 | ## Runs eslint and golangci-lint 45 | .PHONY: check-style 46 | check-style: webapp/node_modules 47 | @echo Checking for style guide compliance 48 | 49 | ifneq ($(HAS_WEBAPP),) 50 | cd webapp && npm run lint 51 | cd webapp && npm run check-types 52 | endif 53 | 54 | ifneq ($(HAS_SERVER),) 55 | @if ! [ -x "$$(command -v golangci-lint)" ]; then \ 56 | echo "golangci-lint is not installed. Please see https://github.com/golangci/golangci-lint#install for installation instructions."; \ 57 | exit 1; \ 58 | fi; \ 59 | 60 | @echo Running golangci-lint 61 | golangci-lint run ./... 62 | endif 63 | 64 | ## Builds the server, if it exists, for all supported architectures, unless MM_SERVICESETTINGS_ENABLEDEVELOPER is set. 65 | .PHONY: server 66 | server: 67 | ifneq ($(HAS_SERVER),) 68 | ifneq ($(MM_DEBUG),) 69 | $(info DEBUG mode is on; to disable, unset MM_DEBUG) 70 | endif 71 | mkdir -p server/dist; 72 | ifneq ($(MM_SERVICESETTINGS_ENABLEDEVELOPER),) 73 | @echo Building plugin only for $(DEFAULT_GOOS)-$(DEFAULT_GOARCH) because MM_SERVICESETTINGS_ENABLEDEVELOPER is enabled 74 | cd server && env CGO_ENABLED=0 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-$(DEFAULT_GOOS)-$(DEFAULT_GOARCH); 75 | else 76 | cd server && env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-linux-amd64; 77 | cd server && env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-linux-arm64; 78 | cd server && env CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-darwin-amd64; 79 | cd server && env CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-darwin-arm64; 80 | cd server && env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-windows-amd64.exe; 81 | cd server && env CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-freebsd-amd64.exe; 82 | endif 83 | endif 84 | 85 | ## Ensures NPM dependencies are installed without having to run this all the time. 86 | webapp/node_modules: $(wildcard webapp/package.json) 87 | ifneq ($(HAS_WEBAPP),) 88 | cd webapp && $(NPM) install 89 | touch $@ 90 | endif 91 | 92 | ## Builds the webapp, if it exists. 93 | .PHONY: webapp 94 | webapp: webapp/node_modules 95 | ifneq ($(HAS_WEBAPP),) 96 | ifeq ($(MM_DEBUG),) 97 | cd webapp && $(NPM) run build; 98 | else 99 | cd webapp && $(NPM) run debug; 100 | endif 101 | endif 102 | 103 | ## Generates a tar bundle of the plugin for install. 104 | .PHONY: bundle 105 | bundle: 106 | rm -rf dist/ 107 | mkdir -p dist/$(PLUGIN_ID) 108 | cp $(MANIFEST_FILE) dist/$(PLUGIN_ID)/ 109 | ifneq ($(wildcard $(ASSETS_DIR)/.),) 110 | cp -r $(ASSETS_DIR) dist/$(PLUGIN_ID)/ 111 | endif 112 | ifneq ($(HAS_PUBLIC),) 113 | cp -r public dist/$(PLUGIN_ID)/ 114 | endif 115 | ifneq ($(HAS_SERVER),) 116 | mkdir -p dist/$(PLUGIN_ID)/server 117 | cp -r server/dist dist/$(PLUGIN_ID)/server/ 118 | endif 119 | ifneq ($(HAS_WEBAPP),) 120 | mkdir -p dist/$(PLUGIN_ID)/webapp 121 | cp -r webapp/dist dist/$(PLUGIN_ID)/webapp/ 122 | endif 123 | cd dist && tar -cvzf $(BUNDLE_NAME) $(PLUGIN_ID) 124 | 125 | @echo plugin built at: dist/$(BUNDLE_NAME) 126 | 127 | ## Builds and bundles the plugin. 128 | .PHONY: dist 129 | dist: server webapp bundle 130 | 131 | ## Builds and installs the plugin to a server. 132 | .PHONY: deploy 133 | deploy: dist 134 | ./build/bin/pluginctl deploy $(PLUGIN_ID) dist/$(BUNDLE_NAME) 135 | 136 | ## Builds and installs the plugin to a server, updating the webapp automatically when changed. 137 | .PHONY: watch 138 | watch: server bundle 139 | ifeq ($(MM_DEBUG),) 140 | cd webapp && $(NPM) run build:watch 141 | else 142 | cd webapp && $(NPM) run debug:watch 143 | endif 144 | 145 | ## Installs a previous built plugin with updated webpack assets to a server. 146 | .PHONY: deploy-from-watch 147 | deploy-from-watch: bundle 148 | ./build/bin/pluginctl deploy $(PLUGIN_ID) dist/$(BUNDLE_NAME) 149 | 150 | ## Setup dlv for attaching, identifying the plugin PID for other targets. 151 | .PHONY: setup-attach 152 | setup-attach: 153 | $(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}')) 154 | $(eval NUM_PID := $(shell echo -n ${PLUGIN_PID} | wc -w)) 155 | 156 | @if [ ${NUM_PID} -gt 2 ]; then \ 157 | echo "** There is more than 1 plugin process running. Run 'make kill reset' to restart just one."; \ 158 | exit 1; \ 159 | fi 160 | 161 | ## Check if setup-attach succeeded. 162 | .PHONY: check-attach 163 | check-attach: 164 | @if [ -z ${PLUGIN_PID} ]; then \ 165 | echo "Could not find plugin PID; the plugin is not running. Exiting."; \ 166 | exit 1; \ 167 | else \ 168 | echo "Located Plugin running with PID: ${PLUGIN_PID}"; \ 169 | fi 170 | 171 | ## Attach dlv to an existing plugin instance. 172 | .PHONY: attach 173 | attach: setup-attach check-attach 174 | dlv attach ${PLUGIN_PID} 175 | 176 | ## Attach dlv to an existing plugin instance, exposing a headless instance on $DLV_DEBUG_PORT. 177 | .PHONY: attach-headless 178 | attach-headless: setup-attach check-attach 179 | dlv attach ${PLUGIN_PID} --listen :$(DLV_DEBUG_PORT) --headless=true --api-version=2 --accept-multiclient 180 | 181 | ## Detach dlv from an existing plugin instance, if previously attached. 182 | .PHONY: detach 183 | detach: setup-attach 184 | @DELVE_PID=$(shell ps aux | grep "dlv attach ${PLUGIN_PID}" | grep -v "grep" | awk -F " " '{print $$2}') && \ 185 | if [ "$$DELVE_PID" -gt 0 ] > /dev/null 2>&1 ; then \ 186 | echo "Located existing delve process running with PID: $$DELVE_PID. Killing." ; \ 187 | kill -9 $$DELVE_PID ; \ 188 | fi 189 | 190 | ## Runs any lints and unit tests defined for the server and webapp, if they exist. 191 | .PHONY: test 192 | test: webapp/node_modules 193 | ifneq ($(HAS_SERVER),) 194 | $(GO) test -v $(GO_TEST_FLAGS) ./server/... 195 | endif 196 | ifneq ($(HAS_WEBAPP),) 197 | cd webapp && $(NPM) run test; 198 | endif 199 | 200 | ## Creates a coverage report for the server code. 201 | .PHONY: coverage 202 | coverage: webapp/node_modules 203 | ifneq ($(HAS_SERVER),) 204 | $(GO) test $(GO_TEST_FLAGS) -coverprofile=server/coverage.txt ./server/... 205 | $(GO) tool cover -html=server/coverage.txt 206 | endif 207 | 208 | ## Extract strings for translation from the source code. 209 | .PHONY: i18n-extract 210 | i18n-extract: 211 | ifneq ($(HAS_WEBAPP),) 212 | ifeq ($(HAS_MM_UTILITIES),) 213 | @echo "You must clone github.com/mattermost/mattermost-utilities repo in .. to use this command" 214 | else 215 | cd $(MM_UTILITIES_DIR) && npm install && npm run babel && node mmjstool/build/index.js i18n extract-webapp --webapp-dir $(PWD)/webapp 216 | endif 217 | endif 218 | 219 | ## Disable the plugin. 220 | .PHONY: disable 221 | disable: detach 222 | ./build/bin/pluginctl disable $(PLUGIN_ID) 223 | 224 | ## Enable the plugin. 225 | .PHONY: enable 226 | enable: 227 | ./build/bin/pluginctl enable $(PLUGIN_ID) 228 | 229 | ## Reset the plugin, effectively disabling and re-enabling it on the server. 230 | .PHONY: reset 231 | reset: detach 232 | ./build/bin/pluginctl reset $(PLUGIN_ID) 233 | 234 | ## Kill all instances of the plugin, detaching any existing dlv instance. 235 | .PHONY: kill 236 | kill: detach 237 | $(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}')) 238 | 239 | @for PID in ${PLUGIN_PID}; do \ 240 | echo "Killing plugin pid $$PID"; \ 241 | kill -9 $$PID; \ 242 | done; \ 243 | 244 | ## Clean removes all build artifacts. 245 | .PHONY: clean 246 | clean: 247 | rm -fr dist/ 248 | ifneq ($(HAS_SERVER),) 249 | rm -fr server/coverage.txt 250 | rm -fr server/dist 251 | endif 252 | ifneq ($(HAS_WEBAPP),) 253 | rm -fr webapp/junit.xml 254 | rm -fr webapp/dist 255 | rm -fr webapp/node_modules 256 | endif 257 | rm -fr build/bin/ 258 | 259 | # Help documentation à la https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html 260 | help: 261 | @cat Makefile build/*.mk | grep -v '\.PHONY' | grep -v '\help:' | grep -B1 -E '^[a-zA-Z0-9_.-]+:.*' | sed -e "s/:.*//" | sed -e "s/^## //" | grep -v '\-\-' | sed '1!G;h;$$!d' | awk 'NR%2{printf "\033[36m%-30s\033[0m",$$0;next;}1' | sort 262 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mattermost GIF commands plugin (ex-'GIPHY plugin') 2 | 3 | [![Build Status](https://github.com/moussetc/mattermost-plugin-giphy/actions/workflows/ci.yml/badge.svg)](https://github.com/moussetc/mattermost-plugin-giphy/actions/workflows/ci.yml/badge.svg) 4 | 5 | **Maintainer:** [@moussetc](https://github.com/moussetc) 6 | 7 | A Mattermost plugin to post GIFs from **Giphy or Tenor** with slash commands. 8 | 9 | ## Usage 10 | 11 | ### Plugin v2.0.0 & higher 12 | 13 | Use the command `/gif "" ""` to search for a GIF and shuffle through GIFs until you find one you like. You can also use `/gif ` if you don't want to add a custom caption. 14 | 15 | Example: first choose a GIF with `/gif "waving cat" "Hello!"` and use the Shuffle button to browse others GIFs: 16 | 17 | ![demo](assets/demo_preview.png) 18 | 19 | You can use the Previous button to go back to previous results: 20 | ![demo](assets/demo_preview_with_previous.png) 21 | 22 | When you found the perfect GIF, use the Send button to post it: 23 | 24 | ![demo](assets/demo_post.png). 25 | 26 | *If you prefer having both the `/gif` (post GIF without previewing!) AND `/gifs` (preview and choose GIF before posting) as in the previous versions of the plugin, you can disable the 'Force GIF preview before posting' in the plugin configuration.* 27 | 28 | ## Compatibility 29 | Use the following table to find the correct plugin version for each Mattermost server version: 30 | 31 | | Mattermost server | Plugin release | Incompatibility | 32 | | --- | --- | --- | 33 | | 6.5 and higher | v3.0.x and higher | - | 34 | | 6.0 to 6.4 | v2.0.x and higher | breaking plugin API changes | 35 | | 5.20 to 5.39 | v1.2.x and higher | breaking plugin manifest change | 36 | | 5.12 to 5.19 | v1.1.x | breaking plugin API change | 37 | | 5.10 to 5.11 | v1.0.x | buttons on ephemeral posts | 38 | | 5.2 to 5.9 | v0.2.0 | | 39 | | 4.6 to 5.1 | v0.1.x | | 40 | | below | *not supported* | plugins can't create slash commands | 41 | 42 | ## Installation and configuration 43 | 44 | > [!TIP] 45 | > This plugin was for a few years available in the official Mattermost marketplace, however the Mattermost team [decided to stop hosting community plugins in the marketplace](https://mattermost.atlassian.net/browse/MM-53030) in September 2023, so however you installed your current version, you will need to follow the manual installation steps below. 46 | 47 | 1. Go to the [Releases page](https://github.com/moussetc/mattermost-plugin-giphy/releases) and download the `.tar.gz` package. Supported platforms are: Linux x64, Windows x64, Darwin x64, FreeBSD x64. 48 | 2. Use the Mattermost `System Console > Plugins Management > Management` page to upload the `.tar.gz` package 49 | 3. Go to the `System Console > Plugins > GIF commands` 50 | 4. Choose if you want to use GIPHY (default) or Tenor (both of which requires an API key, see below). 51 | 5. **Configure the Giphy or Tenor API key** as explained on the configuration page. 52 | 6. You can also configure the following settings : 53 | - display style (non-collapsable embedded image or collapsable full URL preview) 54 | - rendition style (GIF size, quality, etc.) 55 | - rating 56 | - language (not available for Giphy if random is activated) 57 | - random (true random is only available for Giphy; for Tenor, the random only applies to the current page of results, meaning you'll need to use Shuffle until a new page of results is loaded in order to see new results even in random mode) 58 | 7. **Activate the plugin** in the `System Console > Plugins Management > Management` page 59 | 60 | ### Configuration Notes in HA 61 | 62 | If you are running Mattermost v5.11 or earlier in [High Availability mode](https://docs.mattermost.com/deployment/cluster.html), please review the following: 63 | 64 | 1. To install the plugin, [use these documented steps](https://docs.mattermost.com/administration/plugins.html#plugin-uploads-in-high-availability-mode) 65 | 2. Then, modify the config.json [using the standard doc steps](https://docs.mattermost.com/deployment/cluster.html#updating-configuration-changes-while-operating-continuously) to the following (check the [plugin.json](https://github.com/moussetc/mattermost-plugin-giphy/blob/master/plugin.json) file to see the lists of options for language, rating, rendition, etC.). 66 | 67 | ```json 68 | "PluginSettings": { 69 | // [...] 70 | "Plugins": { 71 | "com.github.moussetc.mattermost.plugin.giphy": { 72 | "displaymode": "embedded", 73 | "provider": "", 74 | "apikey": "", 75 | "language": "en", 76 | "rating": "none", 77 | "rendition": "fixed_height_small", 78 | "renditiontenor": "mediumgif", 79 | "randomsearch": true, 80 | "disablepostingwithoutpreview": true 81 | }, 82 | }, 83 | "PluginStates": { 84 | // [...] 85 | "com.github.moussetc.mattermost.plugin.giphy": { 86 | "Enable": true 87 | }, 88 | } 89 | } 90 | ``` 91 | 92 | ## TROUBLESHOOTING 93 | 94 | ### I can't upload or activate the plugin 95 | - Is your plugin version compatible with your server version? Check the Compatibility section in the README. 96 | - Make sure you have configured the `SiteURL` setting correctly in the Mattermost administration panel. 97 | - Check the Mattermost logs (`yourURL/admin_console/logs`) for more detail on why the activation failed. 98 | 99 | ### Error 'Command with a trigger of `/gif` not found' 100 | This happens when the plugin is not activated, see above section. 101 | 102 | ### Error 'Unable to get GIF URL' 103 | Start by checking the Mattermost logs (`yourURL/admin_console/logs`) for more detail. Usual causes include: 104 | - Using GIPHY as provider and using the public beta Giphy. The log will looks like: `{"level":"error", ... ,"msg":"Unable to get GIF URL", ... ,"method":"POST","err_where":"Giphy Plugin","http_code":400,"err_details":"Error HTTP status 429: 429 Unknown Error"}`. Solution: get your own GIPHY API key as the default one shouldn't be used in production. 105 | - If your Mattermost server is behind a proxy: 106 | - If the proxy blocks Giphy and Tenor: there's no solution besides convincing your security department that accessing Giphy is business-critical. 107 | - If the proxy allows Giphy and Tenor: configure your Mattermost server to use your [outbound proxy](https://docs.mattermost.com/install/outbound-proxy.html). 108 | 109 | ### The picture doesn't load 110 | - Your client (web client, desktop client, etc.) might be behind a proxy that blocks GIPHY or Tenor. Solution: activate the Mattermost [image proxy](https://docs.mattermost.com/administration/image-proxy.html). 111 | - If the Display Mode configured is "Collapsable Image Preview", then the link previews option must be configured in the System Console (> Posts > Enable Link Previews). Do note that user can also change this option in their Account Settings. 112 | 113 | ### There are no buttons on the shuffle message 114 | - Check your Mattermost version with the compatibility list at the top of this page. 115 | 116 | ## Development 117 | 118 | To avoid having to manually install your plugin, build and deploy your plugin using one of the following options. In order for the below options to work, you must first enable plugin uploads via your config.json or API and restart Mattermost. 119 | 120 | ```json 121 | "PluginSettings" : { 122 | ... 123 | "EnableUploads" : true 124 | } 125 | ``` 126 | 127 | ### Deploying with Local Mode 128 | 129 | If your Mattermost server is running locally, you can enable [local mode](https://docs.mattermost.com/administration/mmctl-cli-tool.html#local-mode) to streamline deploying your plugin. Edit your server configuration as follows: 130 | 131 | ```json 132 | { 133 | "ServiceSettings": { 134 | ... 135 | "EnableLocalMode": true, 136 | "LocalModeSocketLocation": "/var/tmp/mattermost_local.socket" 137 | }, 138 | } 139 | ``` 140 | 141 | and then deploy your plugin: 142 | ``` 143 | make deploy 144 | ``` 145 | 146 | You may also customize the Unix socket path: 147 | ``` 148 | export MM_LOCALSOCKETPATH=/var/tmp/alternate_local.socket 149 | make deploy 150 | ``` 151 | 152 | If developing a plugin with a webapp, watch for changes and deploy those automatically: 153 | ``` 154 | export MM_SERVICESETTINGS_SITEURL=http://localhost:8065 155 | export MM_ADMIN_TOKEN=j44acwd8obn78cdcx7koid4jkr 156 | make watch 157 | ``` 158 | 159 | ### Deploying with credentials 160 | 161 | Alternatively, you can authenticate with the server's API with credentials: 162 | ``` 163 | export MM_SERVICESETTINGS_SITEURL=http://localhost:8065 164 | export MM_ADMIN_USERNAME=admin 165 | export MM_ADMIN_PASSWORD=password 166 | make deploy 167 | ``` 168 | 169 | or with a [personal access token](https://docs.mattermost.com/developer/personal-access-tokens.html): 170 | ``` 171 | export MM_SERVICESETTINGS_SITEURL=http://localhost:8065 172 | export MM_ADMIN_TOKEN=j44acwd8obn78cdcx7koid4jkr 173 | make deploy 174 | ``` 175 | 176 | ## How do I share feedback on this plugin? 177 | 178 | Feel free to create a GitHub issue or to contact me at `@cmousset` on the [community Mattermost instance](https://pre-release.mattermost.com/) to discuss. 179 | -------------------------------------------------------------------------------- /assets/demo_gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/demo_gif.png -------------------------------------------------------------------------------- /assets/demo_gifs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/demo_gifs.png -------------------------------------------------------------------------------- /assets/demo_post.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/demo_post.png -------------------------------------------------------------------------------- /assets/demo_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/demo_preview.png -------------------------------------------------------------------------------- /assets/demo_preview_with_previous.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/demo_preview_with_previous.png -------------------------------------------------------------------------------- /assets/icon-inkscape.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 45 | 47 | 48 | 50 | image/svg+xml 51 | 53 | 54 | 55 | 56 | 57 | 61 | 67 | 68 | 72 | /gif 83 | 84 | 85 | -------------------------------------------------------------------------------- /assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/assets/icon.png -------------------------------------------------------------------------------- /assets/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 20 | 22 | 48 | 50 | 51 | 53 | image/svg+xml 54 | 56 | 57 | 58 | 59 | 60 | 64 | 70 | 71 | 75 | /gif 86 | 87 | 88 | -------------------------------------------------------------------------------- /build/.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | -------------------------------------------------------------------------------- /build/custom.mk: -------------------------------------------------------------------------------- 1 | # Include custom targets and environment variables here 2 | -------------------------------------------------------------------------------- /build/legacy.mk: -------------------------------------------------------------------------------- 1 | .PHONY: apply 2 | apply: 3 | @echo make apply is deprecated and has no effect. 4 | -------------------------------------------------------------------------------- /build/manifest/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/mattermost/mattermost/server/public/model" 9 | "github.com/pkg/errors" 10 | ) 11 | 12 | func main() { 13 | if len(os.Args) <= 1 { 14 | panic("no cmd specified") 15 | } 16 | 17 | manifest, err := findManifest() 18 | if err != nil { 19 | panic("failed to find manifest: " + err.Error()) 20 | } 21 | 22 | cmd := os.Args[1] 23 | switch cmd { 24 | case "id": 25 | dumpPluginID(manifest) 26 | 27 | case "version": 28 | dumpPluginVersion(manifest) 29 | 30 | case "has_server": 31 | if manifest.HasServer() { 32 | fmt.Printf("true") 33 | } 34 | 35 | case "has_webapp": 36 | if manifest.HasWebapp() { 37 | fmt.Printf("true") 38 | } 39 | 40 | default: 41 | panic("unrecognized command: " + cmd) 42 | } 43 | } 44 | 45 | func findManifest() (*model.Manifest, error) { 46 | _, manifestFilePath, err := model.FindManifest(".") 47 | if err != nil { 48 | return nil, errors.Wrap(err, "failed to find manifest in current working directory") 49 | } 50 | manifestFile, err := os.Open(manifestFilePath) 51 | if err != nil { 52 | return nil, errors.Wrapf(err, "failed to open %s", manifestFilePath) 53 | } 54 | defer manifestFile.Close() 55 | 56 | // Re-decode the manifest, disallowing unknown fields. When we write the manifest back out, 57 | // we don't want to accidentally clobber anything we won't preserve. 58 | var manifest model.Manifest 59 | decoder := json.NewDecoder(manifestFile) 60 | decoder.DisallowUnknownFields() 61 | if err = decoder.Decode(&manifest); err != nil { 62 | return nil, errors.Wrap(err, "failed to parse manifest") 63 | } 64 | 65 | return &manifest, nil 66 | } 67 | 68 | // dumpPluginId writes the plugin id from the given manifest to standard out 69 | func dumpPluginID(manifest *model.Manifest) { 70 | fmt.Printf("%s", manifest.Id) 71 | } 72 | 73 | // dumpPluginVersion writes the plugin version from the given manifest to standard out 74 | func dumpPluginVersion(manifest *model.Manifest) { 75 | fmt.Printf("%s", manifest.Version) 76 | } 77 | -------------------------------------------------------------------------------- /build/pluginctl/main.go: -------------------------------------------------------------------------------- 1 | // main handles deployment of the plugin to a development server using the Client4 API. 2 | package main 3 | 4 | import ( 5 | "context" 6 | "errors" 7 | "fmt" 8 | "log" 9 | "net" 10 | "os" 11 | "time" 12 | 13 | "github.com/mattermost/mattermost/server/public/model" 14 | ) 15 | 16 | const commandTimeout = 120 * time.Second 17 | 18 | const helpText = ` 19 | Usage: 20 | pluginctl deploy 21 | pluginctl disable 22 | pluginctl enable 23 | pluginctl reset 24 | ` 25 | 26 | func main() { 27 | err := pluginctl() 28 | if err != nil { 29 | fmt.Printf("Failed: %s\n", err.Error()) 30 | fmt.Print(helpText) 31 | os.Exit(1) 32 | } 33 | } 34 | 35 | func pluginctl() error { 36 | if len(os.Args) < 3 { 37 | return errors.New("invalid number of arguments") 38 | } 39 | 40 | ctx, cancel := context.WithTimeout(context.Background(), commandTimeout) 41 | defer cancel() 42 | 43 | client, err := getClient(ctx) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | switch os.Args[1] { 49 | case "deploy": 50 | if len(os.Args) < 4 { 51 | return errors.New("invalid number of arguments") 52 | } 53 | return deploy(ctx, client, os.Args[2], os.Args[3]) 54 | case "disable": 55 | return disablePlugin(ctx, client, os.Args[2]) 56 | case "enable": 57 | return enablePlugin(ctx, client, os.Args[2]) 58 | case "reset": 59 | return resetPlugin(ctx, client, os.Args[2]) 60 | default: 61 | return errors.New("invalid second argument") 62 | } 63 | } 64 | 65 | func getClient(ctx context.Context) (*model.Client4, error) { 66 | socketPath := os.Getenv("MM_LOCALSOCKETPATH") 67 | if socketPath == "" { 68 | socketPath = model.LocalModeSocketPath 69 | } 70 | 71 | client, connected := getUnixClient(socketPath) 72 | if connected { 73 | log.Printf("Connecting using local mode over %s", socketPath) 74 | return client, nil 75 | } 76 | 77 | if os.Getenv("MM_LOCALSOCKETPATH") != "" { 78 | log.Printf("No socket found at %s for local mode deployment. Attempting to authenticate with credentials.", socketPath) 79 | } 80 | 81 | siteURL := os.Getenv("MM_SERVICESETTINGS_SITEURL") 82 | adminToken := os.Getenv("MM_ADMIN_TOKEN") 83 | adminUsername := os.Getenv("MM_ADMIN_USERNAME") 84 | adminPassword := os.Getenv("MM_ADMIN_PASSWORD") 85 | 86 | if siteURL == "" { 87 | return nil, errors.New("MM_SERVICESETTINGS_SITEURL is not set") 88 | } 89 | 90 | client = model.NewAPIv4Client(siteURL) 91 | 92 | if adminToken != "" { 93 | log.Printf("Authenticating using token against %s.", siteURL) 94 | client.SetToken(adminToken) 95 | return client, nil 96 | } 97 | 98 | if adminUsername != "" && adminPassword != "" { 99 | client := model.NewAPIv4Client(siteURL) 100 | log.Printf("Authenticating as %s against %s.", adminUsername, siteURL) 101 | _, _, err := client.Login(ctx, adminUsername, adminPassword) 102 | if err != nil { 103 | return nil, fmt.Errorf("failed to login as %s: %w", adminUsername, err) 104 | } 105 | 106 | return client, nil 107 | } 108 | 109 | return nil, errors.New("one of MM_ADMIN_TOKEN or MM_ADMIN_USERNAME/MM_ADMIN_PASSWORD must be defined") 110 | } 111 | 112 | func getUnixClient(socketPath string) (*model.Client4, bool) { 113 | _, err := net.Dial("unix", socketPath) 114 | if err != nil { 115 | return nil, false 116 | } 117 | 118 | return model.NewAPIv4SocketClient(socketPath), true 119 | } 120 | 121 | // deploy attempts to upload and enable a plugin via the Client4 API. 122 | // It will fail if plugin uploads are disabled. 123 | func deploy(ctx context.Context, client *model.Client4, pluginID, bundlePath string) error { 124 | pluginBundle, err := os.Open(bundlePath) 125 | if err != nil { 126 | return fmt.Errorf("failed to open %s: %w", bundlePath, err) 127 | } 128 | defer pluginBundle.Close() 129 | 130 | log.Print("Uploading plugin via API.") 131 | _, _, err = client.UploadPluginForced(ctx, pluginBundle) 132 | if err != nil { 133 | return fmt.Errorf("failed to upload plugin bundle: %s", err.Error()) 134 | } 135 | 136 | log.Print("Enabling plugin.") 137 | _, err = client.EnablePlugin(ctx, pluginID) 138 | if err != nil { 139 | return fmt.Errorf("failed to enable plugin: %s", err.Error()) 140 | } 141 | 142 | return nil 143 | } 144 | 145 | // disablePlugin attempts to disable the plugin via the Client4 API. 146 | func disablePlugin(ctx context.Context, client *model.Client4, pluginID string) error { 147 | log.Print("Disabling plugin.") 148 | _, err := client.DisablePlugin(ctx, pluginID) 149 | if err != nil { 150 | return fmt.Errorf("failed to disable plugin: %w", err) 151 | } 152 | 153 | return nil 154 | } 155 | 156 | // enablePlugin attempts to enable the plugin via the Client4 API. 157 | func enablePlugin(ctx context.Context, client *model.Client4, pluginID string) error { 158 | log.Print("Enabling plugin.") 159 | _, err := client.EnablePlugin(ctx, pluginID) 160 | if err != nil { 161 | return fmt.Errorf("failed to enable plugin: %w", err) 162 | } 163 | 164 | return nil 165 | } 166 | 167 | // resetPlugin attempts to reset the plugin via the Client4 API. 168 | func resetPlugin(ctx context.Context, client *model.Client4, pluginID string) error { 169 | err := disablePlugin(ctx, client, pluginID) 170 | if err != nil { 171 | return err 172 | } 173 | 174 | err = enablePlugin(ctx, client, pluginID) 175 | if err != nil { 176 | return err 177 | } 178 | 179 | return nil 180 | } 181 | -------------------------------------------------------------------------------- /build/setup.mk: -------------------------------------------------------------------------------- 1 | # Ensure that go is installed. Note that this is independent of whether or not a server is being 2 | # built, since the build script itself uses go. 3 | ifeq ($(GO),) 4 | $(error "go is not available: see https://golang.org/doc/install") 5 | endif 6 | 7 | # Ensure that the build tools are compiled. Go's caching makes this quick. 8 | $(shell cd build/manifest && $(GO) build -o ../bin/manifest) 9 | 10 | # Ensure that the deployment tools are compiled. Go's caching makes this quick. 11 | $(shell cd build/pluginctl && $(GO) build -o ../bin/pluginctl) 12 | 13 | # Extract the plugin id from the manifest. 14 | PLUGIN_ID ?= $(shell build/bin/manifest id) 15 | ifeq ($(PLUGIN_ID),) 16 | $(error "Cannot parse id from $(MANIFEST_FILE)") 17 | endif 18 | 19 | # Extract the plugin version from the manifest. 20 | PLUGIN_VERSION ?= $(shell build/bin/manifest version) 21 | ifeq ($(PLUGIN_VERSION),) 22 | $(error "Cannot parse version from $(MANIFEST_FILE)") 23 | endif 24 | 25 | # Determine if a server is defined in the manifest. 26 | HAS_SERVER ?= $(shell build/bin/manifest has_server) 27 | 28 | # Determine if a webapp is defined in the manifest. 29 | HAS_WEBAPP ?= $(shell build/bin/manifest has_webapp) 30 | 31 | # Determine if a /public folder is in use 32 | HAS_PUBLIC ?= $(wildcard public/.) 33 | 34 | # Determine if the mattermost-utilities repo is present 35 | HAS_MM_UTILITIES ?= $(wildcard $(MM_UTILITIES_DIR)/.) 36 | 37 | # Store the current path for later use 38 | PWD ?= $(shell pwd) 39 | 40 | # Ensure that npm (and thus node) is installed. 41 | ifneq ($(HAS_WEBAPP),) 42 | ifeq ($(NPM),) 43 | $(error "npm is not available: see https://www.npmjs.com/get-npm") 44 | endif 45 | endif 46 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/moussetc/mattermost-plugin-giphy 2 | 3 | go 1.23.0 4 | 5 | require ( 6 | github.com/golang/mock v1.6.0 7 | github.com/mattermost/mattermost/server/public v0.1.11 8 | github.com/mitchellh/mapstructure v1.5.0 9 | github.com/pkg/errors v0.9.1 10 | github.com/stretchr/testify v1.10.0 11 | ) 12 | 13 | require ( 14 | filippo.io/edwards25519 v1.1.0 // indirect 15 | github.com/beevik/etree v1.1.0 // indirect 16 | github.com/blang/semver/v4 v4.0.0 // indirect 17 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect 18 | github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a // indirect 19 | github.com/fatih/color v1.18.0 // indirect 20 | github.com/francoispqt/gojay v1.2.13 // indirect 21 | github.com/go-asn1-ber/asn1-ber v1.5.7 // indirect 22 | github.com/go-sql-driver/mysql v1.8.1 // indirect 23 | github.com/golang/protobuf v1.5.4 // indirect 24 | github.com/google/uuid v1.6.0 // indirect 25 | github.com/gorilla/websocket v1.5.3 // indirect 26 | github.com/hashicorp/errwrap v1.1.0 // indirect 27 | github.com/hashicorp/go-hclog v1.6.3 // indirect 28 | github.com/hashicorp/go-multierror v1.1.1 // indirect 29 | github.com/hashicorp/go-plugin v1.6.3 // indirect 30 | github.com/hashicorp/yamux v0.1.2 // indirect 31 | github.com/jonboulle/clockwork v0.2.2 // indirect 32 | github.com/lib/pq v1.10.9 // indirect 33 | github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 // indirect 34 | github.com/mattermost/gosaml2 v0.8.0 // indirect 35 | github.com/mattermost/ldap v0.0.0-20231116144001-0f480c025956 // indirect 36 | github.com/mattermost/logr/v2 v2.0.21 // indirect 37 | github.com/mattermost/xml-roundtrip-validator v0.1.0 // indirect 38 | github.com/mattn/go-colorable v0.1.14 // indirect 39 | github.com/mattn/go-isatty v0.0.20 // indirect 40 | github.com/oklog/run v1.1.0 // indirect 41 | github.com/pborman/uuid v1.2.1 // indirect 42 | github.com/pelletier/go-toml v1.9.5 // indirect 43 | github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c // indirect 44 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect 45 | github.com/russellhaering/goxmldsig v1.2.0 // indirect 46 | github.com/sirupsen/logrus v1.9.3 // indirect 47 | github.com/stretchr/objx v0.5.2 // indirect 48 | github.com/tinylib/msgp v1.2.5 // indirect 49 | github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect 50 | github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect 51 | github.com/wiggin77/merror v1.0.5 // indirect 52 | github.com/wiggin77/srslog v1.0.1 // indirect 53 | golang.org/x/crypto v0.36.0 // indirect 54 | golang.org/x/mod v0.22.0 // indirect 55 | golang.org/x/net v0.38.0 // indirect 56 | golang.org/x/sys v0.31.0 // indirect 57 | golang.org/x/text v0.23.0 // indirect 58 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 // indirect 59 | google.golang.org/grpc v1.70.0 // indirect 60 | google.golang.org/protobuf v1.36.4 // indirect 61 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect 62 | gopkg.in/yaml.v2 v2.4.0 // indirect 63 | gopkg.in/yaml.v3 v3.0.1 // indirect 64 | ) 65 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 3 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 4 | cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= 5 | dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= 6 | dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= 7 | dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= 8 | dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= 9 | filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= 10 | filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= 11 | git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= 12 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 13 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= 14 | github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= 15 | github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= 16 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 17 | github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= 18 | github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= 19 | github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= 20 | github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= 21 | github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8= 22 | github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= 23 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 24 | github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= 25 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 26 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 27 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 28 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 29 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 30 | github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= 31 | github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a h1:etIrTD8BQqzColk9nKRusM9um5+1q0iOEJLqfBMIK64= 32 | github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a/go.mod h1:emQhSYTXqB0xxjLITTw4EaWZ+8IIQYw+kx9GqNUKdLg= 33 | github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= 34 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= 35 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= 36 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= 37 | github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk= 38 | github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY= 39 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 40 | github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= 41 | github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= 42 | github.com/go-asn1-ber/asn1-ber v1.5.7 h1:DTX+lbVTWaTw1hQ+PbZPlnDZPEIs0SS/GCZAl535dDk= 43 | github.com/go-asn1-ber/asn1-ber v1.5.7/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= 44 | github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= 45 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= 46 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 47 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= 48 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= 49 | github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= 50 | github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= 51 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 52 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 53 | github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= 54 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 55 | github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 56 | github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= 57 | github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= 58 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 59 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 60 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 61 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 62 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= 63 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 64 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 65 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 66 | github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= 67 | github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= 68 | github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= 69 | github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= 70 | github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 71 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 72 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 73 | github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= 74 | github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= 75 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 76 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 77 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 78 | github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= 79 | github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= 80 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 81 | github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= 82 | github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 83 | github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= 84 | github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= 85 | github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= 86 | github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= 87 | github.com/hashicorp/go-plugin v1.6.3 h1:xgHB+ZUSYeuJi96WtxEjzi23uh7YQpznjGh0U0UUrwg= 88 | github.com/hashicorp/go-plugin v1.6.3/go.mod h1:MRobyh+Wc/nYy1V4KAXUiYfzxoYhs7V1mlH1Z7iY2h0= 89 | github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= 90 | github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= 91 | github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= 92 | github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= 93 | github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= 94 | github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= 95 | github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= 96 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 97 | github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= 98 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 99 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 100 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 101 | github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= 102 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 103 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 104 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 105 | github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 106 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 107 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 108 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 109 | github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= 110 | github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= 111 | github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= 112 | github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= 113 | github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 h1:Khvh6waxG1cHc4Cz5ef9n3XVCxRWpAKUtqg9PJl5+y8= 114 | github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404/go.mod h1:RyS7FDNQlzF1PsjbJWHRI35exqaKGSO9qD4iv8QjE34= 115 | github.com/mattermost/gosaml2 v0.8.0 h1:nkYiByawqwJ7KncK1LDWKwTx5aRarBTQsmH+XcCVsWQ= 116 | github.com/mattermost/gosaml2 v0.8.0/go.mod h1:1nMAdE2Psxaz+pj79Oytayi+hC3aZUi3SmJQlIe+sLM= 117 | github.com/mattermost/ldap v0.0.0-20231116144001-0f480c025956 h1:Y1Tu/swM31pVwwb2BTCsOdamENjjWCI6qmfHLbk6OZI= 118 | github.com/mattermost/ldap v0.0.0-20231116144001-0f480c025956/go.mod h1:SRl30Lb7/QoYyohYeVBuqYvvmXSZJxZgiV3Zf6VbxjI= 119 | github.com/mattermost/logr/v2 v2.0.21 h1:CMHsP+nrbRlEC4g7BwOk1GAnMtHkniFhlSQPXy52be4= 120 | github.com/mattermost/logr/v2 v2.0.21/go.mod h1:kZkB/zqKL9e+RY5gB3vGpsyenC+TpuiOenjMkvJJbzc= 121 | github.com/mattermost/mattermost/server/public v0.1.11 h1:qxn36BE1rk5lTiMrHCVjdEdeUcbkOy/fxFvlRVyK0rI= 122 | github.com/mattermost/mattermost/server/public v0.1.11/go.mod h1:h/rage94cF+ZWqDdVRaROXFUEPVyO3Wbq8tfKRPRL0s= 123 | github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= 124 | github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= 125 | github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= 126 | github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= 127 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= 128 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= 129 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 130 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= 131 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 132 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 133 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 134 | github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= 135 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 136 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 137 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 138 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 139 | github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= 140 | github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= 141 | github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= 142 | github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= 143 | github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= 144 | github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw= 145 | github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= 146 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= 147 | github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= 148 | github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= 149 | github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY= 150 | github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= 151 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 152 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 153 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 154 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 155 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 156 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 157 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 158 | github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 159 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 160 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 161 | github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 162 | github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= 163 | github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= 164 | github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= 165 | github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= 166 | github.com/russellhaering/goxmldsig v1.2.0 h1:Y6GTTc9Un5hCxSzVz4UIWQ/zuVwDvzJk80guqzwx6Vg= 167 | github.com/russellhaering/goxmldsig v1.2.0/go.mod h1:gM4MDENBQf7M+V824SGfyIUVFWydB7n0KkEubVJl+Tw= 168 | github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= 169 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 170 | github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= 171 | github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= 172 | github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= 173 | github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= 174 | github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= 175 | github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= 176 | github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= 177 | github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= 178 | github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= 179 | github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= 180 | github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= 181 | github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= 182 | github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= 183 | github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= 184 | github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= 185 | github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= 186 | github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= 187 | github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= 188 | github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= 189 | github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= 190 | github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= 191 | github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= 192 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= 193 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= 194 | github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= 195 | github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= 196 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 197 | github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= 198 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 199 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 200 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 201 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 202 | github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= 203 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 204 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 205 | github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= 206 | github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po= 207 | github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= 208 | github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= 209 | github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= 210 | github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= 211 | github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= 212 | github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= 213 | github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= 214 | github.com/wiggin77/merror v1.0.5 h1:P+lzicsn4vPMycAf2mFf7Zk6G9eco5N+jB1qJ2XW3ME= 215 | github.com/wiggin77/merror v1.0.5/go.mod h1:H2ETSu7/bPE0Ymf4bEwdUoo73OOEkdClnoRisfw0Nm0= 216 | github.com/wiggin77/srslog v1.0.1 h1:gA2XjSMy3DrRdX9UqLuDtuVAAshb8bE1NhX1YK0Qe+8= 217 | github.com/wiggin77/srslog v1.0.1/go.mod h1:fehkyYDq1QfuYn60TDPu9YdY2bB85VUW2mvN1WynEls= 218 | github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 219 | go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= 220 | go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= 221 | go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= 222 | go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= 223 | go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= 224 | go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= 225 | go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= 226 | go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= 227 | go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= 228 | go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= 229 | go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= 230 | go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= 231 | golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= 232 | golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 233 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 234 | golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 235 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 236 | golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= 237 | golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= 238 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 239 | golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 240 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 241 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 242 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 243 | golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= 244 | golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= 245 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 246 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 247 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 248 | golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 249 | golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 250 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 251 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 252 | golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 253 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 254 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 255 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= 256 | golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= 257 | golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= 258 | golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= 259 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 260 | golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 261 | golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 262 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 263 | golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= 264 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 265 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 266 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 267 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 268 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 269 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 270 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 271 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 272 | golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 273 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 274 | golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 275 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 276 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 277 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 278 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 279 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 280 | golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 281 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 282 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 283 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 284 | golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 285 | golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 286 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 287 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 288 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= 289 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 290 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 291 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 292 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 293 | golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 294 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 295 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 296 | golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= 297 | golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= 298 | golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 299 | golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 300 | golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 301 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 302 | golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 303 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 304 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 305 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 306 | golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= 307 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 308 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 309 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 310 | google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= 311 | google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= 312 | google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= 313 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 314 | google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 315 | google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 316 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 317 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 318 | google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 319 | google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 320 | google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= 321 | google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 322 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47 h1:91mG8dNTpkC0uChJUQ9zCiRqx3GEEFOWaRZ0mI6Oj2I= 323 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250124145028-65684f501c47/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= 324 | google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= 325 | google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= 326 | google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= 327 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 328 | google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= 329 | google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= 330 | google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM= 331 | google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 332 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 333 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 334 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 335 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 336 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 337 | gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 338 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= 339 | gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= 340 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 341 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 342 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 343 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 344 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 345 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 346 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 347 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 348 | grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= 349 | honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 350 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 351 | honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 352 | sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= 353 | sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= 354 | -------------------------------------------------------------------------------- /plugin.go: -------------------------------------------------------------------------------- 1 | package root 2 | 3 | import ( 4 | _ "embed" // Need to embed manifest file 5 | "encoding/json" 6 | "strings" 7 | 8 | "github.com/mattermost/mattermost/server/public/model" 9 | ) 10 | 11 | //go:embed plugin.json 12 | var manifestString string 13 | 14 | var Manifest model.Manifest 15 | 16 | func init() { 17 | _ = json.NewDecoder(strings.NewReader(manifestString)).Decode(&Manifest) 18 | } 19 | -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "com.github.moussetc.mattermost.plugin.giphy", 3 | "name": "GIF commands", 4 | "description": "Add GIF slash commands from Giphy or Tenor", 5 | "version": "4.0.0", 6 | "min_server_version": "6.5.0", 7 | "homepage_url": "https://github.com/moussetc/mattermost-plugin-giphy/", 8 | "support_url": "https://github.com/moussetc/mattermost-plugin-giphy/issues", 9 | "release_notes_url": "https://github.com/moussetc/mattermost-plugin-giphy/releases/v3.0.0", 10 | "icon_path": "assets/icon.svg", 11 | "server": { 12 | "executables": { 13 | "linux-amd64": "server/dist/plugin-linux-amd64", 14 | "linux-arm64": "server/dist/plugin-linux-arm64", 15 | "darwin-amd64": "server/dist/plugin-darwin-amd64", 16 | "darwin-arm64": "server/dist/plugin-darwin-arm64", 17 | "windows-amd64": "server/dist/plugin-windows-amd64.exe" 18 | }, 19 | "executable": "server/dist/plugin-freebsd-amd64.exe" 20 | }, 21 | "settings_schema": { 22 | "settings": [ 23 | { 24 | "key": "DisplayMode", 25 | "type": "radio", 26 | "display_name": "Display the GIF as:", 27 | "default": "embedded", 28 | "options": [ 29 | { 30 | "display_name": "Embedded image (the GIF cannot be collapsed)", 31 | "value": "embedded" 32 | }, 33 | { 34 | "display_name": "Collapsible image preview (the full URL is displayed, requires link previews to be enabled)", 35 | "value": "full_url" 36 | } 37 | ], 38 | "help_text": "It is not yet possible to collapse an embedded image in Mattermost: use the Full URL option if preferred and keep an eye on [this issue](https://mattermost.atlassian.net/browse/MM-12290).\n\n To enable link previews, go to **System Console > Site Configuration > Posts > Enable Link Previews**." 39 | }, 40 | { 41 | "key": "Provider", 42 | "type": "radio", 43 | "display_name": "GIF Provider:", 44 | "default": "giphy", 45 | "options": [ 46 | { 47 | "display_name": "GIPHY", 48 | "value": "giphy" 49 | }, 50 | { 51 | "display_name": "Tenor", 52 | "value": "tenor" 53 | } 54 | ] 55 | }, 56 | { 57 | "key": "APIKey", 58 | "type": "text", 59 | "display_name": "GIPHY or Tenor API Key:", 60 | "help_text": "Configure your own API key. To get your own API key, follow [these instructions for Giphy](https://developers.giphy.com/docs/api#quick-start-guide) or [these for Tenor](https://developers.google.com/tenor/guides/quickstart#setup)." 61 | }, 62 | { 63 | "key": "Rating", 64 | "type": "dropdown", 65 | "display_name": "Content Rating:", 66 | "help_text": "Choose a MPAA-style rating", 67 | "options": [ 68 | { 69 | "display_name": "No rating (no content filtering)", 70 | "value": "none" 71 | }, 72 | { 73 | "display_name": "G", 74 | "value": "g" 75 | }, 76 | { 77 | "display_name": "PG", 78 | "value": "pg" 79 | }, 80 | { 81 | "display_name": "PG-13", 82 | "value": "pg-13" 83 | }, 84 | { 85 | "display_name": "R", 86 | "value": "r" 87 | } 88 | ] 89 | }, 90 | { 91 | "key": "Rendition", 92 | "type": "dropdown", 93 | "display_name": "GIPHY display style:", 94 | "help_text": "Select the style to display GIFs from GIPHY (more info [here](https://developers.giphy.com/docs/optional-settings/#rendition-guide)).", 95 | "default": "fixed_height_small", 96 | "options": [ 97 | { 98 | "display_name": "Height set to 200px. Good for mobile use.", 99 | "value": "fixed_height" 100 | }, 101 | { 102 | "display_name": "Static preview image for fixed_height.", 103 | "value": "fixed_height_still" 104 | }, 105 | { 106 | "display_name": "Height set to 100px. Good for mobile keyboards.", 107 | "value": "fixed_height_small" 108 | }, 109 | { 110 | "display_name": "Static preview image for fixed_height_small.", 111 | "value": "fixed_height_small_still" 112 | }, 113 | { 114 | "display_name": "Width set to 200px. Good for mobile use.", 115 | "value": "fixed_width" 116 | }, 117 | { 118 | "display_name": "Static preview image for fixed_width.", 119 | "value": "fixed_width_still" 120 | }, 121 | { 122 | "display_name": "Width set to 100px. Good for mobile keyboards.", 123 | "value": "fixed_width_small" 124 | }, 125 | { 126 | "display_name": "Static preview image for fixed_width_small.", 127 | "value": "fixed_width_small_still" 128 | }, 129 | { 130 | "display_name": "File size under 2mb.", 131 | "value": "downsized" 132 | }, 133 | { 134 | "display_name": "File size under 8mb.", 135 | "value": "downsized_large" 136 | }, 137 | { 138 | "display_name": "Static preview image for downsized.", 139 | "value": "downsized_still" 140 | }, 141 | { 142 | "display_name": "Original file size and file dimensions. Good for desktop use.", 143 | "value": "original" 144 | }, 145 | { 146 | "display_name": "Preview image for original.", 147 | "value": "original_still" 148 | }, 149 | { 150 | "display_name": "Duration set to loop for 15 seconds. Only recommended for this exact use case.", 151 | "value": "looping" 152 | } 153 | ] 154 | }, 155 | { 156 | "key": "RenditionTenor", 157 | "type": "dropdown", 158 | "display_name": "Tenor display style:", 159 | "help_text": "Select the style to display GIFs from Tenor (more info [here](https://developers.google.com/tenor/guides/response-objects-and-errors#content-formats)).", 160 | "default": "mediumgif", 161 | "options": [ 162 | { 163 | "display_name": "Original: High quality GIF format, largest file size available. Use this size for GIF shares on desktop.", 164 | "value": "gif" 165 | }, 166 | { 167 | "display_name": "Medium: Small reduction in size of the original format.", 168 | "value": "mediumgif" 169 | }, 170 | { 171 | "display_name": "Tiny: Reduced size of the original format, up to 220px wide. Good for mobile.", 172 | "value": "tinygif" 173 | } 174 | ] 175 | }, 176 | { 177 | "key": "Language", 178 | "type": "dropdown", 179 | "display_name": "Language:", 180 | "help_text": "Select the language used to search GIFs (more info [here](https://developers.giphy.com/docs/optional-settings/#language-support)).", 181 | "default": "en", 182 | "options": [ 183 | { 184 | "display_name": "English", 185 | "value": "en" 186 | }, 187 | { 188 | "display_name": "Español", 189 | "value": "es" 190 | }, 191 | { 192 | "display_name": "Français", 193 | "value": "fr" 194 | }, 195 | { 196 | "display_name": "Português", 197 | "value": "pt" 198 | }, 199 | { 200 | "display_name": "Bahasa Indonesia", 201 | "value": "id" 202 | }, 203 | { 204 | "display_name": "العربية", 205 | "value": "ar" 206 | }, 207 | { 208 | "display_name": "Türkçe", 209 | "value": "tr" 210 | }, 211 | { 212 | "display_name": "ไทย", 213 | "value": "th" 214 | }, 215 | { 216 | "display_name": "Tiếng Việt", 217 | "value": "vi" 218 | }, 219 | { 220 | "display_name": "Deutsch", 221 | "value": "de" 222 | }, 223 | { 224 | "display_name": "Italiano", 225 | "value": "it" 226 | }, 227 | { 228 | "display_name": "日本語 (にほんご)", 229 | "value": "ja" 230 | }, 231 | { 232 | "display_name": "Chinese Simplified", 233 | "value": "zh-CN" 234 | }, 235 | { 236 | "display_name": "Chinese Traditional", 237 | "value": "zh-TW" 238 | }, 239 | { 240 | "display_name": "русский", 241 | "value": "ru" 242 | }, 243 | { 244 | "display_name": "한국어", 245 | "value": "ko" 246 | }, 247 | { 248 | "display_name": "Polszczyzna", 249 | "value": "pl" 250 | }, 251 | { 252 | "display_name": "Nederlands", 253 | "value": "nl" 254 | }, 255 | { 256 | "display_name": "Română", 257 | "value": "ro" 258 | }, 259 | { 260 | "display_name": "magyar", 261 | "value": "hu" 262 | }, 263 | { 264 | "display_name": "Svenska", 265 | "value": "sv" 266 | }, 267 | { 268 | "display_name": "čeština", 269 | "value": "cs" 270 | }, 271 | { 272 | "display_name": "हिन्दी, हिंदी", 273 | "value": "hi" 274 | }, 275 | { 276 | "display_name": "বাংলা", 277 | "value": "bn" 278 | }, 279 | { 280 | "display_name": "dansk", 281 | "value": "da" 282 | }, 283 | { 284 | "display_name": "فارسی", 285 | "value": "fa" 286 | }, 287 | { 288 | "display_name": "Filipino", 289 | "value": "tl" 290 | }, 291 | { 292 | "display_name": "suomi", 293 | "value": "fi" 294 | }, 295 | { 296 | "display_name": "עברית", 297 | "value": "he" 298 | }, 299 | { 300 | "display_name": "بهاس ملايو", 301 | "value": "ms" 302 | }, 303 | { 304 | "display_name": "Norsk", 305 | "value": "no" 306 | }, 307 | { 308 | "display_name": "Українська", 309 | "value": "uk" 310 | } 311 | ] 312 | }, 313 | { 314 | "key": "RandomSearch", 315 | "type": "bool", 316 | "display_name": "Random:", 317 | "help_text": "If deactivated, the same search will return the same sequence of GIFs. Note: only pseudo-randomization is available for Tenor", 318 | "default": true 319 | }, 320 | { 321 | "key": "DisablePostingWithoutPreview", 322 | "type": "bool", 323 | "display_name": "Force GIF preview before posting (force /gifs):", 324 | "help_text": "If deactivated, both /gif (no preview before posting) and /gifs (preview) will be available. This option is activated by default to prevent the accidental posting of inappropriate GIFs from a provider that does not allow content rating.", 325 | "default": true 326 | } 327 | ], 328 | "footer": "Powered by GIPHY and Tenor.\n\n * To report an issue, make a suggestion or a contribution, or fork your own version of the plugin, [check the repository](https://github.com/moussetc/mattermost-plugin-giphy).\n" 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /public/powered-by-giphy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moussetc/mattermost-plugin-giphy/2076bdc881454d5eb722c23a29f23572a7d9aca2/public/powered-by-giphy.png -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | coverage.txt 2 | .depensure 3 | -------------------------------------------------------------------------------- /server/commands.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "strings" 7 | 8 | manifest "github.com/moussetc/mattermost-plugin-giphy" 9 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 10 | 11 | "github.com/mattermost/mattermost/server/public/model" 12 | 13 | "github.com/pkg/errors" 14 | ) 15 | 16 | // Contains all that's related to the basic Post command 17 | 18 | // Triggers used to define slash commands 19 | const ( 20 | triggerGif = "gif" 21 | triggerGifs = "gifs" 22 | ) 23 | 24 | func (p *Plugin) RegisterCommands() error { 25 | unregisterErr := p.API.UnregisterCommand("", triggerGif) 26 | if unregisterErr != nil { 27 | p.API.LogWarn("Unable to unregister the command", "trigger", triggerGif, "error", unregisterErr.Error()) 28 | } 29 | unregisterErr = p.API.UnregisterCommand("", triggerGifs) 30 | if unregisterErr != nil { 31 | p.API.LogWarn("Unable to unregister the command", "trigger", triggerGifs, "error", unregisterErr.Error()) 32 | } 33 | 34 | config := p.getConfiguration() 35 | if config.CommandTriggerGif != "" { 36 | err := p.API.RegisterCommand(&model.Command{ 37 | Trigger: config.CommandTriggerGif, 38 | Description: "Post a GIF matching your search", 39 | DisplayName: "Giphy Search", 40 | AutoComplete: true, 41 | AutoCompleteDesc: "Post a GIF matching your search", 42 | AutoCompleteHint: getHintMessage(config.CommandTriggerGif), 43 | }) 44 | if err != nil { 45 | return errors.Wrap(err, "Unable to define the following command: "+config.CommandTriggerGif) 46 | } 47 | } 48 | if config.CommandTriggerGifWithPreview != "" { 49 | err := p.API.RegisterCommand(&model.Command{ 50 | Trigger: config.CommandTriggerGifWithPreview, 51 | Description: "Preview a GIF", 52 | DisplayName: "Giphy Shuffle", 53 | AutoComplete: true, 54 | AutoCompleteDesc: "Let you preview and shuffle a GIF before posting for real", 55 | AutoCompleteHint: getHintMessage(config.CommandTriggerGifWithPreview), 56 | }) 57 | if err != nil { 58 | return errors.Wrap(err, "Unable to define the following command: "+config.CommandTriggerGifWithPreview) 59 | } 60 | } 61 | return nil 62 | } 63 | 64 | func parseCommandLine(commandLine, trigger string) (keywords, caption string, err error) { 65 | reg := regexp.MustCompile("^\\s*(?P(\"([^\\s\"]+\\s*)+\")+|([^\\s\"]+\\s*)+)(?P\\s+\"(\\s*[^\\s\"]+\\s*)+\")?\\s*$") 66 | matchIndexes := reg.FindStringSubmatch(strings.Replace(commandLine, "/"+trigger, "", 1)) 67 | if matchIndexes == nil { 68 | return "", "", fmt.Errorf("could not read the command, try one of the following syntax: /%s %s", trigger, getHintMessage(trigger)) 69 | } 70 | results := make(map[string]string) 71 | for i, name := range reg.SubexpNames() { 72 | results[name] = matchIndexes[i] 73 | } 74 | return strings.Trim(strings.TrimSpace(results["keywords"]), "\""), strings.Trim(strings.TrimSpace(results["caption"]), "\""), nil 75 | } 76 | 77 | // executeCommandGif returns a public post containing a matching GIF 78 | func (p *Plugin) executeCommandGif(keywords, caption string, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { 79 | cursor := "" 80 | gifURLs, errGif := p.gifProvider.GetGifURL(keywords, &cursor, p.configuration.RandomSearch) 81 | if errGif != nil { 82 | p.API.LogWarn("Error while trying to get GIF URL", "error", errGif.Error()) 83 | return nil, errGif 84 | } 85 | if len(gifURLs) < 1 { 86 | return p.handleNoGifFound(keywords, args) 87 | } 88 | 89 | text := generateGifCaption(p.getConfiguration().DisplayMode, keywords, caption, gifURLs[0], p.gifProvider.GetAttributionMessage()) 90 | return &model.CommandResponse{ResponseType: model.CommandResponseTypeInChannel, Text: text}, nil 91 | } 92 | 93 | // executeCommandGifWithPreview returns an ephemeral post with one GIF that can either be posted, shuffled or canceled 94 | func (p *Plugin) executeCommandGifWithPreview(keywords, caption string, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { 95 | cursor := "" 96 | // Load a first page of GIFs 97 | gifURLs, errGif := p.gifProvider.GetGifURL(keywords, &cursor, p.configuration.RandomSearch) 98 | if errGif != nil { 99 | p.API.LogWarn("Error while trying to get GIF URL", "error", errGif.Error()) 100 | return nil, errGif 101 | } 102 | if len(gifURLs) < 1 { 103 | return p.handleNoGifFound(keywords, args) 104 | } 105 | 106 | post := p.generateGifPost(p.botID, keywords, caption, gifURLs[0], args.ChannelId, args.RootId, p.gifProvider.GetAttributionMessage()) 107 | // Only embedded display mode works inside an ephemeral post 108 | post.Message = generateGifCaption(pluginConf.DisplayModeEmbedded, keywords, caption, gifURLs[0], p.gifProvider.GetAttributionMessage()) 109 | post.SetProps(map[string]interface{}{ 110 | "attachments": generatePreviewPostAttachments(keywords, caption, cursor, args.RootId, gifURLs, 0), 111 | }) 112 | p.API.SendEphemeralPost(args.UserId, post) 113 | 114 | return &model.CommandResponse{}, nil 115 | } 116 | 117 | func (p *Plugin) handleNoGifFound(keywords string, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { 118 | // Create ephemeral post directly rather than with CommandResponse, so the bot can be the author 119 | post := &model.Post{ 120 | Message: "No GIFs found for '" + keywords + "'", 121 | UserId: p.botID, 122 | ChannelId: args.ChannelId, 123 | RootId: args.RootId, 124 | } 125 | 126 | p.API.SendEphemeralPost(args.UserId, post) 127 | 128 | return &model.CommandResponse{}, nil 129 | } 130 | 131 | func getHintMessage(trigger string) string { 132 | return "[happy kitty] or /" + trigger + " \"[happy kitty]\" \"[This is a custom caption]\"" 133 | } 134 | 135 | func generateGifCaption(displayMode, keywords, caption, gifURL, attributionMessage string) string { 136 | captionOrKeywords := caption 137 | if caption == "" { 138 | captionOrKeywords = fmt.Sprintf("**/gif [%s](%s)**", keywords, gifURL) 139 | } 140 | formattedAttributionMessage := "" 141 | if attributionMessage != "" { 142 | formattedAttributionMessage = "*" + attributionMessage + "*\n" 143 | } 144 | if displayMode == pluginConf.DisplayModeFullURL { 145 | return fmt.Sprintf("%s \n%s%s", captionOrKeywords, gifURL, formattedAttributionMessage) 146 | } 147 | 148 | return fmt.Sprintf("%s \n%s![GIF for '%s'](%s)", captionOrKeywords, formattedAttributionMessage, keywords, gifURL) 149 | } 150 | 151 | func (p *Plugin) generateGifPost(userID, keywords, caption, gifURL, channelID, rootID, attributionMessage string) *model.Post { 152 | return &model.Post{ 153 | Message: generateGifCaption(p.getConfiguration().DisplayMode, keywords, caption, gifURL, attributionMessage), 154 | UserId: userID, 155 | ChannelId: channelID, 156 | RootId: rootID, 157 | } 158 | } 159 | 160 | func generatePreviewPostAttachments(keywords, caption, searchCursor, rootID string, gifURLs []string, currentGifIndex int) []*model.SlackAttachment { 161 | actionContext := map[string]interface{}{ 162 | contextRootID: rootID, 163 | contextKeywords: keywords, 164 | contextCaption: caption, 165 | contextAPICursor: searchCursor, 166 | contextGifURLs: gifURLs, 167 | contextCurrentIndex: currentGifIndex, 168 | } 169 | 170 | actions := []*model.PostAction{} 171 | actions = append(actions, generateButton("Cancel", URLCancel, "default", actionContext)) 172 | if currentGifIndex > 0 { 173 | actions = append(actions, generateButton("Previous", URLPrevious, "default", actionContext)) 174 | } 175 | actions = append(actions, generateButton("Shuffle", URLShuffle, "primary", actionContext)) 176 | actions = append(actions, generateButton("Send", URLSend, "good", actionContext)) 177 | 178 | attachments := []*model.SlackAttachment{} 179 | attachments = append(attachments, &model.SlackAttachment{ 180 | Actions: actions, 181 | }) 182 | 183 | return attachments 184 | } 185 | 186 | // Generate an attachment for an action Button that will point to a plugin HTTP handler 187 | func generateButton(name string, urlAction string, style string, context map[string]interface{}) *model.PostAction { 188 | return &model.PostAction{ 189 | Name: name, 190 | Type: model.PostActionTypeButton, 191 | Style: style, 192 | Integration: &model.PostActionIntegration{ 193 | URL: fmt.Sprintf("/plugins/%s%s", manifest.Manifest.Id, urlAction), 194 | Context: context, 195 | }, 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /server/commands_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | 10 | "github.com/mattermost/mattermost/server/public/model" 11 | "github.com/mattermost/mattermost/server/public/plugin/plugintest" 12 | "github.com/mattermost/mattermost/server/public/plugin/plugintest/mock" 13 | ) 14 | 15 | var testArgs = &model.CommandArgs{ 16 | RootId: "42", 17 | ChannelId: "43", 18 | UserId: testUserID, 19 | } 20 | 21 | func TestRegisterCommandsShouldFailWhenRegisterGifCommandFails(t *testing.T) { 22 | api := &plugintest.API{} 23 | config := generateMockPluginConfig() 24 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(config)) 25 | api.On("RegisterCommand", mock.MatchedBy(func(command *model.Command) bool { return command.Trigger == config.CommandTriggerGif })).Return(errors.New("fail mock register command")) 26 | api.On("RegisterCommand", mock.MatchedBy(func(command *model.Command) bool { return command.Trigger == config.CommandTriggerGifWithPreview })).Return(nil) 27 | api.On("UnregisterCommand", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil) 28 | p := Plugin{} 29 | p.configuration = &config 30 | p.SetAPI(api) 31 | 32 | assert.NotNil(t, p.RegisterCommands()) 33 | } 34 | 35 | func TestRegisterCommandsShouldFailWhenRegisterGifPreviewCommandFails(t *testing.T) { 36 | api := &plugintest.API{} 37 | config := generateMockPluginConfig() 38 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(config)) 39 | api.On("RegisterCommand", mock.MatchedBy(func(command *model.Command) bool { return command.Trigger == config.CommandTriggerGif })).Return(nil) 40 | api.On("RegisterCommand", mock.MatchedBy(func(command *model.Command) bool { return command.Trigger == config.CommandTriggerGifWithPreview })).Return(errors.New("fail mock register command")) 41 | api.On("UnregisterCommand", mock.Anything, mock.Anything).Return(nil) 42 | p := Plugin{} 43 | p.configuration = &config 44 | p.SetAPI(api) 45 | 46 | assert.NotNil(t, p.RegisterCommands()) 47 | } 48 | 49 | func TestExecuteCommandGifShouldReturnInChannelResponseWhenSearchSucceeds(t *testing.T) { 50 | _, p := initMockAPI() 51 | p.gifProvider = newMockGifProvider() 52 | 53 | response, err := p.executeCommandGif(testKeywords, testCaption, testArgs) 54 | 55 | assert.Nil(t, err) 56 | assert.NotNil(t, response) 57 | assert.Equal(t, model.CommandResponseTypeInChannel, response.ResponseType) 58 | assert.True(t, strings.Contains(response.Text, testKeywords)) 59 | assert.True(t, strings.Contains(response.Text, testCaption)) 60 | } 61 | 62 | func TestExecuteCommandGifShouldSendEphemeralPostWhenSearchReturnsNoResult(t *testing.T) { 63 | api, p := initMockAPI() 64 | p.gifProvider = &emptyGifProvider{} 65 | api.On("SendEphemeralPost", mock.Anything, mock.Anything).Return(nil) 66 | 67 | response, err := p.executeCommandGif(testKeywords, testCaption, testArgs) 68 | 69 | assert.Nil(t, err) 70 | assert.NotNil(t, response) 71 | api.AssertNumberOfCalls(t, "SendEphemeralPost", 1) 72 | api.AssertCalled(t, "SendEphemeralPost", 73 | mock.MatchedBy(func(uID string) bool { 74 | return uID == testArgs.UserId 75 | }), 76 | mock.MatchedBy(func(post *model.Post) bool { 77 | return post != nil && 78 | post.ChannelId == testArgs.ChannelId && 79 | post.UserId == p.botID && 80 | strings.Contains(post.Message, "found") && 81 | strings.Contains(post.Message, testKeywords) 82 | })) 83 | } 84 | 85 | func TestExecuteCommandGifShouldLogAndFailWhenSearchFails(t *testing.T) { 86 | api, p := initMockAPI() 87 | errorMessage := "ARGHHHH" 88 | p.gifProvider = &mockGifProviderFail{errorMessage} 89 | api.On("LogWarn", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil) 90 | 91 | response, err := p.executeCommandGif("mayhem", "guy", testArgs) 92 | assert.NotNil(t, err) 93 | assert.Empty(t, response) 94 | assert.Contains(t, err.DetailedError, errorMessage) 95 | api.AssertNumberOfCalls(t, "LogWarn", 1) 96 | } 97 | 98 | func TestExecuteCommandGifWithPreviewShouldPostAnEphemeralGifPostWhenSearchSucceeds(t *testing.T) { 99 | api, p := initMockAPI() 100 | p.gifProvider = newMockGifProvider() 101 | 102 | var recordCreationPost *model.Post 103 | api.On("SendEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("*model.Post")).Return(nil, nil).Run(func(args mock.Arguments) { 104 | recordCreationPost = args.Get(1).(*model.Post) 105 | }) 106 | 107 | response, err := p.executeCommandGifWithPreview(testKeywords, testCaption, testArgs) 108 | 109 | assert.Nil(t, err) 110 | assert.NotNil(t, response) 111 | assert.Equal(t, "", response.ResponseType) 112 | assert.NotNil(t, recordCreationPost) 113 | assert.True(t, strings.Contains(recordCreationPost.Message, testKeywords)) 114 | assert.True(t, strings.Contains(recordCreationPost.Message, testCaption)) 115 | assert.Equal(t, recordCreationPost.RootId, testArgs.RootId) 116 | assert.Equal(t, recordCreationPost.ChannelId, testArgs.ChannelId) 117 | } 118 | 119 | func TestExecuteCommandGifWithPreviewShouldReturnEphemeralResponseWhenSearchReturnsNoResult(t *testing.T) { 120 | api, p := initMockAPI() 121 | p.gifProvider = &emptyGifProvider{} 122 | api.On("SendEphemeralPost", mock.Anything, mock.Anything).Return(nil) 123 | 124 | response, err := p.executeCommandGifWithPreview(testKeywords, testCaption, testArgs) 125 | 126 | assert.Nil(t, err) 127 | assert.NotNil(t, response) 128 | api.AssertNumberOfCalls(t, "SendEphemeralPost", 1) 129 | api.AssertCalled(t, "SendEphemeralPost", 130 | mock.MatchedBy(func(uID string) bool { return uID == testArgs.UserId }), 131 | mock.MatchedBy(func(post *model.Post) bool { 132 | return post != nil && 133 | post.ChannelId == testArgs.ChannelId && 134 | post.UserId == p.botID && 135 | strings.Contains(post.Message, "found") && 136 | strings.Contains(post.Message, testKeywords) 137 | })) 138 | } 139 | 140 | func TestExecuteCommandGifWithPreviewShouldLogAndFailWhenSearchFails(t *testing.T) { 141 | api, p := initMockAPI() 142 | p.gifProvider = &mockGifProviderFail{"mockError"} 143 | api.On("LogWarn", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil) 144 | 145 | response, err := p.executeCommandGifWithPreview("hello", "", nil) 146 | 147 | assert.NotNil(t, err) 148 | assert.Contains(t, err.Error(), "mockError") 149 | assert.Nil(t, response) 150 | api.AssertNumberOfCalls(t, "LogWarn", 1) 151 | } 152 | 153 | func TestGeneratePreviewPostAttachments(t *testing.T) { 154 | gifURLs := []string{testGifURLPrevious, testGifURL} 155 | attachments := generatePreviewPostAttachments(testKeywords, testCaption, testCursor, testRootID, gifURLs, 0) 156 | 157 | assert.NotNil(t, attachments) 158 | assert.Len(t, attachments, 1) 159 | attachment := attachments[0] 160 | assert.NotNil(t, attachment) 161 | actions := attachment.Actions 162 | assert.NotNil(t, actions) 163 | assert.Len(t, actions, 3) 164 | for i := 0; i < 3; i++ { 165 | assert.NotNil(t, actions[i].Integration) 166 | context := actions[i].Integration.Context 167 | assert.NotNil(t, context) 168 | assert.Equal(t, testKeywords, context[contextKeywords]) 169 | assert.Equal(t, gifURLs, context[contextGifURLs]) 170 | assert.Equal(t, testCursor, context[contextAPICursor]) 171 | assert.Equal(t, testRootID, context[contextRootID]) 172 | } 173 | } 174 | 175 | func TestParseCommandeLine(t *testing.T) { 176 | testCases := []struct { 177 | command string 178 | expectedError bool 179 | expectedKeywords string 180 | expectedCaption string 181 | }{ 182 | {command: "", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 183 | {command: "\"k1 k2 k3", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 184 | {command: "k1 k2 k3\"", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 185 | {command: "\"k1 k2 k3\" m1 m2 m3", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 186 | {command: "\"k1 k2 k3\" \"m1 m2 m3", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 187 | {command: "\"k1 k2 k3\" m1 m2 m3\"", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 188 | {command: "\"\" \"m1 m2 m3\"", expectedError: true, expectedKeywords: "", expectedCaption: ""}, 189 | {command: "unique", expectedError: false, expectedKeywords: "unique", expectedCaption: ""}, 190 | {command: "k1 k2", expectedError: false, expectedKeywords: "k1 k2", expectedCaption: ""}, 191 | {command: "\"k1 k2 k3\"", expectedError: false, expectedKeywords: "k1 k2 k3", expectedCaption: ""}, 192 | {command: "unique \"m1 m2 m3\"", expectedError: false, expectedKeywords: "unique", expectedCaption: "m1 m2 m3"}, 193 | {command: "\"k1 k2 k3\" \"m1 m2 m3\"", expectedError: false, expectedKeywords: "k1 k2 k3", expectedCaption: "m1 m2 m3"}, 194 | {command: "\"We\nlike\nnew\nlines\" \"yes\nwe\ndo\"", expectedError: false, expectedKeywords: "We\nlike\nnew\nlines", expectedCaption: "yes\nwe\ndo"}, 195 | {command: "\"Unicode supporté\\? ça c'est fort\" \"héhéhé !\"", expectedError: false, expectedKeywords: "Unicode supporté\\? ça c'est fort", expectedCaption: "héhéhé !"}, 196 | } 197 | for _, testCase := range testCases { 198 | keywords, caption, err := parseCommandLine(testCase.command, triggerGif) 199 | 200 | if testCase.expectedError { 201 | assert.NotNil(t, err, "Testing: "+testCase.command) 202 | } else { 203 | assert.Nil(t, err, "Testing: "+testCase.command) 204 | } 205 | assert.Equal(t, testCase.expectedKeywords, keywords, "Testing: "+testCase.command) 206 | assert.Equal(t, testCase.expectedCaption, caption, "Testing: "+testCase.command) 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /server/configuration.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "path/filepath" 6 | "strings" 7 | 8 | manifest "github.com/moussetc/mattermost-plugin-giphy" 9 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 10 | provider "github.com/moussetc/mattermost-plugin-giphy/server/internal/provider" 11 | 12 | "github.com/pkg/errors" 13 | 14 | "github.com/mattermost/mattermost/server/public/model" 15 | "github.com/mattermost/mattermost/server/public/pluginapi" 16 | ) 17 | 18 | // getConfiguration retrieves the active configuration under lock, making it safe to use 19 | // concurrently. The active configuration may change underneath the client of this method, but 20 | // the struct returned by this API call is considered immutable. 21 | func (p *Plugin) getConfiguration() *pluginConf.Configuration { 22 | p.configurationLock.RLock() 23 | defer p.configurationLock.RUnlock() 24 | 25 | if p.configuration == nil { 26 | return &pluginConf.Configuration{} 27 | } 28 | 29 | return p.configuration 30 | } 31 | 32 | // setConfiguration replaces the active configuration under lock. 33 | func (p *Plugin) setConfiguration(configuration *pluginConf.Configuration) { 34 | p.configurationLock.Lock() 35 | defer p.configurationLock.Unlock() 36 | 37 | if configuration != nil && p.configuration == configuration { 38 | panic("setConfiguration called with the existing configuration") 39 | } 40 | 41 | p.configuration = configuration 42 | } 43 | 44 | // OnConfigurationChange is invoked when configuration changes may have been made. 45 | func (p *Plugin) OnConfigurationChange() error { 46 | var configuration = new(pluginConf.Configuration) 47 | // Load the public configuration fields from the Mattermost server configuration. 48 | if err := p.API.LoadPluginConfiguration(configuration); err != nil { 49 | return errors.Wrap(err, "Failed to load plugin configuration") 50 | } 51 | p.setConfiguration(configuration) 52 | if configurationErr := configuration.IsValid(); configurationErr != nil { 53 | return configurationErr 54 | } 55 | 56 | rootURL := "" 57 | if siteURL := p.API.GetConfig().ServiceSettings.SiteURL; siteURL != nil { 58 | rootURL = strings.TrimSuffix(*siteURL, "/") 59 | } 60 | p.rootURL = fmt.Sprintf("%s/plugins/%s", rootURL, manifest.Manifest.Id) 61 | 62 | gifProvider, err := provider.GifProviderGenerator(*configuration, p.errorGenerator, p.rootURL) 63 | if err != nil { 64 | return err 65 | } 66 | 67 | p.gifProvider = gifProvider 68 | if configuration.DisablePostingWithoutPreview { 69 | // Force preview 70 | configuration.CommandTriggerGif = "" 71 | configuration.CommandTriggerGifWithPreview = triggerGif 72 | } else { 73 | // Slack-like syntax 74 | configuration.CommandTriggerGif = triggerGif 75 | configuration.CommandTriggerGifWithPreview = triggerGifs 76 | } 77 | 78 | // Re-register commands since a configuration change can impact the available commands 79 | return p.RegisterCommands() 80 | } 81 | 82 | func (p *Plugin) defineBot() error { 83 | bot := model.Bot{ 84 | Username: "gifcommandsplugin", 85 | DisplayName: manifest.Manifest.Name, 86 | Description: "Bot for the " + manifest.Manifest.Name + " plugin.", 87 | } 88 | botID, ensureBotError := p.pluginClient.Bot.EnsureBot(&bot, pluginapi.ProfileImagePath(filepath.Join("assets", "icon.png"))) 89 | if ensureBotError != nil { 90 | return errors.Wrap(ensureBotError, "failed to ensure GIF bot") 91 | } 92 | 93 | p.botID = botID 94 | 95 | return nil 96 | } 97 | -------------------------------------------------------------------------------- /server/configuration_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | manifest "github.com/moussetc/mattermost-plugin-giphy" 8 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 9 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 10 | 11 | "github.com/mattermost/mattermost/server/public/model" 12 | "github.com/mattermost/mattermost/server/public/plugin/plugintest" 13 | "github.com/mattermost/mattermost/server/public/plugin/plugintest/mock" 14 | "github.com/stretchr/testify/assert" 15 | ) 16 | 17 | func generateMocksForConfigurationTesting(pluginConfig *pluginConf.Configuration) *Plugin { 18 | api := &plugintest.API{} 19 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(*pluginConfig)) 20 | api.On("RegisterCommand", mock.Anything).Return(nil) 21 | api.On("UnregisterCommand", mock.Anything, mock.Anything).Return(nil) 22 | 23 | siteURL := "https://test.com" 24 | serverConfig := &model.Config{ 25 | ServiceSettings: model.ServiceSettings{ 26 | SiteURL: &siteURL, 27 | }, 28 | } 29 | 30 | api.On("GetConfig").Return(serverConfig) 31 | p := Plugin{} 32 | p.errorGenerator = test.MockErrorGenerator() 33 | p.SetAPI(api) 34 | p.setConfiguration(pluginConfig) 35 | return &p 36 | } 37 | 38 | func TestOnConfigurationChangeOK(t *testing.T) { 39 | configuration := generateMockPluginConfig() 40 | configuration.DisplayMode = pluginConf.DisplayModeEmbedded 41 | configuration.Provider = "giphy" 42 | p := generateMocksForConfigurationTesting(&configuration) 43 | 44 | err := p.OnConfigurationChange() 45 | 46 | assert.Nil(t, err) 47 | assert.Equal(t, "https://test.com/plugins/"+manifest.Manifest.Id, p.rootURL) 48 | } 49 | 50 | func TestOnConfigurationChangeLoadFail(t *testing.T) { 51 | api := &plugintest.API{} 52 | mockErr := errors.New("failed config load") 53 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockErr) 54 | p := Plugin{} 55 | p.SetAPI(api) 56 | 57 | err := p.OnConfigurationChange() 58 | 59 | assert.NotNil(t, err) 60 | assert.Contains(t, err.Error(), mockErr.Error()) 61 | } 62 | 63 | func TestOnConfigurationChangeEmptyDisplayMode(t *testing.T) { 64 | configuration := generateMockPluginConfig() 65 | configuration.DisplayMode = "" 66 | p := generateMocksForConfigurationTesting(&configuration) 67 | 68 | err := p.OnConfigurationChange() 69 | 70 | assert.NotNil(t, err) 71 | assert.Contains(t, err.Error(), "the Display Mode must be configured") 72 | } 73 | 74 | func TestOnConfigurationChangeGifProviderError(t *testing.T) { 75 | api := &plugintest.API{} 76 | pluginConfig := generateMockPluginConfig() 77 | pluginConfig.DisplayMode = pluginConf.DisplayModeEmbedded 78 | pluginConfig.APIKey = "" 79 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(pluginConfig)) 80 | 81 | p := Plugin{errorGenerator: test.MockErrorGenerator()} 82 | p.SetAPI(api) 83 | err := p.OnConfigurationChange() 84 | assert.NotNil(t, err) 85 | } 86 | 87 | func TestGetSetConfiguration(t *testing.T) { 88 | p := Plugin{} 89 | 90 | initialConfig := p.getConfiguration() 91 | assert.NotNil(t, initialConfig) 92 | 93 | initialConfig.APIKey = "COUCOU" 94 | p.setConfiguration(initialConfig) 95 | 96 | modifiedConfig := p.getConfiguration() 97 | assert.Equal(t, initialConfig.APIKey, modifiedConfig.APIKey) 98 | 99 | defer func() { 100 | if r := recover(); r == nil { 101 | t.Errorf("The code did not panic") 102 | } 103 | }() 104 | p.setConfiguration(modifiedConfig) 105 | } 106 | -------------------------------------------------------------------------------- /server/httpHandler.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "io" 7 | "net/http" 8 | "strconv" 9 | 10 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 11 | 12 | "github.com/mattermost/mattermost/server/public/model" 13 | "github.com/mattermost/mattermost/server/public/plugin" 14 | "github.com/mitchellh/mapstructure" 15 | ) 16 | 17 | // Contains what's related to handling HTTP requests directed to the plugin 18 | 19 | const ( 20 | URLShuffle = "/shuffle" 21 | URLCancel = "/cancel" 22 | URLPrevious = "/previous" 23 | URLSend = "/send" 24 | ) 25 | 26 | type integrationRequest struct { 27 | Keywords string `mapstructure:"keywords"` 28 | Caption string `mapstructure:"caption"` 29 | GifURLs []string `mapstructure:"gifURLs"` 30 | CurrentGifIndex int `mapstructure:"currentGifIndex"` 31 | SearchCursor string `mapstructure:"searchCursor"` 32 | RootID string `mapstructure:"rootID"` 33 | model.PostActionIntegrationRequest 34 | } 35 | 36 | type ( 37 | pluginHTTPHandler interface { 38 | handleCancel(p *Plugin, w http.ResponseWriter, request *integrationRequest) 39 | handleShuffle(p *Plugin, w http.ResponseWriter, request *integrationRequest) 40 | handlePrevious(p *Plugin, w http.ResponseWriter, request *integrationRequest) 41 | handleSend(p *Plugin, w http.ResponseWriter, request *integrationRequest) 42 | } 43 | defaultHTTPHandler struct{} 44 | ) 45 | 46 | var notifyUserOfError = defaultNotifyUserOfError 47 | 48 | func (p *Plugin) handleHTTPRequest(w http.ResponseWriter, r *http.Request) { 49 | if r.Method != "POST" { 50 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) 51 | return 52 | } 53 | 54 | // Header is set by MM server only if the request was successfully authenticated 55 | userID := r.Header.Get("Mattermost-User-Id") 56 | if userID == "" { 57 | http.Error(w, "Authentication failed: user not set in header", http.StatusUnauthorized) 58 | return 59 | } 60 | 61 | request, err := parseRequest(r) 62 | if err != nil { 63 | p.API.LogWarn("Could not parse PostActionIntegrationRequest", "error", err.Error()) 64 | w.WriteHeader(http.StatusBadRequest) 65 | return 66 | } 67 | 68 | if userID != request.UserId { 69 | http.Error(w, "The user of the request should match the authenticated user", http.StatusBadRequest) 70 | return 71 | } 72 | if !p.API.HasPermissionToChannel(request.UserId, request.ChannelId, model.PermissionReadChannel) { 73 | http.Error(w, "The user is not allowed to read this channel", http.StatusForbidden) 74 | return 75 | } 76 | if !p.API.HasPermissionToChannel(request.UserId, request.ChannelId, model.PermissionCreatePost) { 77 | http.Error(w, "The user is not allowed to post in this channel", http.StatusForbidden) 78 | return 79 | } 80 | 81 | switch r.URL.Path { 82 | case URLShuffle: 83 | p.httpHandler.handleShuffle(p, w, request) 84 | case URLPrevious: 85 | p.httpHandler.handlePrevious(p, w, request) 86 | case URLSend: 87 | p.httpHandler.handleSend(p, w, request) 88 | case URLCancel: 89 | p.httpHandler.handleCancel(p, w, request) 90 | default: 91 | http.NotFound(w, r) 92 | } 93 | } 94 | 95 | func parseRequest(r *http.Request) (*integrationRequest, error) { 96 | // Read data added by default for a button action 97 | body, readErr := io.ReadAll(r.Body) 98 | if readErr != nil { 99 | return nil, readErr 100 | } 101 | var request model.PostActionIntegrationRequest 102 | jsonErr := json.Unmarshal(body, &request) 103 | if jsonErr != nil { 104 | return nil, jsonErr 105 | } 106 | 107 | context := integrationRequest{} 108 | context.PostActionIntegrationRequest = request 109 | err := mapstructure.Decode(request.Context, &context) 110 | if context.Keywords == "" { 111 | return nil, errors.New("missing " + contextKeywords + " from action request context") 112 | } 113 | if len(context.GifURLs) == 0 { 114 | return nil, errors.New("missing " + contextGifURLs + " from action request context") 115 | } 116 | return &context, err 117 | } 118 | 119 | func writeResponse(httpStatus int, w http.ResponseWriter) { 120 | w.WriteHeader(httpStatus) 121 | if httpStatus == http.StatusOK { 122 | // Return the object the MM server expects in case of 200 status 123 | response := &model.PostActionIntegrationResponse{} 124 | w.Header().Set("Content-Type", "application/json") 125 | json, jsonErr := json.Marshal(response) 126 | if jsonErr == nil { 127 | _, _ = w.Write(json) 128 | } 129 | } 130 | } 131 | 132 | // Delete the ephemeral preview post 133 | func (h *defaultHTTPHandler) handleCancel(p *Plugin, w http.ResponseWriter, request *integrationRequest) { 134 | p.API.DeleteEphemeralPost(request.UserId, request.PostId) 135 | writeResponse(http.StatusOK, w) 136 | } 137 | 138 | // Replace the GIF in the ephemeral shuffle post by a new one 139 | func (h *defaultHTTPHandler) handleShuffle(p *Plugin, w http.ResponseWriter, request *integrationRequest) { 140 | if request.CurrentGifIndex+1 < len(request.GifURLs) { 141 | h.sendPreviewPost(p, w, request, request.GifURLs, request.CurrentGifIndex+1) 142 | return 143 | } 144 | 145 | random := p.configuration.RandomSearch 146 | if !random && request.SearchCursor == "" { 147 | notifyUserOfError(p.API, p.botID, "No more GIFs found for '"+request.Keywords+"'", nil, &request.PostActionIntegrationRequest) 148 | return 149 | } 150 | 151 | newGifURLs, err := p.gifProvider.GetGifURL(request.Keywords, &request.SearchCursor, random) 152 | if err != nil { 153 | notifyUserOfError(p.API, p.botID, "Unable to fetch a new Gif for shuffling", err, &request.PostActionIntegrationRequest) 154 | writeResponse(http.StatusServiceUnavailable, w) 155 | return 156 | } 157 | 158 | if len(newGifURLs) < 1 { 159 | notifyUserOfError(p.API, p.botID, "No GIFs found for '"+request.Keywords+"'", nil, &request.PostActionIntegrationRequest) 160 | return 161 | } 162 | 163 | currentIndex := len(request.GifURLs) 164 | // only add URLs that were not already seen (as we make successive API calls, the same URL can popup twice) 165 | for _, newURL := range newGifURLs { 166 | alreadyExist := false 167 | for _, usedURL := range request.GifURLs { 168 | if newURL == usedURL { 169 | alreadyExist = true 170 | break 171 | } 172 | } 173 | if !alreadyExist { 174 | request.GifURLs = append(request.GifURLs, newURL) 175 | } 176 | } 177 | 178 | h.sendPreviewPost(p, w, request, request.GifURLs, currentIndex) 179 | } 180 | 181 | // Replace the GIF in the ephemeral shuffle post by one that was already shuffled 182 | func (h *defaultHTTPHandler) handlePrevious(p *Plugin, w http.ResponseWriter, request *integrationRequest) { 183 | previousIndex := request.CurrentGifIndex - 1 184 | if previousIndex < 0 { 185 | notifyUserOfError(p.API, p.botID, "There is no previous URL", nil, &request.PostActionIntegrationRequest) 186 | writeResponse(http.StatusBadRequest, w) 187 | return 188 | } 189 | 190 | h.sendPreviewPost(p, w, request, request.GifURLs, previousIndex) 191 | } 192 | 193 | // Create and send an ephemeral for a gif preview message 194 | func (h *defaultHTTPHandler) sendPreviewPost(p *Plugin, w http.ResponseWriter, request *integrationRequest, gifURLs []string, currentGifIndex int) { 195 | time := model.GetMillis() 196 | post := &model.Post{ 197 | Id: request.PostId, 198 | ChannelId: request.ChannelId, 199 | UserId: p.botID, 200 | RootId: request.RootID, 201 | // Only embedded display mode works inside an ephemeral post 202 | Message: generateGifCaption(pluginConf.DisplayModeEmbedded, request.Keywords, request.Caption, gifURLs[currentGifIndex], p.gifProvider.GetAttributionMessage()), 203 | CreateAt: time, 204 | UpdateAt: time, 205 | } 206 | post.SetProps(map[string]interface{}{ 207 | "attachments": generatePreviewPostAttachments(request.Keywords, request.Caption, request.SearchCursor, request.RootID, gifURLs, currentGifIndex), 208 | }) 209 | p.API.UpdateEphemeralPost(request.UserId, post) 210 | writeResponse(http.StatusOK, w) 211 | } 212 | 213 | // Post the actual GIF and delete the obsolete ephemeral post 214 | func (h *defaultHTTPHandler) handleSend(p *Plugin, w http.ResponseWriter, request *integrationRequest) { 215 | p.API.DeleteEphemeralPost(request.UserId, request.PostId) 216 | if request.CurrentGifIndex < 0 || request.CurrentGifIndex >= len(request.GifURLs) { 217 | notifyUserOfError(p.API, p.botID, "Unable to create post : index "+strconv.Itoa(request.CurrentGifIndex)+"is out of bounds [0,"+strconv.Itoa(len(request.GifURLs))+"]", nil, &request.PostActionIntegrationRequest) 218 | writeResponse(http.StatusInternalServerError, w) 219 | return 220 | } 221 | time := model.GetMillis() 222 | post := &model.Post{ 223 | Message: generateGifCaption(p.getConfiguration().DisplayMode, request.Keywords, request.Caption, request.GifURLs[request.CurrentGifIndex], ""), 224 | UserId: request.UserId, 225 | ChannelId: request.ChannelId, 226 | RootId: request.RootID, 227 | CreateAt: time, 228 | UpdateAt: time, 229 | } 230 | _, err := p.API.CreatePost(post) 231 | if err != nil { 232 | notifyUserOfError(p.API, p.botID, "Unable to create post : ", err, &request.PostActionIntegrationRequest) 233 | writeResponse(http.StatusInternalServerError, w) 234 | return 235 | } 236 | 237 | writeResponse(http.StatusOK, w) 238 | } 239 | 240 | // Informs the user of an error (domain error with message, or technical error with err) that occurred in a button handler, and logs it if it's technical 241 | func defaultNotifyUserOfError(api plugin.API, botID string, message string, err *model.AppError, request *model.PostActionIntegrationRequest) { 242 | fullMessage := message 243 | if err != nil { 244 | fullMessage = err.Message 245 | } 246 | post := &model.Post{ 247 | Message: "*" + fullMessage + "*", 248 | ChannelId: request.ChannelId, 249 | UserId: botID, 250 | } 251 | post.SetProps(map[string]interface{}{ 252 | "sent_by_plugin": true, 253 | }) 254 | api.SendEphemeralPost(request.UserId, post) 255 | 256 | // Only log technical errors 257 | if err != nil { 258 | api.LogWarn(message, "error", err) 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /server/httpHandler_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "io" 8 | "net/http" 9 | "net/http/httptest" 10 | "strings" 11 | "testing" 12 | 13 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 14 | 15 | "github.com/stretchr/testify/assert" 16 | 17 | "github.com/mattermost/mattermost/server/public/model" 18 | "github.com/mattermost/mattermost/server/public/plugin" 19 | "github.com/mattermost/mattermost/server/public/plugin/plugintest" 20 | "github.com/mattermost/mattermost/server/public/plugin/plugintest/mock" 21 | ) 22 | 23 | const ( 24 | testChannelID = "gifs-channel" 25 | testCaption = "Message prêt à tout" 26 | testUserID = "gif-user" 27 | testPostID = "skfqsldjhfkljhf" 28 | testKeywords = "kitty" 29 | testGifURLPrevious = "https://gif.fr/gif/41" 30 | testGifURL = "https://gif.fr/gif/42" 31 | testGifURLNext = "https://gif.fr/gif/43" 32 | testCursor = "43abc" 33 | testRootID = "4242abc" 34 | ) 35 | 36 | var testPostActionIntegrationRequest = model.PostActionIntegrationRequest{ 37 | ChannelId: testChannelID, 38 | UserId: testUserID, 39 | PostId: testPostID, 40 | Context: map[string]interface{}{ 41 | contextGifURLs: []string{testGifURLPrevious, testGifURL, testGifURLNext}, 42 | contextCurrentIndex: 1, 43 | contextCaption: testCaption, 44 | contextKeywords: testKeywords, 45 | contextAPICursor: testCursor, 46 | contextRootID: testRootID, 47 | }, 48 | } 49 | 50 | func generatePostActionIntegrationRequestBody() io.Reader { 51 | json, _ := json.Marshal(testPostActionIntegrationRequest) 52 | return bytes.NewBuffer(json) 53 | } 54 | 55 | func generateTestIntegrationRequest(currentIndex int) *integrationRequest { 56 | return &integrationRequest{ 57 | testKeywords, testCaption, []string{testGifURLPrevious, testGifURL, testGifURLNext}, currentIndex, testCursor, testRootID, testPostActionIntegrationRequest, 58 | } 59 | } 60 | 61 | func setupMockPluginWithAuthent() *Plugin { 62 | api := &plugintest.API{} 63 | api.On("HasPermissionToChannel", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.AnythingOfType("*model.Permission")).Return(true) 64 | p := &Plugin{} 65 | p.SetAPI(api) 66 | p.httpHandler = &mockHTTPHandler{} 67 | 68 | return p 69 | } 70 | 71 | func TestHandleHTTPRequestShouldReturnOKStatusForAllSupportedRoutes(t *testing.T) { 72 | p := setupMockPluginWithAuthent() 73 | 74 | goodURLs := [4]string{URLCancel, URLShuffle, URLPrevious, URLSend} 75 | for _, URL := range goodURLs { 76 | w := httptest.NewRecorder() 77 | r := httptest.NewRequest("POST", URL, generatePostActionIntegrationRequestBody()) 78 | r.Header.Add("Mattermost-User-Id", testUserID) 79 | 80 | p.handleHTTPRequest(w, r) 81 | 82 | result := w.Result() 83 | assert.NotNil(t, result) 84 | assert.Equal(t, 200, result.StatusCode) 85 | } 86 | } 87 | 88 | func TestHandleHTTPRequestShouldFailWhenBadMethodIsUsed(t *testing.T) { 89 | p := setupMockPluginWithAuthent() 90 | w := httptest.NewRecorder() 91 | r := httptest.NewRequest("GET", URLSend, nil) 92 | r.Header.Add("Mattermost-User-Id", testUserID) 93 | 94 | p.handleHTTPRequest(w, r) 95 | 96 | result := w.Result() 97 | assert.NotNil(t, result) 98 | assert.Equal(t, 405, result.StatusCode) 99 | } 100 | 101 | func TestHandleHTTPRequestShouldFailWhenUnsupportedURLIsUsed(t *testing.T) { 102 | p := setupMockPluginWithAuthent() 103 | w := httptest.NewRecorder() 104 | r := httptest.NewRequest("POST", "/unexistingURL", generatePostActionIntegrationRequestBody()) 105 | r.Header.Add("Mattermost-User-Id", testUserID) 106 | 107 | p.handleHTTPRequest(w, r) 108 | 109 | result := w.Result() 110 | assert.NotNil(t, result) 111 | assert.Equal(t, 404, result.StatusCode) 112 | } 113 | 114 | func TestHandleHTTPRequestShouldFailWhenMissingAuthHeader(t *testing.T) { 115 | p := setupMockPluginWithAuthent() 116 | w := httptest.NewRecorder() 117 | r := httptest.NewRequest("POST", URLSend, nil) 118 | 119 | p.handleHTTPRequest(w, r) 120 | 121 | result := w.Result() 122 | assert.NotNil(t, result) 123 | assert.Equal(t, 401, result.StatusCode) 124 | } 125 | 126 | func TestHandleHTTPRequestShouldFailWhenAuthHeaderDoesntMatchRequestUser(t *testing.T) { 127 | p := setupMockPluginWithAuthent() 128 | w := httptest.NewRecorder() 129 | r := httptest.NewRequest("POST", URLSend, generatePostActionIntegrationRequestBody()) 130 | r.Header.Add("Mattermost-User-Id", "differentUserId") 131 | 132 | p.handleHTTPRequest(w, r) 133 | 134 | result := w.Result() 135 | assert.NotNil(t, result) 136 | assert.Equal(t, 400, result.StatusCode) 137 | } 138 | 139 | func TestHandleHTTPRequestShouldFailWhenUserDontHavePostingPermissionToChannel(t *testing.T) { 140 | api := &plugintest.API{} 141 | api.On("HasPermissionToChannel", 142 | mock.AnythingOfType("string"), 143 | mock.AnythingOfType("string"), 144 | mock.AnythingOfType("*model.Permission"), 145 | ).Return(false) 146 | p := &Plugin{} 147 | p.SetAPI(api) 148 | p.httpHandler = &mockHTTPHandler{} 149 | 150 | w := httptest.NewRecorder() 151 | r := httptest.NewRequest("POST", URLSend, generatePostActionIntegrationRequestBody()) 152 | r.Header.Add("Mattermost-User-Id", testUserID) 153 | 154 | p.handleHTTPRequest(w, r) 155 | 156 | result := w.Result() 157 | assert.NotNil(t, result) 158 | assert.Equal(t, 403, result.StatusCode) 159 | } 160 | 161 | func TestParseRequestShouldParseAllValuesFromCorrectRequest(t *testing.T) { 162 | r := httptest.NewRequest("POST", URLSend, generatePostActionIntegrationRequestBody()) 163 | 164 | request, err := parseRequest(r) 165 | 166 | assert.Nil(t, err) 167 | assert.NotNil(t, request) 168 | assert.Equal(t, request.ChannelId, testChannelID) 169 | assert.Equal(t, request.UserId, testUserID) 170 | assert.Equal(t, request.GifURLs, []string{testGifURLPrevious, testGifURL, testGifURLNext}) 171 | assert.Equal(t, request.CurrentGifIndex, 1) 172 | assert.Equal(t, request.Keywords, testKeywords) 173 | assert.Equal(t, request.SearchCursor, testCursor) 174 | assert.Equal(t, request.RootID, testRootID) 175 | } 176 | 177 | func TestParseRequestShouldFailIfRequestIfBodyCantBeRead(t *testing.T) { 178 | r := httptest.NewRequest("POST", URLSend, nil) 179 | request, err := parseRequest(r) 180 | assert.Nil(t, request) 181 | assert.NotNil(t, err) 182 | } 183 | 184 | func TestParseRequestShouldFailIfBodyCantBeParsed(t *testing.T) { 185 | body := bytes.NewBuffer([]byte("this is not a valid json")) 186 | r := httptest.NewRequest("POST", URLSend, body) 187 | request, err := parseRequest(r) 188 | assert.Nil(t, request) 189 | assert.NotNil(t, err) 190 | } 191 | 192 | func TestParseRequestShouldFailWhenRequiredContextValueIsMissing(t *testing.T) { 193 | incompleteContextRequests := []string{`{ 194 | "ChannelId": "testChannelId", 195 | "UserId": "testUserId", 196 | "PostId": "testPostId", 197 | Context: { 198 | "contextKeywords": "testKeywords", 199 | "contextCursor": "testCursor", 200 | "contextRootId": "testRootId", 201 | }`, 202 | `{ 203 | "ChannelId": "testChannelId", 204 | "UserId": "testUserId", 205 | "PostId": "testPostId", 206 | Context: { 207 | "contextGifURL": "testGifURL", 208 | "contextCursor": "testCursor", 209 | "contextRootId": "testRootId", 210 | }`} 211 | 212 | for i := 0; i < len(incompleteContextRequests); i++ { 213 | body := bytes.NewBuffer([]byte(incompleteContextRequests[i])) 214 | r := httptest.NewRequest("POST", URLSend, body) 215 | 216 | request, err := parseRequest(r) 217 | 218 | assert.Nil(t, request) 219 | assert.NotNil(t, err) 220 | } 221 | } 222 | 223 | func TestWriteResponseShouldHandleOKStatus(t *testing.T) { 224 | w := httptest.NewRecorder() 225 | 226 | writeResponse(http.StatusOK, w) 227 | 228 | result := w.Result() 229 | assert.Equal(t, result.StatusCode, http.StatusOK) 230 | bodyBytes, _ := io.ReadAll(result.Body) 231 | assert.Contains(t, string(bodyBytes), "update") 232 | } 233 | 234 | func TestWriteResponseShouldHandleOtherStatus(t *testing.T) { 235 | w := httptest.NewRecorder() 236 | writeResponse(http.StatusTeapot, w) 237 | result := w.Result() 238 | assert.Equal(t, result.StatusCode, http.StatusTeapot) 239 | bodyBytes, _ := io.ReadAll(result.Body) 240 | assert.NotContains(t, string(bodyBytes), "update") 241 | } 242 | 243 | func TestHandleCancelShouldDeleteEphemeralPost(t *testing.T) { 244 | api := &plugintest.API{} 245 | api.On("DeleteEphemeralPost", 246 | mock.AnythingOfType("string"), 247 | mock.AnythingOfType("string")).Return(nil) 248 | p := Plugin{} 249 | p.SetAPI(api) 250 | h := &defaultHTTPHandler{} 251 | w := httptest.NewRecorder() 252 | h.handleCancel(&p, w, generateTestIntegrationRequest(1)) 253 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 254 | api.AssertCalled(t, 255 | "DeleteEphemeralPost", 256 | mock.MatchedBy(func(s string) bool { return s == testUserID }), 257 | mock.MatchedBy(func(postId string) bool { return postId == testPostID })) 258 | } 259 | 260 | func TestHandleShuffleShouldUseTheNextLoadedGifToUpdateTheEphemeralPost(t *testing.T) { 261 | api, p := initMockAPI() 262 | api.On("UpdateEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("*model.Post")).Return(nil) 263 | p.gifProvider = newMockGifProvider() 264 | h := &defaultHTTPHandler{} 265 | w := httptest.NewRecorder() 266 | h.handleShuffle(p, w, generateTestIntegrationRequest(1)) 267 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 268 | api.AssertCalled(t, "UpdateEphemeralPost", 269 | mock.MatchedBy(func(s string) bool { return s == testUserID }), 270 | mock.MatchedBy(func(post *model.Post) bool { 271 | return post.Id == testPostID && 272 | strings.Contains(post.Message, testGifURLNext) && 273 | post.UserId == p.botID && 274 | post.ChannelId == testChannelID && 275 | post.RootId == testRootID 276 | })) 277 | } 278 | 279 | func TestHandleShuffleShouldLoadNewGifsIfNeededToUpdateEphemeralPostWhenSearchSucceeds(t *testing.T) { 280 | api, p := initMockAPI() 281 | api.On("UpdateEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("*model.Post")).Return(nil) 282 | p.gifProvider = newMockGifProvider() 283 | h := &defaultHTTPHandler{} 284 | w := httptest.NewRecorder() 285 | h.handleShuffle(p, w, generateTestIntegrationRequest(2)) 286 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 287 | api.AssertCalled(t, "UpdateEphemeralPost", 288 | mock.MatchedBy(func(s string) bool { return s == testUserID }), 289 | mock.MatchedBy(func(post *model.Post) bool { 290 | return post.Id == testPostID && 291 | strings.Contains(post.Message, "fakeURL") && 292 | post.UserId == p.botID && 293 | post.ChannelId == testChannelID && 294 | post.RootId == testRootID 295 | })) 296 | } 297 | 298 | func TestHandleShuffleShouldNotifyUserWhenSearchReturnsNoResult(t *testing.T) { 299 | _, p := initMockAPI() 300 | notifyUserWasCalled := false 301 | notifyUserOfError = func(_ plugin.API, _ string, message string, _ *model.AppError, _ *model.PostActionIntegrationRequest) { 302 | notifyUserWasCalled = true 303 | assert.Contains(t, message, "found") 304 | } 305 | 306 | p.gifProvider = &emptyGifProvider{} 307 | p.botID = "bot" 308 | h := &defaultHTTPHandler{} 309 | w := httptest.NewRecorder() 310 | h.handleShuffle(p, w, generateTestIntegrationRequest(2)) 311 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 312 | assert.True(t, notifyUserWasCalled) 313 | } 314 | 315 | func TestHandleShuffleShouldFailWhenSearchFails(t *testing.T) { 316 | api, p := initMockAPI() 317 | p.gifProvider = &mockGifProviderFail{"fakeURL"} 318 | h := &defaultHTTPHandler{} 319 | 320 | notifyUserOfError = func(_ plugin.API, _ string, message string, _ *model.AppError, _ *model.PostActionIntegrationRequest) { 321 | assert.Contains(t, message, "Gif") 322 | } 323 | 324 | w := httptest.NewRecorder() 325 | h.handleShuffle(p, w, generateTestIntegrationRequest(2)) 326 | assert.Equal(t, w.Result().StatusCode, http.StatusServiceUnavailable) 327 | api.AssertNumberOfCalls(t, "UpdateEphemeralPost", 0) 328 | } 329 | 330 | func TestHandlePreviousShouldUpdateEphemeralPostWithPreviousGifFromContext(t *testing.T) { 331 | api, p := initMockAPI() 332 | api.On("UpdateEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("*model.Post")).Return(nil) 333 | p.gifProvider = newMockGifProvider() 334 | h := &defaultHTTPHandler{} 335 | w := httptest.NewRecorder() 336 | h.handlePrevious(p, w, generateTestIntegrationRequest(1)) 337 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 338 | api.AssertCalled(t, "UpdateEphemeralPost", 339 | mock.MatchedBy(func(s string) bool { return s == testUserID }), 340 | mock.MatchedBy(func(post *model.Post) bool { 341 | return post.Id == testPostID && 342 | strings.Contains(post.Message, testGifURLPrevious) && 343 | post.UserId == p.botID && 344 | post.ChannelId == testChannelID && 345 | post.RootId == testRootID 346 | })) 347 | } 348 | 349 | func TestHandleSendSHouldDeleteTheEphemeralPostAndCreateANewPostWhenSearchSucceeds(t *testing.T) { 350 | api, p := initMockAPI() 351 | api.On("DeleteEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil) 352 | api.On("CreatePost", mock.AnythingOfType("*model.Post")).Return(nil, nil) 353 | p.gifProvider = newMockGifProvider() 354 | h := &defaultHTTPHandler{} 355 | w := httptest.NewRecorder() 356 | h.handleSend(p, w, generateTestIntegrationRequest(1)) 357 | assert.Equal(t, w.Result().StatusCode, http.StatusOK) 358 | api.AssertCalled(t, 359 | "DeleteEphemeralPost", 360 | mock.MatchedBy(func(s string) bool { return s == testUserID }), 361 | mock.MatchedBy(func(postId string) bool { return postId == testPostID })) 362 | api.AssertCalled(t, 363 | "CreatePost", 364 | mock.MatchedBy(func(p *model.Post) bool { 365 | return strings.Contains(p.Message, testGifURL) && 366 | p.UserId == testUserID && 367 | p.ChannelId == testChannelID && 368 | p.RootId == testRootID 369 | }), 370 | ) 371 | } 372 | 373 | func TestHandleSendShouldFailWhenCreatePostFails(t *testing.T) { 374 | api := &plugintest.API{} 375 | api.On("DeleteEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil) 376 | api.On("CreatePost", mock.AnythingOfType("*model.Post")).Return(nil, model.NewAppError("test", "id42", nil, "errorMessage", 42)) 377 | notifyUserOfError = func(_ plugin.API, _ string, message string, _ *model.AppError, _ *model.PostActionIntegrationRequest) { 378 | assert.Contains(t, message, "create") 379 | } 380 | 381 | p := Plugin{} 382 | p.SetAPI(api) 383 | p.gifProvider = newMockGifProvider() 384 | h := &defaultHTTPHandler{} 385 | w := httptest.NewRecorder() 386 | h.handleSend(&p, w, generateTestIntegrationRequest(1)) 387 | assert.Equal(t, w.Result().StatusCode, http.StatusInternalServerError) 388 | } 389 | 390 | func TestDefaultNotifyUserOfErrorCreateAnEphemeralPostAndLogsForTechnicalError(t *testing.T) { 391 | api := &plugintest.API{} 392 | api.On("SendEphemeralPost", mock.Anything, mock.Anything).Return(nil) 393 | api.On("LogWarn", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.Anything).Return(nil) 394 | message := "oops" 395 | err := test.MockErrorGenerator().FromError(message, errors.New("strange failure")) 396 | channelID := "42" 397 | userID := "jane" 398 | botID := "bot" 399 | request := &model.PostActionIntegrationRequest{ 400 | UserId: userID, 401 | ChannelId: channelID, 402 | } 403 | userIDCheck := func(uID string) bool { return uID == userID } 404 | postCheck := func(post *model.Post) bool { 405 | return post != nil && 406 | post.ChannelId == channelID && 407 | post.UserId == botID && 408 | strings.Contains(post.Message, message) && 409 | (err == nil || strings.Contains(post.Message, err.Message)) 410 | } 411 | // With error 412 | defaultNotifyUserOfError(api, botID, message, err, request) 413 | api.AssertNumberOfCalls(t, "LogWarn", 1) 414 | api.AssertCalled(t, "SendEphemeralPost", 415 | mock.MatchedBy(userIDCheck), 416 | mock.MatchedBy(postCheck)) 417 | } 418 | 419 | func TestDefaultNotifyUserOfErrorCreateAnEphemeralPostForDomainError(t *testing.T) { 420 | api := &plugintest.API{} 421 | api.On("SendEphemeralPost", mock.Anything, mock.Anything).Return(nil) 422 | message := "oops" 423 | channelID := "42" 424 | userID := "jane" 425 | botID := "bot" 426 | request := &model.PostActionIntegrationRequest{ 427 | UserId: userID, 428 | ChannelId: channelID, 429 | } 430 | userIDCheck := func(uID string) bool { return uID == userID } 431 | postCheck := func(post *model.Post) bool { 432 | return post != nil && 433 | post.ChannelId == channelID && 434 | post.UserId == botID && 435 | strings.Contains(post.Message, message) 436 | } 437 | 438 | defaultNotifyUserOfError(api, botID, message, nil, request) 439 | api.AssertNumberOfCalls(t, "LogWarn", 0) 440 | api.AssertCalled(t, "SendEphemeralPost", 441 | mock.MatchedBy(userIDCheck), 442 | mock.MatchedBy(postCheck)) 443 | } 444 | -------------------------------------------------------------------------------- /server/internal/configuration/configuration.go: -------------------------------------------------------------------------------- 1 | package configuration 2 | 3 | import "errors" 4 | 5 | // Configuration captures the plugin's external configuration as exposed in the Mattermost server 6 | // configuration, as well as values computed from the configuration. Any public fields will be 7 | // deserialized from the Mattermost server configuration in OnConfigurationChange. 8 | type Configuration struct { 9 | Provider string 10 | DisplayMode string 11 | Rating string 12 | Language string 13 | Rendition string 14 | RenditionTenor string 15 | APIKey string 16 | DisablePostingWithoutPreview bool 17 | RandomSearch bool 18 | // Computed fields: 19 | CommandTriggerGif string 20 | CommandTriggerGifWithPreview string 21 | } 22 | 23 | // Clone shallow copies the configuration. Your implementation may require a deep copy if 24 | // your configuration has reference types. 25 | func (c *Configuration) Clone() *Configuration { 26 | var clone = *c 27 | return &clone 28 | } 29 | 30 | // Return an error if the configuration is invalid, or nil if it is valid 31 | func (c *Configuration) IsValid() error { 32 | if c.DisplayMode == "" { 33 | return errors.New("the Display Mode must be configured") 34 | } 35 | 36 | if (c.Provider == "giphy" || c.Provider == "tenor") && len(c.APIKey) == 0 { 37 | return errors.New("when the selected Provider is Giphy or Tenor, an API Key must be provided") 38 | } 39 | 40 | return nil 41 | } 42 | 43 | const ( 44 | // DisplayModeEmbedded display GIFs as Markdown embedded images 45 | DisplayModeEmbedded = "embedded" 46 | // DisplayModeFullURL displays GIFs as raw URLs using image preview 47 | DisplayModeFullURL = "full_url" 48 | ) 49 | -------------------------------------------------------------------------------- /server/internal/error/plugin_error.go: -------------------------------------------------------------------------------- 1 | package error 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/mattermost/mattermost/server/public/model" 7 | ) 8 | 9 | // PluginError create appErrors enriched with plugin name for better logging 10 | type PluginError interface { 11 | FromError(message string, err error) *model.AppError 12 | FromMessage(message string) *model.AppError 13 | } 14 | 15 | // NewPluginErrorGenerator returns the default PluginError 16 | func NewPluginErrorGenerator(manifestName string) PluginError { 17 | return &pluginError{where: manifestName} 18 | } 19 | 20 | type pluginError struct { 21 | where string 22 | } 23 | 24 | // appError generates a normalized error for this plugin 25 | func (e *pluginError) FromError(message string, err error) *model.AppError { 26 | errorMessage := "" 27 | if err != nil { 28 | errorMessage = err.Error() 29 | } 30 | return model.NewAppError(e.where, message, nil, errorMessage, http.StatusBadRequest) 31 | } 32 | 33 | // appError generates a normalized error for this plugin 34 | func (e *pluginError) FromMessage(message string) *model.AppError { 35 | return e.FromError(message, nil) 36 | } 37 | -------------------------------------------------------------------------------- /server/internal/pluginapi/mock_pluginapi/mock_pluginapi.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: pluginapi.go 3 | 4 | // Package mock_pluginapi is a generated GoMock package. 5 | package mock_pluginapi 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | mattermost_plugin_api "github.com/mattermost/mattermost/server/public/pluginapi" 12 | model "github.com/mattermost/mattermost/server/public/model" 13 | ) 14 | 15 | // MockBotService is a mock of BotService interface. 16 | type MockBotService struct { 17 | ctrl *gomock.Controller 18 | recorder *MockBotServiceMockRecorder 19 | } 20 | 21 | // MockBotServiceMockRecorder is the mock recorder for MockBotService. 22 | type MockBotServiceMockRecorder struct { 23 | mock *MockBotService 24 | } 25 | 26 | // NewMockBotService creates a new mock instance. 27 | func NewMockBotService(ctrl *gomock.Controller) *MockBotService { 28 | mock := &MockBotService{ctrl: ctrl} 29 | mock.recorder = &MockBotServiceMockRecorder{mock} 30 | return mock 31 | } 32 | 33 | // EXPECT returns an object that allows the caller to indicate expected use. 34 | func (m *MockBotService) EXPECT() *MockBotServiceMockRecorder { 35 | return m.recorder 36 | } 37 | 38 | // EnsureBot mocks base method. 39 | func (m *MockBotService) EnsureBot(arg0 *model.Bot, arg1 ...mattermost_plugin_api.EnsureBotOption) (string, error) { 40 | m.ctrl.T.Helper() 41 | varargs := []interface{}{arg0} 42 | for _, a := range arg1 { 43 | varargs = append(varargs, a) 44 | } 45 | ret := m.ctrl.Call(m, "EnsureBot", varargs...) 46 | ret0, _ := ret[0].(string) 47 | ret1, _ := ret[1].(error) 48 | return ret0, ret1 49 | } 50 | 51 | // EnsureBot indicates an expected call of EnsureBot. 52 | func (mr *MockBotServiceMockRecorder) EnsureBot(arg0 interface{}, arg1 ...interface{}) *gomock.Call { 53 | mr.mock.ctrl.T.Helper() 54 | varargs := append([]interface{}{arg0}, arg1...) 55 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBot", reflect.TypeOf((*MockBotService)(nil).EnsureBot), varargs...) 56 | } 57 | -------------------------------------------------------------------------------- /server/internal/pluginapi/pluginapi.go: -------------------------------------------------------------------------------- 1 | package pluginapi 2 | 3 | import ( 4 | "github.com/mattermost/mattermost/server/public/model" 5 | "github.com/mattermost/mattermost/server/public/plugin" 6 | "github.com/mattermost/mattermost/server/public/pluginapi" 7 | ) 8 | 9 | type Client struct { 10 | Bot BotService 11 | } 12 | 13 | // BotService is an interface declaring only the functions from 14 | // mattermost-plugin-api BotService that are used in this plugin 15 | type BotService interface { 16 | EnsureBot(*model.Bot, ...pluginapi.EnsureBotOption) (retBotID string, retErr error) 17 | } 18 | 19 | func NewClient(api plugin.API, driver plugin.Driver) *Client { 20 | client := pluginapi.NewClient(api, driver) 21 | return &Client{Bot: &client.Bot} 22 | } 23 | -------------------------------------------------------------------------------- /server/internal/provider/gif_provider.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "net/http" 5 | 6 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 7 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 8 | 9 | "github.com/mattermost/mattermost/server/public/model" 10 | ) 11 | 12 | // GifProvider exposes methods to get GIF from an API 13 | type GifProvider interface { 14 | // GetGifURL return the URL of a GIF that matches the requested keywords if one is found or else an empty string 15 | GetGifURL(request string, cursor *string, random bool) ([]string, *model.AppError) 16 | 17 | // GetAttributionMessage returns the text that should be displayed near the GIF, as defined by the providers' Terms of Service 18 | GetAttributionMessage() string 19 | } 20 | 21 | // HTTPClient is an subset of the standard HTTP client functions used by GIF Providers 22 | type HTTPClient interface { 23 | Do(req *http.Request) (*http.Response, error) 24 | Get(s string) (*http.Response, error) 25 | } 26 | 27 | type Query struct { 28 | Keywords string 29 | Cursor string 30 | } 31 | 32 | // nolint: structcheck //linter mistakenly thinks all fields are unused but they are used by composition 33 | type abstractGifProvider struct { 34 | httpClient HTTPClient 35 | errorGenerator pluginError.PluginError 36 | language string 37 | rating string 38 | rendition string 39 | } 40 | 41 | func defaultGifProviderGenerator(configuration pluginConf.Configuration, errorGenerator pluginError.PluginError, rootURL string) (gifProvider GifProvider, err *model.AppError) { 42 | if configuration.Provider == "" { 43 | return nil, errorGenerator.FromMessage("The GIF provider must be configured") 44 | } 45 | switch configuration.Provider { 46 | case "giphy": 47 | gifProvider, err = NewGiphyProvider(http.DefaultClient, errorGenerator, configuration.APIKey, configuration.Language, configuration.Rating, configuration.Rendition, rootURL) 48 | case "tenor": 49 | gifProvider, err = NewTenorProvider(http.DefaultClient, errorGenerator, configuration.APIKey, configuration.Language, configuration.Rating, configuration.RenditionTenor) 50 | } 51 | return gifProvider, err 52 | } 53 | 54 | var GifProviderGenerator = defaultGifProviderGenerator 55 | -------------------------------------------------------------------------------- /server/internal/provider/gif_provider_test.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 8 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestDefaultGifProviderGenerator(t *testing.T) { 14 | testCases := []struct { 15 | testLabel string 16 | providerType string 17 | expectedError bool 18 | expectedType interface{} 19 | }{ 20 | {testLabel: "Empty provider", providerType: "", expectedError: true, expectedType: nil}, 21 | {testLabel: "Giphyprovider", providerType: "giphy", expectedError: false, expectedType: &giphy{}}, 22 | {testLabel: "Tenor provider", providerType: "tenor", expectedError: false, expectedType: tenor{}}, 23 | } 24 | 25 | for _, testCase := range testCases { 26 | testConfig := pluginConf.Configuration{Provider: testCase.providerType, 27 | APIKey: testGiphyAPIKey, 28 | Language: testGiphyLanguage, 29 | Rating: testGiphyRating, 30 | Rendition: testGiphyRendition, 31 | RenditionTenor: testTenorRendition, 32 | } 33 | provider, err := defaultGifProviderGenerator(testConfig, test.MockErrorGenerator(), "/test") 34 | if testCase.expectedError { 35 | assert.NotNil(t, err, testCase.testLabel) 36 | assert.Nil(t, provider, testCase.testLabel) 37 | } else { 38 | assert.Nil(t, err, testCase.testLabel) 39 | assert.NotNil(t, provider, testCase.testLabel) 40 | assert.Equal(t, "*provider."+testConfig.Provider, reflect.TypeOf(provider).String()) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /server/internal/provider/giphy.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | "strconv" 9 | 10 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 11 | 12 | "github.com/mattermost/mattermost/server/public/model" 13 | ) 14 | 15 | // giphy find GIFs using the giphy API 16 | type giphy struct { 17 | abstractGifProvider 18 | apiKey string 19 | rootURL string 20 | } 21 | 22 | const ( 23 | baseURLGiphy = "https://api.giphy.com/v1/gifs" 24 | ) 25 | 26 | type GiphyData struct { 27 | Images map[string]struct { 28 | URL string `json:"url"` 29 | } `json:"images"` 30 | } 31 | 32 | type GiphySearchResult struct { 33 | Data []GiphyData `json:"data"` 34 | Pagination struct { 35 | Offset int `json:"offset"` 36 | } `json:"pagination"` 37 | } 38 | 39 | type GiphyRandomResult struct { 40 | Data GiphyData `json:"data"` 41 | } 42 | 43 | type GiphyRandomEmptyResult struct { 44 | Data []GiphyData `json:"data"` 45 | } 46 | 47 | // NewGiphyProvider creates an instance of a GIF provider that uses the Giphy API 48 | func NewGiphyProvider(httpClient HTTPClient, errorGenerator pluginError.PluginError, apiKey, language, rating, rendition, rootURL string) (GifProvider, *model.AppError) { 49 | if errorGenerator == nil { 50 | return nil, model.NewAppError("NewGiphyProvider", "errorGenerator cannot be nil for Giphy Provider", nil, "", http.StatusInternalServerError) 51 | } 52 | if httpClient == nil { 53 | return nil, errorGenerator.FromMessage("httpClient cannot be nil for Giphy Provider") 54 | } 55 | if apiKey == "" { 56 | return nil, errorGenerator.FromMessage("apiKey cannot be empty for Giphy Provider") 57 | } 58 | if rendition == "" { 59 | return nil, errorGenerator.FromMessage("rendition cannot be empty for Giphy Provider") 60 | } 61 | if rootURL == "" { 62 | return nil, errorGenerator.FromMessage("internal error: rootURL must be set") 63 | } 64 | 65 | GiphyProvider := &giphy{} 66 | GiphyProvider.httpClient = httpClient 67 | GiphyProvider.errorGenerator = errorGenerator 68 | GiphyProvider.apiKey = apiKey 69 | GiphyProvider.language = language 70 | GiphyProvider.rating = rating 71 | GiphyProvider.rendition = rendition 72 | GiphyProvider.rootURL = rootURL 73 | 74 | return GiphyProvider, nil 75 | } 76 | 77 | func (p *giphy) GetAttributionMessage() string { 78 | return fmt.Sprintf("![GIPHY](%s/public/powered-by-giphy.png)", p.rootURL) 79 | } 80 | 81 | // Return the URL of a GIF that matches the query, or an empty string if no GIF matches the query, or an error if the search failed 82 | func (p *giphy) GetGifURL(request string, cursor *string, random bool) ([]string, *model.AppError) { 83 | if random { 84 | return p.getRandomGifURL(request) 85 | } 86 | return p.getSearchGifURL(request, cursor) 87 | } 88 | 89 | // Return the URL of a GIF that matches the query, or an empty string if no GIF matches the query, or an error if the search failed 90 | func (p *giphy) getSearchGifURL(request string, cursor *string) ([]string, *model.AppError) { 91 | parameters := map[string]string{"q": request} 92 | if counter, err2 := strconv.Atoi(*cursor); err2 == nil { 93 | parameters["offset"] = fmt.Sprintf("%d", counter) 94 | } 95 | if len(p.language) > 0 { 96 | parameters["lang"] = p.language 97 | } 98 | 99 | body, err := p.callGiphyEndpoint("search", parameters) 100 | if err != nil { 101 | return []string{}, err 102 | } 103 | 104 | var response GiphySearchResult 105 | if decodeErr := json.Unmarshal(body, &response); decodeErr != nil { 106 | return []string{}, p.errorGenerator.FromError("Could not parse Giphy response body", decodeErr) 107 | } 108 | 109 | if len(response.Data) < 1 { 110 | return []string{}, nil 111 | } 112 | 113 | urls := []string{} 114 | for i := range response.Data { 115 | if url, err := p.getURL(response.Data[i]); err == nil { 116 | urls = append(urls, url) 117 | } 118 | } 119 | 120 | if len(urls) < 1 { 121 | return []string{}, p.errorGenerator.FromMessage("No gifs found for display style \"" + p.rendition + "\" in the response") 122 | } 123 | 124 | *cursor = fmt.Sprintf("%d", response.Pagination.Offset+1) 125 | 126 | return urls, nil 127 | } 128 | 129 | // Return the URL of a random GIF that matches the query, or an empty string if no GIF matches the query, or an error if the search failed 130 | func (p *giphy) getRandomGifURL(request string) ([]string, *model.AppError) { 131 | body, err := p.callGiphyEndpoint("random", map[string]string{"tag": request}) 132 | if err != nil { 133 | return []string{}, err 134 | } 135 | 136 | var response GiphyRandomResult 137 | if err := json.Unmarshal(body, &response); err != nil { 138 | // Giphy API has the bad taste to return a different structure in case of no GIF found... 139 | var emptyResponse GiphyRandomEmptyResult 140 | if err = json.Unmarshal(body, &emptyResponse); err == nil { 141 | // No GIF found 142 | return []string{}, nil 143 | } 144 | return []string{}, p.errorGenerator.FromError("Could not parse Giphy response body", err) 145 | } 146 | 147 | url, err := p.getURL(response.Data) 148 | if err != nil { 149 | return []string{}, err 150 | } 151 | return []string{url}, nil 152 | } 153 | 154 | func (p *giphy) callGiphyEndpoint(endpoint string, customParameters map[string]string) ([]byte, *model.AppError) { 155 | req, err := http.NewRequest("GET", baseURLGiphy+"/"+endpoint, nil) 156 | if err != nil { 157 | return nil, p.errorGenerator.FromError("Could not generate URL", err) 158 | } 159 | 160 | q := req.URL.Query() 161 | 162 | q.Add("api_key", p.apiKey) 163 | if p.rating != "none" && len(p.rating) > 0 { 164 | q.Add("rating", p.rating) 165 | } 166 | for key, value := range customParameters { 167 | q.Add(key, value) 168 | } 169 | 170 | req.URL.RawQuery = q.Encode() 171 | 172 | r, err := p.httpClient.Do(req) 173 | if err != nil { 174 | return nil, p.errorGenerator.FromError("Error calling the Giphy API "+req.URL.RawQuery, err) 175 | } 176 | if r.Body != nil { 177 | defer r.Body.Close() 178 | } 179 | 180 | if r.StatusCode != http.StatusOK { 181 | explanation := "" 182 | if r.StatusCode == http.StatusTooManyRequests { 183 | explanation = ", this can happen if you're using the default Giphy API key" 184 | } 185 | return nil, p.errorGenerator.FromMessage(fmt.Sprintf("Error calling the Giphy API (HTTP Status: %v%s)", r.Status, explanation)) 186 | } 187 | if r.Body == nil { 188 | return nil, p.errorGenerator.FromMessage("Giphy response body is empty") 189 | } 190 | 191 | body, err := io.ReadAll(r.Body) 192 | if err != nil { 193 | return nil, p.errorGenerator.FromError("Unable to read response body", err) 194 | } 195 | return body, nil 196 | } 197 | 198 | func (p *giphy) getURL(gif GiphyData) (string, *model.AppError) { 199 | url := gif.Images[p.rendition].URL 200 | 201 | if len(url) < 1 { 202 | return "", p.errorGenerator.FromMessage("No URL found for display style \"" + p.rendition + "\" in the response") 203 | } 204 | return url, nil 205 | } 206 | -------------------------------------------------------------------------------- /server/internal/provider/giphy_test.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | 7 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 8 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | const defaultGiphyResponseBodyForSearch = "{\"data\" : [ { \"images\": { \"fixed_height_small\": {\"url\": \"url\"}}} ] }" 14 | const defaultGiphyResponseBodyForRandom = "{\"data\" : { \"images\": { \"fixed_height_small\": {\"url\": \"url\"}}} }" 15 | const ( 16 | testGiphyAPIKey = "apikey" 17 | testGiphyLanguage = "fr" 18 | testGiphyRating = "R" 19 | testGiphyRendition = "fixed_height_small" 20 | testRootURL = "/test" 21 | ) 22 | 23 | func TestNewGiphyProvider(t *testing.T) { 24 | testtHTTPClient := NewMockHTTPClient(newServerResponseOK(defaultGiphyResponseBodyForSearch)) 25 | testErrorGenerator := test.MockErrorGenerator() 26 | testCases := []struct { 27 | testLabel string 28 | paramHTTPClient HTTPClient 29 | paramErrorGenerator pluginError.PluginError 30 | paramAPIKey string 31 | paramRating string 32 | paramLanguage string 33 | paramRendition string 34 | expectedError bool 35 | }{ 36 | {testLabel: "OK", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: testGiphyRating, paramRendition: testGiphyRendition, expectedError: false}, 37 | {testLabel: "KO missing rendition", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: testGiphyRating, paramRendition: "", expectedError: true}, 38 | {testLabel: "OK empty rating (legacy: empty string)", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: "", paramRendition: testGiphyRendition, expectedError: false}, 39 | {testLabel: "OK empty rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: "none", paramRendition: testGiphyRendition, expectedError: false}, 40 | {testLabel: "OK empty language", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: "", paramRating: testGiphyRating, paramRendition: testGiphyRendition, expectedError: false}, 41 | {testLabel: "KO empty api key", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: "", paramLanguage: testGiphyLanguage, paramRating: testGiphyRating, paramRendition: testGiphyRendition, expectedError: true}, 42 | {testLabel: "KO nil errorGenerator", paramHTTPClient: testtHTTPClient, paramErrorGenerator: nil, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: testGiphyRating, paramRendition: testGiphyRendition, expectedError: true}, 43 | {testLabel: "KO nil httpClient", paramHTTPClient: nil, paramErrorGenerator: testErrorGenerator, paramAPIKey: testGiphyAPIKey, paramLanguage: testGiphyLanguage, paramRating: testGiphyRating, paramRendition: testGiphyRendition, expectedError: true}, 44 | {testLabel: "KO all empty", paramHTTPClient: nil, paramErrorGenerator: nil, paramAPIKey: "", paramLanguage: "", paramRating: "", paramRendition: "", expectedError: true}, 45 | } 46 | 47 | for _, testCase := range testCases { 48 | provider, err := NewGiphyProvider(testCase.paramHTTPClient, testCase.paramErrorGenerator, testCase.paramAPIKey, testCase.paramLanguage, testCase.paramRating, testCase.paramRendition, testRootURL) 49 | if testCase.expectedError { 50 | assert.NotNil(t, err, testCase.testLabel) 51 | assert.Nil(t, provider, testCase.testLabel) 52 | } else { 53 | assert.Nil(t, err, testCase.testLabel) 54 | assert.NotNil(t, provider, testCase.testLabel) 55 | assert.IsType(t, &giphy{}, provider, testCase.testLabel) 56 | assert.Equal(t, testCase.paramHTTPClient, provider.(*giphy).httpClient, testCase.testLabel) 57 | assert.Equal(t, testCase.paramErrorGenerator, provider.(*giphy).errorGenerator, testCase.testLabel) 58 | assert.Equal(t, testCase.paramAPIKey, provider.(*giphy).apiKey, testCase.testLabel) 59 | assert.Equal(t, testCase.paramLanguage, provider.(*giphy).language, testCase.testLabel) 60 | assert.Equal(t, testCase.paramRating, provider.(*giphy).rating, testCase.testLabel) 61 | assert.Equal(t, testCase.paramRendition, provider.(*giphy).rendition, testCase.testLabel) 62 | } 63 | } 64 | } 65 | 66 | func generateGiphyProviderForTest(mockHTTPResponse *http.Response) *giphy { 67 | provider, _ := NewGiphyProvider(NewMockHTTPClient(mockHTTPResponse), test.MockErrorGenerator(), testGiphyAPIKey, testGiphyLanguage, testGiphyRating, testGiphyRendition, testRootURL) 68 | return provider.(*giphy) 69 | } 70 | 71 | func TestGiphyProviderGetGifURLShouldHandleAPIErrors(t *testing.T) { 72 | testCases := []struct { 73 | testLabel string 74 | httpResponse *http.Response 75 | cursor string 76 | expectedError string 77 | }{ 78 | {testLabel: "KO empty HTTP response body", httpResponse: newServerResponseOK(""), expectedError: "empty"}, 79 | {testLabel: "KO HTTP response JSON parse error", httpResponse: newServerResponseOK("This is not a valid JSON response"), expectedError: "parse"}, 80 | {testLabel: "KO HTTP 400 Bad request", httpResponse: newServerResponseKO(400), expectedError: "400"}, 81 | {testLabel: "KO HTTP 429 Too many requests", httpResponse: newServerResponseKO(429), expectedError: "default Giphy API key"}, 82 | } 83 | 84 | for _, random := range [2]bool{true, false} { 85 | for _, testCase := range testCases { 86 | p := generateGiphyProviderForTest(testCase.httpResponse) 87 | url, err := p.GetGifURL("cat", &testCase.cursor, random) 88 | assert.NotNil(t, err, testCase.testLabel) 89 | assert.Contains(t, err.Error(), testCase.expectedError, testCase.testLabel) 90 | assert.Empty(t, url, testCase.testLabel) 91 | } 92 | } 93 | } 94 | 95 | func generateSearchAndRandomTestCases(apiResponseForSearch string, apiResponseForRandom string) (testCases []struct { 96 | random bool 97 | httpResponse *http.Response 98 | label string 99 | }) { 100 | testCases = []struct { 101 | random bool 102 | httpResponse *http.Response 103 | label string 104 | }{ 105 | {label: "search", random: false, httpResponse: newServerResponseOK(apiResponseForSearch)}, 106 | {label: "random", random: true, httpResponse: newServerResponseOK(apiResponseForRandom)}, 107 | } 108 | return testCases 109 | } 110 | 111 | func TestGiphyProviderGetGifURLShouldReturnUrlWhenSearchSucceeds(t *testing.T) { 112 | cursor := "" 113 | for _, testCase := range generateSearchAndRandomTestCases(defaultGiphyResponseBodyForSearch, defaultGiphyResponseBodyForRandom) { 114 | p := generateGiphyProviderForTest(testCase.httpResponse) 115 | url, err := p.GetGifURL("cat", &cursor, testCase.random) 116 | assert.Nil(t, err, testCase.label) 117 | assert.NotEmpty(t, url, testCase.label) 118 | assert.Equal(t, []string{"url"}, url, testCase.label) 119 | } 120 | } 121 | 122 | func TestGiphyProviderGetGifURLShouldReturnEmptyUrlWhenSearchReturnNoResult(t *testing.T) { 123 | cursor := "" 124 | 125 | for _, testCase := range generateSearchAndRandomTestCases("{\"data\": [] }", "{\"data\": [] }") { 126 | p := generateGiphyProviderForTest(testCase.httpResponse) 127 | url, err := p.GetGifURL("cat", &cursor, testCase.random) 128 | assert.Nil(t, err, testCase.label) 129 | assert.Empty(t, url, testCase.label) 130 | } 131 | } 132 | 133 | func TestGiphyProviderGetGifURLShouldFailWhenNoURLForRendition(t *testing.T) { 134 | cursor := "" 135 | for _, testCase := range generateSearchAndRandomTestCases(defaultGiphyResponseBodyForSearch, defaultGiphyResponseBodyForRandom) { 136 | p := generateGiphyProviderForTest(testCase.httpResponse) 137 | p.rendition = "unknown_rendition_style" 138 | url, err := p.GetGifURL("cat", &cursor, testCase.random) 139 | assert.NotNil(t, err, testCase.label) 140 | if testCase.random { 141 | assert.Contains(t, err.Error(), "No URL found for display style", testCase.label) 142 | } else { 143 | assert.Contains(t, err.Error(), "No gifs found for display style", testCase.label) 144 | } 145 | assert.Contains(t, err.Error(), p.rendition, testCase.label) 146 | assert.Empty(t, url, testCase.label) 147 | } 148 | } 149 | 150 | func generateGiphyProviderForURLBuildingTests(random bool) (*giphy, *MockHTTPClient, string) { 151 | var serverResponse *http.Response 152 | if random { 153 | serverResponse = newServerResponseOK(defaultGiphyResponseBodyForRandom) 154 | } else { 155 | serverResponse = newServerResponseOK(defaultGiphyResponseBodyForSearch) 156 | } 157 | client := NewMockHTTPClient(serverResponse) 158 | provider, _ := NewGiphyProvider(client, test.MockErrorGenerator(), testGiphyAPIKey, testGiphyLanguage, testGiphyRating, testGiphyRendition, testRootURL) 159 | return provider.(*giphy), client, "" 160 | } 161 | 162 | func TestGiphyProviderGetGifURLShouldUseSearchAPIWhenNotConfiguredForRandom(t *testing.T) { 163 | p, client, cursor := generateGiphyProviderForURLBuildingTests(false) 164 | 165 | client.testRequestFunc = func(req *http.Request) bool { 166 | assert.Contains(t, req.URL.Path, "/search") 167 | assert.Contains(t, req.URL.RawQuery, "q=cat") 168 | return true 169 | } 170 | _, err := p.GetGifURL("cat", &cursor, false) 171 | assert.Nil(t, err) 172 | assert.True(t, client.lastRequestPassTest) 173 | } 174 | 175 | func TestGiphyProviderGetGifURLShouldUseRandomAPIWhenConfiguredForRandom(t *testing.T) { 176 | p, client, cursor := generateGiphyProviderForURLBuildingTests(true) 177 | 178 | client.testRequestFunc = func(req *http.Request) bool { 179 | assert.Contains(t, req.URL.Path, "/random") 180 | assert.Contains(t, req.URL.RawQuery, "tag=cat") 181 | return true 182 | } 183 | _, err := p.GetGifURL("cat", &cursor, true) 184 | assert.Nil(t, err) 185 | assert.True(t, client.lastRequestPassTest) 186 | } 187 | 188 | func TestGiphyProviderGetGifURLUsesParameterAPIKey(t *testing.T) { 189 | for _, testCase := range generateSearchAndRandomTestCases(defaultGiphyResponseBodyForSearch, defaultGiphyResponseBodyForRandom) { 190 | p, client, cursor := generateGiphyProviderForURLBuildingTests(testCase.random) 191 | 192 | // API Key: mandatory 193 | client.testRequestFunc = func(req *http.Request) bool { 194 | assert.Contains(t, req.URL.RawQuery, "api_key="+testGiphyAPIKey) 195 | return true 196 | } 197 | _, err := p.GetGifURL("cat", &cursor, testCase.random) 198 | assert.Nil(t, err, testCase.label) 199 | assert.True(t, client.lastRequestPassTest, testCase.label) 200 | } 201 | } 202 | 203 | func TestGiphyProviderGetGifURLWhenNoRandomAndCursorIsEmpty(t *testing.T) { 204 | p, client, cursor := generateGiphyProviderForURLBuildingTests(false) 205 | 206 | // Cursor : optional 207 | // Empty initial value 208 | client.testRequestFunc = func(req *http.Request) bool { 209 | assert.NotContains(t, req.URL.RawQuery, "offset") 210 | return true 211 | } 212 | 213 | _, err := p.GetGifURL("cat", &cursor, false) 214 | assert.Nil(t, err) 215 | assert.True(t, client.lastRequestPassTest) 216 | assert.Equal(t, "1", cursor) 217 | } 218 | 219 | func TestGiphyProviderGetGifURLWhenNoRandomAndCursorIsZero(t *testing.T) { 220 | p, client, _ := generateGiphyProviderForURLBuildingTests(false) 221 | 222 | // Initial value : 0 223 | cursor := "0" 224 | client.testRequestFunc = func(req *http.Request) bool { 225 | assert.Contains(t, req.URL.RawQuery, "offset=0") 226 | return true 227 | } 228 | 229 | _, err := p.GetGifURL("cat", &cursor, false) 230 | assert.Nil(t, err) 231 | assert.True(t, client.lastRequestPassTest) 232 | assert.Equal(t, "1", cursor) 233 | } 234 | 235 | func TestGiphyProviderGetGifURLWhenNoRandomAndCursorIsNotANumber(t *testing.T) { 236 | p, client, _ := generateGiphyProviderForURLBuildingTests(false) 237 | 238 | // Initial value : not a number, that should be ignored 239 | cursor := "hahaha" 240 | client.testRequestFunc = func(req *http.Request) bool { 241 | assert.NotContains(t, "offset", req.URL.RawQuery) 242 | return true 243 | } 244 | 245 | _, err := p.GetGifURL("cat", &cursor, false) 246 | assert.Nil(t, err) 247 | assert.True(t, client.lastRequestPassTest) 248 | assert.Equal(t, "1", cursor) 249 | } 250 | 251 | func TestGiphyProviderGetGifURLShouldApplyRatingFilterWhenUnset(t *testing.T) { 252 | for _, testCase := range generateSearchAndRandomTestCases(defaultGiphyResponseBodyForSearch, defaultGiphyResponseBodyForRandom) { 253 | p, client, cursor := generateGiphyProviderForURLBuildingTests(testCase.random) 254 | p.rating = "" 255 | client.testRequestFunc = func(req *http.Request) bool { 256 | assert.NotContains(t, req.URL.RawQuery, "rating") 257 | return true 258 | } 259 | 260 | _, err := p.GetGifURL("cat", &cursor, testCase.random) 261 | assert.Nil(t, err, testCase.label) 262 | assert.True(t, client.lastRequestPassTest, testCase.label) 263 | } 264 | } 265 | 266 | func TestGiphyProviderGetGifURLShouldApplyRatingFilterWhenNoRandomAndRatingFilter(t *testing.T) { 267 | p, client, cursor := generateGiphyProviderForURLBuildingTests(false) 268 | p.rating = "RATING" 269 | client.testRequestFunc = func(req *http.Request) bool { 270 | assert.Contains(t, req.URL.RawQuery, "rating="+p.rating) 271 | return true 272 | } 273 | 274 | _, err := p.GetGifURL("cat", &cursor, false) 275 | assert.Nil(t, err) 276 | assert.True(t, client.lastRequestPassTest) 277 | } 278 | 279 | func TestGiphyProviderGetGifURLShouldNotApplyLanguageFilterWhenNoRandomAndNoLanguageSet(t *testing.T) { 280 | p, client, cursor := generateGiphyProviderForURLBuildingTests(false) 281 | p.language = "" 282 | client.testRequestFunc = func(req *http.Request) bool { 283 | assert.NotContains(t, req.URL.RawQuery, "lang") 284 | return true 285 | } 286 | 287 | _, err := p.GetGifURL("cat", &cursor, false) 288 | assert.Nil(t, err) 289 | assert.True(t, client.lastRequestPassTest) 290 | } 291 | 292 | func TestGiphyProviderGetGifURLShouldApplyLanguageFilterWhenNoRandomAndLanguageSet(t *testing.T) { 293 | p, client, cursor := generateGiphyProviderForURLBuildingTests(false) 294 | p.language = "Moldovalaque" 295 | client.testRequestFunc = func(req *http.Request) bool { 296 | assert.Contains(t, req.URL.RawQuery, "lang="+p.language) 297 | return true 298 | } 299 | 300 | _, err := p.GetGifURL("cat", &cursor, false) 301 | assert.Nil(t, err) 302 | assert.True(t, client.lastRequestPassTest) 303 | } 304 | -------------------------------------------------------------------------------- /server/internal/provider/tenor.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | 8 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 9 | 10 | "github.com/mattermost/mattermost/server/public/model" 11 | ) 12 | 13 | // NewTenorProvider creates an instance of a GIF provider that uses the Tenor API 14 | func NewTenorProvider(httpClient HTTPClient, errorGenerator pluginError.PluginError, apiKey, language, rating, rendition string) (GifProvider, *model.AppError) { 15 | if errorGenerator == nil { 16 | return nil, model.NewAppError("NewTenorProvider", "errorGenerator cannot be nil for Giphy Provider", nil, "", http.StatusInternalServerError) 17 | } 18 | if httpClient == nil { 19 | return nil, errorGenerator.FromMessage("httpClient cannot be nil for Giphy Provider") 20 | } 21 | if apiKey == "" { 22 | return nil, errorGenerator.FromMessage("apiKey cannot be empty for Tenor Provider") 23 | } 24 | if rendition == "" { 25 | return nil, errorGenerator.FromMessage("rendition cannot be empty for Tenor Provider") 26 | } 27 | 28 | tenorProvider := tenor{} 29 | tenorProvider.httpClient = httpClient 30 | tenorProvider.errorGenerator = errorGenerator 31 | tenorProvider.apiKey = apiKey 32 | tenorProvider.language = language 33 | tenorProvider.rating = convertRatingToContentFilter(rating) 34 | tenorProvider.rendition = rendition 35 | 36 | return &tenorProvider, nil 37 | } 38 | 39 | // tenor find GIFs using the tenor API 40 | type tenor struct { 41 | abstractGifProvider 42 | apiKey string 43 | } 44 | 45 | const ( 46 | baseURLTenor = "https://tenor.googleapis.com/v2" 47 | ) 48 | 49 | type tenorSearchResult struct { 50 | Next string `json:"next"` 51 | Results []struct { 52 | Media map[string]struct { 53 | URL string `json:"url"` 54 | } `json:"media_formats"` 55 | } `json:"results"` 56 | } 57 | 58 | type tenorSearchError struct { 59 | Error string `json:"error"` 60 | Code string `json:"code"` 61 | } 62 | 63 | func (p *tenor) GetAttributionMessage() string { 64 | return "Via Tenor" 65 | } 66 | 67 | // Return the URL of a GIF that matches the query, or an empty string if no GIF matches the query, or an error if the search failed 68 | func (p *tenor) GetGifURL(request string, cursor *string, random bool) ([]string, *model.AppError) { 69 | req, err := http.NewRequest("GET", baseURLTenor+"/search", nil) 70 | if err != nil { 71 | return []string{}, p.errorGenerator.FromError("Could not generate URL", err) 72 | } 73 | 74 | q := req.URL.Query() 75 | 76 | q.Add("key", p.apiKey) 77 | q.Add("q", request) 78 | q.Add("ar_range", "all") 79 | if cursor != nil && *cursor != "" { 80 | q.Add("pos", *cursor) 81 | } 82 | 83 | // if random, we need to have several results because tenor applies tne random=true parameter only to the result list of this query 84 | q.Add("contentfilter", p.rating) 85 | q.Add("media_filter", p.rendition) 86 | if len(p.language) > 0 { 87 | q.Add("locale", p.language) 88 | } 89 | if random { 90 | q.Add("random", "true") 91 | } 92 | 93 | req.URL.RawQuery = q.Encode() 94 | 95 | r, err := p.httpClient.Do(req) 96 | if err != nil { 97 | return []string{}, p.errorGenerator.FromError("Error calling the Tenor API", err) 98 | } 99 | if r != nil && r.Body != nil { 100 | defer r.Body.Close() 101 | } 102 | 103 | if r.StatusCode != http.StatusOK { 104 | var errorResponse tenorSearchError 105 | errorDetails := fmt.Sprintf("Error calling the Tenor API (HTTP Status: %v", r.Status) 106 | if r.Body != nil { 107 | decoder := json.NewDecoder(r.Body) 108 | if err = decoder.Decode(&errorResponse); err == nil && errorResponse.Error != "" { 109 | errorDetails += ", API message: \"" + errorResponse.Error + "\"" 110 | } 111 | } 112 | errorDetails += ")" 113 | return []string{}, p.errorGenerator.FromMessage(errorDetails) 114 | } 115 | 116 | var response tenorSearchResult 117 | if r.Body == nil { 118 | return []string{}, p.errorGenerator.FromMessage("Tenor search response body is empty") 119 | } 120 | 121 | decoder := json.NewDecoder(r.Body) 122 | if err = decoder.Decode(&response); err != nil { 123 | return []string{}, p.errorGenerator.FromError("Could not parse Tenor search response body", err) 124 | } 125 | 126 | if len(response.Results) < 1 { 127 | return []string{}, nil 128 | } 129 | 130 | urls := []string{} 131 | for i := range response.Results { 132 | url := response.Results[i].Media[p.rendition].URL 133 | if len(url) > 0 { 134 | urls = append(urls, url) 135 | } 136 | } 137 | 138 | if len(urls) < 1 { 139 | return []string{}, p.errorGenerator.FromMessage("No gifs found for display style \"" + p.rendition + "\" in the response") 140 | } 141 | 142 | *cursor = response.Next 143 | 144 | return urls, nil 145 | } 146 | 147 | func convertRatingToContentFilter(rating string) string { 148 | switch rating { 149 | case "g": 150 | return "high" 151 | case "pg": 152 | return "medium" 153 | case "pg-13": 154 | return "low" 155 | default: 156 | return "off" 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /server/internal/provider/tenor_test.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | 7 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 8 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | const defaultTenorResponseBody = `{ 14 | "results": [ 15 | { 16 | "id": "4242424242", 17 | "title": "", 18 | "media_formats": { 19 | "tinygifpreview": { 20 | "url": "https://fakeurl/tinygifpreview", 21 | "duration": 0, 22 | "preview": "", 23 | "dims": [ 24 | 220, 25 | 220 26 | ], 27 | "size": 42 28 | }, 29 | "mp4": { 30 | "url": "https://fakeurl/mp4", 31 | "duration": 3.3, 32 | "preview": "", 33 | "dims": [ 34 | 640, 35 | 640 36 | ], 37 | "size": 42 38 | }, 39 | "tinywebm": { 40 | "url": "https://fakeurl/tinywebm", 41 | "duration": 0, 42 | "preview": "", 43 | "dims": [ 44 | 232, 45 | 232 46 | ], 47 | "size": 42 48 | }, 49 | "webm": { 50 | "url": "https://fakeurl/webm", 51 | "duration": 0, 52 | "preview": "", 53 | "dims": [ 54 | 640, 55 | 640 56 | ], 57 | "size": 42 58 | }, 59 | "tinymp4": { 60 | "url": "https://fakeurl/tinymp4", 61 | "duration": 3.4, 62 | "preview": "", 63 | "dims": [ 64 | 232, 65 | 232 66 | ], 67 | "size": 42 68 | }, 69 | "nanogif": { 70 | "url": "https://fakeurl/nanogif", 71 | "duration": 0, 72 | "preview": "", 73 | "dims": [ 74 | 90, 75 | 90 76 | ], 77 | "size": 42 78 | }, 79 | "gifpreview": { 80 | "url": "https://fakeurl/gifpreview", 81 | "duration": 0, 82 | "preview": "", 83 | "dims": [ 84 | 640, 85 | 640 86 | ], 87 | "size": 42 88 | }, 89 | "nanomp4": { 90 | "url": "https://fakeurl/nanomp4", 91 | "duration": 3.4, 92 | "preview": "", 93 | "dims": [ 94 | 120, 95 | 120 96 | ], 97 | "size": 42 98 | }, 99 | "gif": { 100 | "url": "https://fakeurl/gif", 101 | "duration": 0, 102 | "preview": "", 103 | "dims": [ 104 | 498, 105 | 498 106 | ], 107 | "size": 42 108 | }, 109 | "tinygif": { 110 | "url": "https://fakeurl/tinygif", 111 | "duration": 0, 112 | "preview": "", 113 | "dims": [ 114 | 220, 115 | 220 116 | ], 117 | "size": 42 118 | }, 119 | "nanogifpreview": { 120 | "url": "https://fakeurl/nanogifpreview", 121 | "duration": 0, 122 | "preview": "", 123 | "dims": [ 124 | 90, 125 | 90 126 | ], 127 | "size": 42 128 | }, 129 | "mediumgif": { 130 | "url": "https://fakeurl/mediumgif", 131 | "duration": 0, 132 | "preview": "", 133 | "dims": [ 134 | 640, 135 | 640 136 | ], 137 | "size": 42 138 | }, 139 | "loopedmp4": { 140 | "url": "https://fakeurl/loopedmp4", 141 | "duration": 3.3, 142 | "preview": "", 143 | "dims": [ 144 | 640, 145 | 640 146 | ], 147 | "size": 42 148 | }, 149 | "nanowebm": { 150 | "url": "https://fakeurl/nanowebm", 151 | "duration": 0, 152 | "preview": "", 153 | "dims": [ 154 | 120, 155 | 120 156 | ], 157 | "size": 42 158 | } 159 | }, 160 | "content_description": "some content description", 161 | "url": "https://fakeurl/fake.gif", 162 | "tags": [], 163 | "flags": [], 164 | "hasaudio": false 165 | } 166 | ], 167 | "next": "some-guid" 168 | }` 169 | 170 | const ( 171 | testTenorAPIKey = "apikey" 172 | testTenorLanguage = "fr" 173 | testTenorRating = "R" 174 | testTenorRendition = "mediumgif" 175 | ) 176 | 177 | func TestNewTenorProvider(t *testing.T) { 178 | testtHTTPClient := NewMockHTTPClient(newServerResponseOK(defaultTenorResponseBody)) 179 | testErrorGenerator := test.MockErrorGenerator() 180 | testCases := []struct { 181 | testLabel string 182 | paramHTTPClient HTTPClient 183 | paramErrorGenerator pluginError.PluginError 184 | paramAPIKey string 185 | paramRating string 186 | paramLanguage string 187 | paramRendition string 188 | expectedError bool 189 | expectedRating string 190 | }{ 191 | {testLabel: "OK", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: testTenorRating, paramRendition: testTenorRendition, expectedError: false, expectedRating: "off"}, 192 | {testLabel: "KO missing rendition", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: testTenorRating, paramRendition: "", expectedError: true}, 193 | {testLabel: "OK empty rating (legacy: empty string)", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "", paramRendition: testTenorRendition, expectedError: false, expectedRating: "off"}, 194 | {testLabel: "OK empty rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "none", paramRendition: testTenorRendition, expectedError: false, expectedRating: "off"}, 195 | {testLabel: "OK r rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "r", paramRendition: testTenorRendition, expectedError: false, expectedRating: "off"}, 196 | {testLabel: "OK g rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "g", paramRendition: testTenorRendition, expectedError: false, expectedRating: "high"}, 197 | {testLabel: "OK pg rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "pg", paramRendition: testTenorRendition, expectedError: false, expectedRating: "medium"}, 198 | {testLabel: "OK pg-13 rating", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: "pg-13", paramRendition: testTenorRendition, expectedError: false, expectedRating: "low"}, 199 | {testLabel: "OK empty language", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: "", paramRating: testTenorRating, paramRendition: testTenorRendition, expectedError: false, expectedRating: "off"}, 200 | {testLabel: "KO empty api key", paramHTTPClient: testtHTTPClient, paramErrorGenerator: testErrorGenerator, paramAPIKey: "", paramLanguage: testTenorLanguage, paramRating: testTenorRating, paramRendition: testTenorRendition, expectedError: true, expectedRating: "off"}, 201 | {testLabel: "KO nil errorGenerator", paramHTTPClient: testtHTTPClient, paramErrorGenerator: nil, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: testTenorRating, paramRendition: testTenorRendition, expectedError: true, expectedRating: "off"}, 202 | {testLabel: "KO nil httpClient", paramHTTPClient: nil, paramErrorGenerator: testErrorGenerator, paramAPIKey: testTenorAPIKey, paramLanguage: testTenorLanguage, paramRating: testTenorRating, paramRendition: testTenorRendition, expectedError: true, expectedRating: "off"}, 203 | {testLabel: "KO all empty", paramHTTPClient: nil, paramErrorGenerator: nil, paramAPIKey: "", paramLanguage: "", paramRating: "", paramRendition: "", expectedError: true}, 204 | } 205 | 206 | for _, testCase := range testCases { 207 | provider, err := NewTenorProvider(testCase.paramHTTPClient, testCase.paramErrorGenerator, testCase.paramAPIKey, testCase.paramLanguage, testCase.paramRating, testCase.paramRendition) 208 | if testCase.expectedError { 209 | assert.NotNil(t, err, testCase.testLabel) 210 | assert.Nil(t, provider, testCase.testLabel) 211 | } else { 212 | assert.Nil(t, err, testCase.testLabel) 213 | assert.NotNil(t, provider, testCase.testLabel) 214 | assert.IsType(t, &tenor{}, provider, testCase.testLabel) 215 | assert.Equal(t, testCase.paramHTTPClient, provider.(*tenor).httpClient, testCase.testLabel) 216 | assert.Equal(t, testCase.paramErrorGenerator, provider.(*tenor).errorGenerator, testCase.testLabel) 217 | assert.Equal(t, testCase.paramAPIKey, provider.(*tenor).apiKey, testCase.testLabel) 218 | assert.Equal(t, testCase.paramLanguage, provider.(*tenor).language, testCase.testLabel) 219 | assert.Equal(t, testCase.expectedRating, provider.(*tenor).rating, testCase.testLabel) 220 | assert.Equal(t, testCase.paramRendition, provider.(*tenor).rendition, testCase.testLabel) 221 | } 222 | } 223 | } 224 | 225 | func generateTenorProviderForTest(mockHTTPResponse *http.Response) *tenor { 226 | provider, _ := NewTenorProvider(NewMockHTTPClient(mockHTTPResponse), test.MockErrorGenerator(), testTenorAPIKey, testTenorLanguage, testTenorRating, testTenorRendition) 227 | return provider.(*tenor) 228 | } 229 | 230 | func TestTenorProviderGetGifURLShouldReturnUrlWhenSearchSucceeds(t *testing.T) { 231 | p := generateTenorProviderForTest(newServerResponseOK(defaultTenorResponseBody)) 232 | p.rendition = "tinygif" 233 | cursor := "" 234 | url, err := p.GetGifURL("cat", &cursor, false) 235 | assert.Nil(t, err) 236 | assert.NotEmpty(t, url) 237 | assert.Equal(t, url, []string{"https://fakeurl/tinygif"}) 238 | } 239 | 240 | func TestTenorProviderGetGifURLShouldFailIfSearchBodyIsEmpty(t *testing.T) { 241 | p := generateTenorProviderForTest(newServerResponseOK("")) 242 | cursor := "" 243 | url, err := p.GetGifURL("cat", &cursor, false) 244 | assert.NotNil(t, err) 245 | assert.Contains(t, err.Error(), "empty") 246 | assert.Empty(t, url) 247 | } 248 | 249 | func TestTenorProviderGetGifURLShouldFailWhenParseError(t *testing.T) { 250 | p := generateTenorProviderForTest(newServerResponseOK("This is not a valid JSON response")) 251 | cursor := "" 252 | url, err := p.GetGifURL("cat", &cursor, false) 253 | assert.NotNil(t, err) 254 | assert.Empty(t, url) 255 | } 256 | 257 | func TestTenorProviderGetGifURLShouldReturnEmptyUrlWhenSearchReturnNoResult(t *testing.T) { 258 | p := generateTenorProviderForTest(newServerResponseOK("{ \"weburl\": \"https://fakeurl/casdfsdfsdfsdfsdfst-gifs\", \"results\": [], \"next\": \"0\" }")) 259 | cursor := "" 260 | url, err := p.GetGifURL("cat", &cursor, false) 261 | assert.Nil(t, err) 262 | assert.Empty(t, url) 263 | } 264 | 265 | func TestTenorProviderGetGifURLShouldFailWhenNoURLForRendition(t *testing.T) { 266 | p := generateTenorProviderForTest(newServerResponseOK(defaultTenorResponseBody)) 267 | p.rendition = "NotExistingDisplayStyle" 268 | cursor := "" 269 | url, err := p.GetGifURL("cat", &cursor, false) 270 | assert.NotNil(t, err) 271 | assert.Contains(t, err.Error(), "No gifs found for display style") 272 | assert.Contains(t, err.Error(), p.rendition) 273 | assert.Empty(t, url) 274 | } 275 | 276 | func TestTenorProviderGetGifURLShouldFailWhenSearchBadStatusWithoutMessage(t *testing.T) { 277 | serverResponse := newServerResponseKO(400) 278 | p := generateTenorProviderForTest(serverResponse) 279 | cursor := "" 280 | url, err := p.GetGifURL("cat", &cursor, false) 281 | assert.NotNil(t, err) 282 | assert.Contains(t, err.Error(), serverResponse.Status) 283 | assert.Empty(t, url) 284 | } 285 | 286 | func TestTenorProviderGetGifURLShouldFailWhenSearchBadStatusWithMessage(t *testing.T) { 287 | serverResponse := newServerResponseKOWithBody(429, "{ \"error\": \"Please use a registered API Key\" }") 288 | p := generateTenorProviderForTest(serverResponse) 289 | cursor := "" 290 | url, err := p.GetGifURL("cat", &cursor, false) 291 | assert.NotNil(t, err) 292 | assert.Contains(t, err.Error(), serverResponse.Status) 293 | assert.Contains(t, err.Error(), "Please use a registered API Key") 294 | assert.Empty(t, url) 295 | } 296 | 297 | func generateTenorProviderForURLBuildingTests() (*tenor, *MockHTTPClient, string) { 298 | serverResponse := newServerResponseOK(defaultTenorResponseBody) 299 | client := NewMockHTTPClient(serverResponse) 300 | provider, _ := NewTenorProvider(client, test.MockErrorGenerator(), testTenorAPIKey, testTenorLanguage, testTenorRating, testTenorRendition) 301 | return provider.(*tenor), client, "" 302 | } 303 | 304 | func TestTenorProviderGetGifURLShouldApplyRatingFilterWhenSet(t *testing.T) { 305 | p, client, cursor := generateTenorProviderForURLBuildingTests() 306 | client.testRequestFunc = func(req *http.Request) bool { 307 | assert.Contains(t, req.URL.RawQuery, "contentfilter=off") 308 | return true 309 | } 310 | _, err := p.GetGifURL("cat", &cursor, false) 311 | assert.Nil(t, err) 312 | assert.True(t, client.lastRequestPassTest) 313 | } 314 | 315 | func TestTenorProviderGetGifURLShouldApplyLanguageFilterWhenUnset(t *testing.T) { 316 | p, client, cursor := generateTenorProviderForURLBuildingTests() 317 | p.language = "" 318 | client.testRequestFunc = func(req *http.Request) bool { 319 | assert.NotContains(t, req.URL.RawQuery, "locale") 320 | return true 321 | } 322 | _, err := p.GetGifURL("cat", &cursor, false) 323 | assert.Nil(t, err) 324 | assert.True(t, client.lastRequestPassTest) 325 | } 326 | 327 | func TestTenorProviderGetGifURLShouldApplyLanguageFilterWhenSet(t *testing.T) { 328 | p, client, cursor := generateTenorProviderForURLBuildingTests() 329 | p.language = "Moldovalaque" 330 | client.testRequestFunc = func(req *http.Request) bool { 331 | assert.Contains(t, req.URL.RawQuery, "locale="+p.language) 332 | return true 333 | } 334 | _, err := p.GetGifURL("cat", &cursor, false) 335 | assert.Nil(t, err) 336 | assert.True(t, client.lastRequestPassTest) 337 | } 338 | 339 | func TestTenorProviderGetGifURLShouldAddRandomOptionWhenRequired(t *testing.T) { 340 | p, client, cursor := generateTenorProviderForURLBuildingTests() 341 | client.testRequestFunc = func(req *http.Request) bool { 342 | assert.Contains(t, req.URL.RawQuery, "random=true") 343 | assert.NotContains(t, req.URL.RawQuery, "limit=1") 344 | return true 345 | } 346 | _, err := p.GetGifURL("cat", &cursor, true) 347 | assert.Nil(t, err) 348 | assert.True(t, client.lastRequestPassTest) 349 | } 350 | -------------------------------------------------------------------------------- /server/internal/provider/utils_test.go: -------------------------------------------------------------------------------- 1 | package provider 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "net/http" 7 | "strconv" 8 | ) 9 | 10 | type MockHTTPClient struct { 11 | response *http.Response 12 | testRequestFunc func(*http.Request) bool 13 | lastRequestPassTest bool 14 | } 15 | 16 | func (c *MockHTTPClient) Do(req *http.Request) (*http.Response, error) { 17 | if c.testRequestFunc != nil { 18 | c.lastRequestPassTest = c.testRequestFunc(req) 19 | } 20 | return c.response, nil 21 | } 22 | 23 | func (c *MockHTTPClient) Get(_ string) (*http.Response, error) { 24 | return c.response, nil 25 | } 26 | 27 | func NewMockHTTPClient(res *http.Response) *MockHTTPClient { 28 | return &MockHTTPClient{ 29 | response: res, 30 | testRequestFunc: nil, 31 | } 32 | } 33 | 34 | func newServerResponseOK(body string) *http.Response { 35 | r := &http.Response{ 36 | StatusCode: 200, 37 | } 38 | if body != "" { 39 | r.Body = io.NopCloser(bytes.NewBufferString(body)) 40 | } 41 | return r 42 | } 43 | 44 | func newServerResponseKO(statusCode int) *http.Response { 45 | return &http.Response{ 46 | StatusCode: statusCode, 47 | Status: strconv.Itoa(statusCode), 48 | } 49 | } 50 | 51 | func newServerResponseKOWithBody(statusCode int, body string) *http.Response { 52 | return &http.Response{ 53 | StatusCode: statusCode, 54 | Body: io.NopCloser(bytes.NewBufferString(body)), 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /server/internal/test/helpers.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 4 | 5 | func MockErrorGenerator() pluginError.PluginError { 6 | return pluginError.NewPluginErrorGenerator("test") 7 | } 8 | -------------------------------------------------------------------------------- /server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | manifest "github.com/moussetc/mattermost-plugin-giphy" 5 | 6 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 7 | 8 | "github.com/mattermost/mattermost/server/public/plugin" 9 | ) 10 | 11 | func main() { 12 | p := Plugin{} 13 | p.errorGenerator = pluginError.NewPluginErrorGenerator(manifest.Manifest.Name) 14 | plugin.ClientMain(&p) 15 | } 16 | -------------------------------------------------------------------------------- /server/plugin.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "strings" 6 | "sync" 7 | 8 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 9 | pluginError "github.com/moussetc/mattermost-plugin-giphy/server/internal/error" 10 | pluginapi "github.com/moussetc/mattermost-plugin-giphy/server/internal/pluginapi" 11 | provider "github.com/moussetc/mattermost-plugin-giphy/server/internal/provider" 12 | 13 | "github.com/mattermost/mattermost/server/public/model" 14 | "github.com/mattermost/mattermost/server/public/plugin" 15 | 16 | "github.com/pkg/errors" 17 | ) 18 | 19 | const ( 20 | contextKeywords = "keywords" 21 | contextCaption = "caption" 22 | contextGifURLs = "gifURLs" 23 | contextCurrentIndex = "currentGifIndex" 24 | contextAPICursor = "searchCursor" 25 | contextRootID = "rootId" 26 | ) 27 | 28 | // Plugin is a Mattermost plugin that adds a /gif slash command 29 | // to display a GIF based on user keywords. 30 | type Plugin struct { 31 | plugin.MattermostPlugin 32 | 33 | configurationLock sync.RWMutex 34 | configuration *pluginConf.Configuration 35 | 36 | pluginClient *pluginapi.Client 37 | 38 | errorGenerator pluginError.PluginError 39 | gifProvider provider.GifProvider 40 | httpHandler pluginHTTPHandler 41 | botID string 42 | rootURL string 43 | } 44 | 45 | // OnActivate register the plugin commands 46 | func (p *Plugin) OnActivate() error { 47 | if configurationErr := p.getConfiguration().IsValid(); configurationErr != nil { 48 | return errors.Wrap(configurationErr, "Unable to activate the plugin with an invalid configuration") 49 | } 50 | 51 | if p.pluginClient == nil { 52 | p.pluginClient = pluginapi.NewClient(p.API, p.Driver) 53 | } 54 | 55 | p.httpHandler = &defaultHTTPHandler{} 56 | 57 | if err := p.RegisterCommands(); err != nil { 58 | return errors.Wrap(err, "Could not define plugin slash commands") 59 | } 60 | 61 | if err := p.defineBot(); err != nil { 62 | return errors.Wrap(err, "Could not define plugin bot") 63 | } 64 | 65 | return nil 66 | } 67 | 68 | // ExecuteCommand dispatch the command based on the trigger word 69 | func (p *Plugin) ExecuteCommand(_ *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { 70 | config := p.getConfiguration() 71 | 72 | if strings.HasPrefix(args.Command, "/"+config.CommandTriggerGifWithPreview) { 73 | keywords, caption, parseErr := parseCommandLine(args.Command, config.CommandTriggerGifWithPreview) 74 | if parseErr != nil { 75 | return nil, p.errorGenerator.FromMessage(parseErr.Error()) 76 | } 77 | return p.executeCommandGifWithPreview(keywords, caption, args) 78 | } 79 | if strings.HasPrefix(args.Command, "/"+config.CommandTriggerGif) { 80 | keywords, caption, parseErr := parseCommandLine(args.Command, config.CommandTriggerGif) 81 | if parseErr != nil { 82 | return nil, p.errorGenerator.FromMessage(parseErr.Error()) 83 | } 84 | return p.executeCommandGif(keywords, caption, args) 85 | } 86 | 87 | return nil, p.errorGenerator.FromMessage("Command trigger " + args.Command + "is not supported by this plugin.") 88 | } 89 | 90 | // ServeHTTP serve the post actions for the shuffle command 91 | func (p *Plugin) ServeHTTP(_ *plugin.Context, w http.ResponseWriter, r *http.Request) { 92 | p.handleHTTPRequest(w, r) 93 | } 94 | -------------------------------------------------------------------------------- /server/plugin_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "net/http" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/golang/mock/gomock" 10 | manifest "github.com/moussetc/mattermost-plugin-giphy" 11 | pluginConf "github.com/moussetc/mattermost-plugin-giphy/server/internal/configuration" 12 | pluginapi "github.com/moussetc/mattermost-plugin-giphy/server/internal/pluginapi" 13 | mock_pluginapi "github.com/moussetc/mattermost-plugin-giphy/server/internal/pluginapi/mock_pluginapi" 14 | "github.com/moussetc/mattermost-plugin-giphy/server/internal/test" 15 | "github.com/stretchr/testify/assert" 16 | 17 | "github.com/mattermost/mattermost/server/public/model" 18 | "github.com/mattermost/mattermost/server/public/plugin" 19 | "github.com/mattermost/mattermost/server/public/plugin/plugintest" 20 | "github.com/mattermost/mattermost/server/public/plugin/plugintest/mock" 21 | ) 22 | 23 | func generateMockPluginConfig() pluginConf.Configuration { 24 | return pluginConf.Configuration{ 25 | DisplayMode: pluginConf.DisplayModeEmbedded, 26 | Provider: "giphy", 27 | Language: "fr", 28 | Rating: "none", 29 | Rendition: "fixed_height_small", 30 | RenditionTenor: "tinygif", 31 | APIKey: "defaultAPIKey", 32 | CommandTriggerGif: triggerGif, 33 | CommandTriggerGifWithPreview: triggerGifs, 34 | } 35 | } 36 | 37 | func mockLoadConfig(conf pluginConf.Configuration) func(dest interface{}) error { 38 | return func(dest interface{}) error { 39 | *dest.(*pluginConf.Configuration) = conf 40 | return nil 41 | } 42 | } 43 | 44 | type mockHTTPHandler struct{} 45 | 46 | func (h *mockHTTPHandler) handleCancel(_ *Plugin, w http.ResponseWriter, _ *integrationRequest) { 47 | w.WriteHeader(http.StatusOK) 48 | } 49 | func (h *mockHTTPHandler) handleShuffle(_ *Plugin, w http.ResponseWriter, _ *integrationRequest) { 50 | w.WriteHeader(http.StatusOK) 51 | } 52 | func (h *mockHTTPHandler) handlePrevious(_ *Plugin, w http.ResponseWriter, _ *integrationRequest) { 53 | w.WriteHeader(http.StatusOK) 54 | } 55 | func (h *mockHTTPHandler) handleSend(_ *Plugin, w http.ResponseWriter, _ *integrationRequest) { 56 | w.WriteHeader(http.StatusOK) 57 | } 58 | 59 | func initMockAPI() (api *plugintest.API, p *Plugin) { 60 | api = &plugintest.API{} 61 | 62 | pluginConfig := generateMockPluginConfig() 63 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(pluginConfig)) 64 | p = &Plugin{} 65 | p.configuration = &pluginConfig 66 | p.SetAPI(api) 67 | p.botID = "botId42" 68 | p.httpHandler = &mockHTTPHandler{} 69 | p.errorGenerator = test.MockErrorGenerator() 70 | return api, p 71 | } 72 | 73 | func TestGeneratedManifestShouldBeValid(t *testing.T) { 74 | assert.Nil(t, manifest.Manifest.IsValid()) 75 | } 76 | 77 | func TestOnActivateWithBadConfig(t *testing.T) { 78 | api := &plugintest.API{} 79 | config := generateMockPluginConfig() 80 | config.DisplayMode = "" 81 | config.APIKey = "" 82 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(config)) 83 | p := Plugin{} 84 | p.SetAPI(api) 85 | 86 | assert.NotNil(t, p.OnActivate()) 87 | } 88 | 89 | func TestOnActivateWithoutSiteURL(t *testing.T) { 90 | api := &plugintest.API{} 91 | config := generateMockPluginConfig() 92 | config.APIKey = "" 93 | api.On("LoadPluginConfiguration", mock.AnythingOfType("*configuration.Configuration")).Return(mockLoadConfig(config)) 94 | p := Plugin{} 95 | p.SetAPI(api) 96 | 97 | assert.NotNil(t, p.OnActivate()) 98 | } 99 | 100 | func TestOnActivateOK(t *testing.T) { 101 | api := &plugintest.API{} 102 | config := generateMockPluginConfig() 103 | api.On("GetServerVersion").Return("42.0.0") 104 | api.On("RegisterCommand", mock.Anything).Return(nil) 105 | api.On("UnregisterCommand", mock.Anything, mock.Anything).Return(nil) 106 | api.On("EnsureBotUser", mock.Anything).Return(model.NewId(), nil) 107 | api.On("GetServerVersion").Return("6.3.0") 108 | p := Plugin{} 109 | p.configuration = &config 110 | p.SetAPI(api) 111 | p.errorGenerator = test.MockErrorGenerator() 112 | 113 | mockCtrl := gomock.NewController(t) 114 | defer mockCtrl.Finish() 115 | mockBot := mock_pluginapi.NewMockBotService(mockCtrl) 116 | mockBot.EXPECT().EnsureBot(gomock.Any(), gomock.Any()) 117 | p.pluginClient = &pluginapi.Client{Bot: mockBot} 118 | 119 | assert.Nil(t, p.OnActivate()) 120 | } 121 | 122 | func TestExecuteGifCommandToSendPost(t *testing.T) { 123 | _, p := initMockAPI() 124 | 125 | url := "http://fakeURL" 126 | p.gifProvider = &mockGifProvider{url} 127 | 128 | command := model.CommandArgs{ 129 | Command: "/gif cute doggo", 130 | UserId: "userid", 131 | } 132 | 133 | response, err := p.ExecuteCommand(&plugin.Context{}, &command) 134 | assert.Nil(t, err) 135 | assert.NotNil(t, response) 136 | assert.True(t, strings.Contains(response.Text, url)) 137 | assert.Equal(t, "in_channel", response.ResponseType) 138 | } 139 | 140 | func TestExecuteShuffleCommandToReturnCommandResponse(t *testing.T) { 141 | api, p := initMockAPI() 142 | url := "http://fakeURL" 143 | p.gifProvider = &mockGifProvider{url} 144 | 145 | command := model.CommandArgs{ 146 | Command: "/gifs cute doggo", 147 | UserId: "userid", 148 | } 149 | api.On("SendEphemeralPost", mock.AnythingOfType("string"), mock.AnythingOfType("*model.Post")).Return(nil, nil) 150 | response, err := p.ExecuteCommand(&plugin.Context{}, &command) 151 | assert.Nil(t, err) 152 | assert.NotNil(t, response) 153 | } 154 | 155 | func TestExecuteCommandFailWhenCommandHandlerFails(t *testing.T) { 156 | api, p := initMockAPI() 157 | api.On("LogWarn", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.Anything).Return(nil) 158 | 159 | errorMessage := "ARGHHHH" 160 | p.gifProvider = &mockGifProviderFail{errorMessage} 161 | 162 | response, err := p.ExecuteCommand(&plugin.Context{}, &model.CommandArgs{Command: "/gif cute doggo"}) 163 | assert.NotNil(t, err) 164 | assert.Empty(t, response) 165 | assert.True(t, strings.Contains(err.DetailedError, errorMessage)) 166 | } 167 | 168 | func TestExecuteUnkownCommand(t *testing.T) { 169 | _, p := initMockAPI() 170 | 171 | command := model.CommandArgs{ 172 | Command: "/worm cute doggo", 173 | UserId: "userid", 174 | } 175 | 176 | response, err := p.ExecuteCommand(&plugin.Context{}, &command) 177 | assert.NotNil(t, err) 178 | assert.Nil(t, response) 179 | } 180 | 181 | // mockGifProviderFail always fail to provide a GIF URL 182 | type mockGifProviderFail struct { 183 | errorMessage string 184 | } 185 | 186 | func (m *mockGifProviderFail) GetGifURL(_ string, _ *string, _ bool) ([]string, *model.AppError) { 187 | return []string{""}, (test.MockErrorGenerator()).FromError(m.errorMessage, errors.New(m.errorMessage)) 188 | } 189 | 190 | func (m *mockGifProviderFail) GetAttributionMessage() string { 191 | return "test" 192 | } 193 | 194 | // mockGifProvider always provides the same fake GIF URL 195 | type emptyGifProvider struct { 196 | } 197 | 198 | func (m *emptyGifProvider) GetGifURL(_ string, _ *string, _ bool) ([]string, *model.AppError) { 199 | return []string{}, nil 200 | } 201 | 202 | func (m *emptyGifProvider) GetAttributionMessage() string { 203 | return "test" 204 | } 205 | 206 | // mockGifProvider always provides the same fake GIF URL 207 | type mockGifProvider struct { 208 | mockURL string 209 | } 210 | 211 | func newMockGifProvider() *mockGifProvider { 212 | return &mockGifProvider{"fakeURL"} 213 | } 214 | 215 | func (m *mockGifProvider) GetGifURL(_ string, _ *string, _ bool) ([]string, *model.AppError) { 216 | return []string{m.mockURL}, nil 217 | } 218 | 219 | func (m *mockGifProvider) GetAttributionMessage() string { 220 | return "test" 221 | } 222 | --------------------------------------------------------------------------------