Skip to content

Commit

Permalink
Refactor calendar engine into its own package (#267)
Browse files Browse the repository at this point in the history
* oauth works

* autocomplete

* viewcal works

* add unimplemented if blocks

* fix tests and lint

* implement CreateMySubscription, RenewSubscription, and DeleteSubscription gcal methods

* WIP gcal subs

* setup-attach make target

* fix lint and tests

* chore: more compatible tar command

* add review comments

* [GCAL] Create event logic (#269)

* remote logic

* allow datetimes without timezone

* add calendar settings readonly scope to get tz

* event conversion

* scopes

* revert datetime.time

* bug: get timezone from datetime instead of event data (#271)

* [GCAL] Allow building two different plugins under the same codebase (#268)

* plugin profile images

* receive provider flag

* manifests

* retrieve manifest id from file

* Build time configuration

* revert manifest

* using go static configuration for providers

* removed unused build flags

* revert manifest

* Added basic Google Calendar instructions

* Update providers/GoogleCalendar.md

Co-authored-by: Michael Kochell <[email protected]>

* Update providers/GoogleCalendar.md

Co-authored-by: Michael Kochell <[email protected]>

* Update server/plugin/plugin.go

Co-authored-by: Michael Kochell <[email protected]>

* remoove log

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Endpoint to autocomplete connected calendar users (#275)

* user_store: more information fields on the index

* feat: endpoint to autocomplete calendar connected users

* revert test event store hashed

* Update server/api/autocomplete.go

Co-authored-by: Michael Kochell <[email protected]>

* Update server/api/autocomplete.go

Co-authored-by: Michael Kochell <[email protected]>

* dont expose private data in endpoint

* lint

* Update server/store/user_store.go

Co-authored-by: Michael Kochell <[email protected]>

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Refactor Microsoft Calendar references to provider references (#276)

* chore: replace provider display name

* chore: replace command trigger references

* revert previous changes

* [GCAL] Enable notifications and reminders when a superuser token is not supported (#272)

* nil control

* use subscriptions default ttl

* return specific error when no superuser token can be used

* notification formatting logic to other file

* Client.GetEventsBetweenDates

* typo: import

* shorter command name :)

* availability without super user token

* delete store subs only if we successfuly do on remote

* comment

* ignore missing subs

* update sync method

* allow switching acting user on the fly

* daily summary without super user token

* formatted imports

* calendar -> calendarEvents

* processAllDailySummaryByUser
 -> processAllDailySummaryWithIndividualCredentials

* revert silenced error under notifications

* msgraph GetEventsBetweenDates

* Update server/mscalendar/daily_summary.go

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Create event logic (#269)

* remote logic

* allow datetimes without timezone

* add calendar settings readonly scope to get tz

* event conversion

* scopes

* revert datetime.time

* Client.GetEventsBetweenDates

* fix: store last post time

* refactored availability logic

* availability test

* refactored daily summary logic

* test: availability

* daily summary tests (wip)

* daily summary test

* fix: merge duplications

* slack attachment for notifications

* lint and test

* goimports

* Update server/mscalendar/availability.go

Co-authored-by: Michael Kochell <[email protected]>

* remove logges

* nullify client when changing acting user

* move withActiveUser filter to fenced code outside of general method

* tests: handling more scenarios

* Fixed test after bugfix

* fixed test assertions

* allow engine copy to perform safe state mutations

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Added encrypted key value storage (#270)

* Added encrypted kvstore

* encrypt only oauth2 kv store

* retrieve encryption setting from provider config

* explicitly disable encrypted store for mscalendar

* remove old comment

* [GCAL] today/tomorrow commands with styling (#273)

* feat: added today and tomorrow commands with attachments

* remove unused function

* linted

* now -> day

* remove unused code

* today/tomorrow autocomplete

* return tables on today/tomorrow commands

* check for nil location

* revert tomorrow day times four

* fix markdown table render and test

* [GCAL] Fix test in main branch from PR merges (#277)

* fix: test from merges

* add meeting url

* [GCAL] Move configuration readyness logic to remotes (#279)

* Move configuration logic to remotes

* check encryption key as well

* Update server/plugin/plugin.go

Co-authored-by: Michael Kochell <[email protected]>

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Remove unused code (#278)

* remove batch requests from gcal code

* More info in readme

* [GCAL] Fix event notifications not working due to missing scope permissions plus internal state (#282)

* fix: notifications scope and acting user logic

* remove log

* avoid calling notifications if the engine fails to load

* [GCAL] Unsubscriptions (#283)

* fix: notifications scope and acting user logic

* fix: gcal unsubscribe requiring more parameters

* update gcal manifest (#285)

* [GCAL] Better logging information (#287)

* fix: better log information

* log missing error

* use correct manifest file on manifest calls (#290)

* [GCAL] Embed tzdata and correctly parse location from event datetime (#288)

* fix: embed tzdata to prevent errors on systems without it installed

* move to main

* avoid overwritting location if empty

* use tags instead of import

* [GCAL] Event notifications behind a feature flag (#292)

* put event notifications behind a feature flag

* admin only un/subscribe commands

* properly fence notification processor

* ignore notifications if there's no processor (#293)

* [GCAL] Remove join event column (broken from merges) (#294)

* remove join column from merges

* revert manifest

* [GCAL] Channels reminder underlying logic (#274)

* nil control

* use subscriptions default ttl

* return specific error when no superuser token can be used

* notification formatting logic to other file

* Client.GetEventsBetweenDates

* typo: import

* shorter command name :)

* availability without super user token

* delete store subs only if we successfuly do on remote

* comment

* ignore missing subs

* update sync method

* allow switching acting user on the fly

* daily summary without super user token

* formatted imports

* calendar -> calendarEvents

* processAllDailySummaryByUser
 -> processAllDailySummaryWithIndividualCredentials

* revert silenced error under notifications

* msgraph GetEventsBetweenDates

* Update server/mscalendar/daily_summary.go

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL] Create event logic (#269)

* remote logic

* allow datetimes without timezone

* add calendar settings readonly scope to get tz

* event conversion

* scopes

* revert datetime.time

* Client.GetEventsBetweenDates

* fix: store last post time

* refactored availability logic

* availability test

* refactored daily summary logic

* test: availability

* daily summary tests (wip)

* daily summary test

* fix: merge duplications

* slack attachment for notifications

* lint and test

* goimports

* Allow poster to create posts

* Allow store event metadata

* styling

* store recurring event id

* deliver channel notifications

* test: fixed for base case

* test: channel reminders

* test: recurring events

* move from slice to map

* Added store methods to interact with event metadata

* lint

* lint imports

* restore logic lost in merge

* duplicated test

* Update server/mscalendar/availability_test.go

Co-authored-by: Michael Kochell <[email protected]>

* remove recurrent event id field

---------

Co-authored-by: Michael Kochell <[email protected]>

* Updated google calendar readme

* [GCAL] Summary command fixes (#286)

* command trigger shown

* added autocomplete to summary command

* remove join meeting column

* fix event subjects with table separator

* fixed merge import

* replace more characters in subject

* [GCAL] Add a modal to create events (#281)

* add webapp folder

* WIP

* opening create event modal from slash command works

* add time selectors and initial impl of attendee selector

* delete .npminstall

* ignore .npminstall

* [GCAL/MSCAL] Add endpoint to create events from the frontend (#291)

* add remoteid to event attendee

* api endpoint

* conversion fixes

* api logic

* frontend logic to test

* check if user belongs to channel

* updated interface

* use api/v1 prefix

* implement getchannelmember

* all day events

* pluginAPI.CanLinkEventToChannel

* autocomplete users

* create event fetch call

* channel autocomplete

* improved error messages displayed to users

* better error handling

* channel selector store channel id

* properly set email addresses for attendees

* event location as string

* response messages

* little refactor

* attendee selector can invite arbitrary emails

* uppercase error dynamically

* lowercase error

* remove punctuation

* linted ts files

* goimports

* fixed import

* link events on creation

* Add channel action to create events

* add channel_id to payload

* time selector every 15 minutes

* time selector start/end with limits

* capitalized error messages

* don't allow 0 minute events

* display timezone in channel reminders

* utc time parsing

* remove nullfunc

* properly initialize variables

* address some comments

* npm run fix

* Update webapp/src/components/time_selector.tsx

Co-authored-by: Michael Kochell <[email protected]>

* Update webapp/src/components/time_selector.tsx

Co-authored-by: Michael Kochell <[email protected]>

* refactor options with useMemo

* capitalization in function for clarity

* npm run fix

* get plugin id from manifest

* remove no-ops

* refactor createEvent

* fix channel autocomplete url

* fix lint

* fix user string typo

* make it so `make apply` assumes gcal for now

* more careful error handling

* reorganize frontend error handling

* default to CALENDAR_PROVIDER=gcal

* use Client4.autocompleteChannels instead of custom plugin endpoint

* fix manifest test

---------

Co-authored-by: Michael Kochell <[email protected]>

* gofmt

---------

Co-authored-by: Felipe Martin <[email protected]>
Co-authored-by: Felipe Martin <[email protected]>

* [GCAL/MSCAL] Store linked events per user to remove links on disconnection (#296)

* add webapp folder

* WIP

* opening create event modal from slash command works

* add time selectors and initial impl of attendee selector

* delete .npminstall

* ignore .npminstall

* add remoteid to event attendee

* api endpoint

* conversion fixes

* api logic

* frontend logic to test

* check if user belongs to channel

* updated interface

* use api/v1 prefix

* implement getchannelmember

* all day events

* pluginAPI.CanLinkEventToChannel

* autocomplete users

* create event fetch call

* channel autocomplete

* improved error messages displayed to users

* better error handling

* channel selector store channel id

* properly set email addresses for attendees

* event location as string

* response messages

* little refactor

* attendee selector can invite arbitrary emails

* uppercase error dynamically

* lowercase error

* remove punctuation

* linted ts files

* goimports

* fixed import

* link events on creation

* Add channel action to create events

* add channel_id to payload

* time selector every 15 minutes

* time selector start/end with limits

* capitalized error messages

* don't allow 0 minute events

* display timezone in channel reminders

* utc time parsing

* remove nullfunc

* properly initialize variables

* address some comments

* npm run fix

* store linked events for user to remove links on disconnection

* typo

* remove unused items after merge

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL/MSCAL] Remind only accepted events (#295)

* remind only accepted events

* fixed tests

* excludeDeclinedEvents

* normalize msgraph event response

* Remove GoogleDomainVerifyKey setting (#299)

* fix: encrypt user store (#297)

* feat: send notifications when an event is created (#300)

* typo: user already connected message (#301)

* typo: user already connected message

* test: fix change

* typo: user already connected message (#301)

* typo: user already connected message

* test: fix change

* [GCAL/MSCAL] Exclude rejected events from agenda commands (#302)

* exclude rejected events from agenda commands

* test: check that declied event are excluded

* fix possible nil pointer

* [GCAL/MSCAL] Create event modal only for connected accounts (#303)

* only connected users chan use slash command

* prevent channel menu action from allowing too

* npm run fix

* lint errors

* retrieve provider configuration to use in messages

* websocket events

* add message to mobile users

* npm run fix

* Update webapp/src/plugin_hooks.ts

Co-authored-by: Michael Kochell <[email protected]>

* register modal in setup

* events create

* trigger from provide config

* using dispatch

* missing semicolon

* Update webapp/src/plugin_hooks.ts

Co-authored-by: Michael Kochell <[email protected]>

* singular

---------

Co-authored-by: Michael Kochell <[email protected]>

* updated settings to use style and removed current value line (#305)

* show link to connect if not connected (#306)

* [GCAL/MSCAL] Reduce welcome steps  (#308)

* reduce welcome steps and edit defaults

* Update server/mscalendar/welcome_flow.go

Co-authored-by: Michael Kochell <[email protected]>

---------

Co-authored-by: Michael Kochell <[email protected]>

* [GCAL/MSCAL] Control start/date times if the selected date is today (#307)

* improvements to create event datetimes

* reset starttime endtime on date change

* repopulate times if date changed

* npm run fix

* database replication workaround (#312)

* [GCAL/MSCAL] Catch errors when using `findmeetings` commands without enough parameters (#313)

* fix: handle error in find meetings parameters command

* changed loop variable usage

* Replace Equals with ElementsMatch

* makefile dist build for production (#314)

* [GCAL/MSCAL] Create event UX improvements (#309)

* Optional fields

* time picker defaults

* Add custom icon to Create Event menu item

* add custom icon to date selector

* npm run fix

* header menu icon multiline

* use scss

* using proper typeRoots

* scoped css style

* [GCAL] Store conference data (#298)

* extract conference data into new attribute

* removed log

* removed unused fuunction

* tests

* Update server/remote/gcal/get_default_calendar_view_test.go

Co-authored-by: Michael Kochell <[email protected]>

* more realistic datetime values

---------

Co-authored-by: Michael Kochell <[email protected]>

* Common code refactor, back to mscalendar plugin (#334)

* refactor: mscalendar -> engine

* remove gcal assets

* refactored common code outside server package

* check-style

* go mod tidy

* REPO_URL -> REPOSITORY_URL

* delete unknown file

* updated mocks

* apped user to handle after all actions (#335)

* refactor msgraph to mscalendar

* goimports

* removed apply command from merge

* remove "REVIEW:" comments

---------

Co-authored-by: Felipe Martin <[email protected]>
Co-authored-by: Felipe Martin <[email protected]>
  • Loading branch information
3 people authored Mar 1, 2024
1 parent b1bcb7b commit 7f1bbcd
Show file tree
Hide file tree
Showing 184 changed files with 3,863 additions and 1,417 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
dist
.DS_Store
.npminstall
111 changes: 105 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,26 @@ CURL ?= $(shell command -v curl 2> /dev/null)
MM_DEBUG ?=
MANIFEST_FILE ?= plugin.json
GOPATH ?= $(shell go env GOPATH)

MANIFEST_FILE ?= plugin.json

GO_TEST_FLAGS ?= -race
GO_BUILD_FLAGS ?=
GO_BUILD_FLAGS ?= -tags timetzdata
MM_UTILITIES_DIR ?= ../mattermost-utilities
DLV_DEBUG_PORT := 2346
DEFAULT_GOOS := $(shell go env GOOS)
DEFAULT_GOARCH := $(shell go env GOARCH)

export GO111MODULE=on

GO_PACKAGES ?= ./server/... ./calendar/... ./msgraph/...

# You can include assets this directory into the bundle. This can be e.g. used to include profile pictures.
ASSETS_DIR ?= assets

# Repository URL
REPOSITORY_URL ?= github.com/mattermost/mattermost-plugin-mscalendar

## Define the default target (make all)
.PHONY: default
default: all
Expand All @@ -41,7 +49,7 @@ endif
.PHONY: all
all: check-style test dist

## Runs eslint and golangci-lint
## Runs golangci-lint and eslint.
.PHONY: check-style
check-style: webapp/node_modules
@echo Checking for style guide compliance
Expand Down Expand Up @@ -94,17 +102,59 @@ webapp: webapp/node_modules
ifneq ($(HAS_WEBAPP),)
ifeq ($(MM_DEBUG),)
cd webapp && $(NPM) run build;
endif

## Builds the webapp in debug mode, if it exists.
.PHONY: webapp-debug
webapp-debug: webapp/.npminstall
ifneq ($(HAS_WEBAPP),)
cd webapp && \
$(NPM) run debug;
endif

# server-debug builds and deploys a debug version of the plugin for your architecture.
# Then resets the plugin to pick up the changes.
.PHONY: server-debug
server-debug: server-debug-deploy reset

.PHONY: server-debug-deploy
server-debug-deploy: validate-go-version
mkdir -p server/dist
ifeq ($(OS),Darwin)
cd server && env GOOS=darwin GOARCH=amd64 $(GOBUILD) -gcflags "all=-N -l" -o dist/plugin-darwin-amd64;
else ifeq ($(OS),Linux)
cd server && env GOOS=linux GOARCH=amd64 $(GOBUILD) -gcflags "all=-N -l" -o dist/plugin-linux-amd64;
else ifeq ($(OS),Windows_NT)
cd server && env GOOS=windows GOARCH=amd64 $(GOBUILD) -gcflags "all=-N -l" -o dist/plugin-windows-amd64.exe;
else
cd webapp && $(NPM) run debug;
endif
endif
rm -rf dist/
mkdir -p dist/$(PLUGIN_ID)/server/dist
cp $(MANIFEST_FILE) dist/$(PLUGIN_ID)/plugin.json
cp -r server/dist/* dist/$(PLUGIN_ID)/server/dist/
mkdir -p ../mattermost-server/plugins
cp -r dist/* ../mattermost-server/plugins/

.PHONY: validate-go-version
validate-go-version: ## Validates the installed version of go against Mattermost's minimum requirement.
@if [ $(GO_MAJOR_VERSION) -gt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \
exit 0 ;\
elif [ $(GO_MAJOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
exit 1; \
elif [ $(GO_MINOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MINOR_VERSION) ] ; then \
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
exit 1; \
fi

## Generates a tar bundle of the plugin for install.
.PHONY: bundle
bundle:
rm -rf dist/
mkdir -p dist/$(PLUGIN_ID)
cp $(MANIFEST_FILE) dist/$(PLUGIN_ID)/
cp $(MANIFEST_FILE) dist/$(PLUGIN_ID)/plugin.json
ifneq ($(wildcard $(ASSETS_DIR)/.),)
cp -r $(ASSETS_DIR) dist/$(PLUGIN_ID)/
endif
Expand All @@ -119,7 +169,7 @@ ifneq ($(HAS_WEBAPP),)
mkdir -p dist/$(PLUGIN_ID)/webapp
cp -r webapp/dist dist/$(PLUGIN_ID)/webapp/
endif
cd dist && tar -cvzf $(BUNDLE_NAME) $(PLUGIN_ID)
cd dist && tar -cvzf $(BUNDLE_NAME) -C $(PLUGIN_ID) .

@echo plugin built at: dist/$(BUNDLE_NAME)

Expand Down Expand Up @@ -190,7 +240,7 @@ detach: setup-attach
.PHONY: test
test: webapp/node_modules
ifneq ($(HAS_SERVER),)
$(GO) test -v $(GO_TEST_FLAGS) ./server/...
$(GO) test -v $(GO_TEST_FLAGS) $(GO_PACKAGES)
endif
ifneq ($(HAS_WEBAPP),)
cd webapp && $(NPM) run test;
Expand All @@ -200,7 +250,7 @@ endif
.PHONY: coverage
coverage: webapp/node_modules
ifneq ($(HAS_SERVER),)
$(GO) test $(GO_TEST_FLAGS) -coverprofile=server/coverage.txt ./server/...
$(GO) test $(GO_TEST_FLAGS) -coverprofile=server/coverage.txt $(GO_PACKAGES)
$(GO) tool cover -html=server/coverage.txt
endif

Expand Down Expand Up @@ -255,6 +305,55 @@ ifneq ($(HAS_WEBAPP),)
endif
rm -fr build/bin/

## Setup dlv for attaching, identifying the plugin PID for other targets.
.PHONY: setup-attach
setup-attach:
$(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}'))
$(eval NUM_PID := $(shell echo -n ${PLUGIN_PID} | wc -w))

@if [ ${NUM_PID} -gt 2 ]; then \
echo "** There is more than 1 plugin process running. Run 'make kill reset' to restart just one."; \
exit 1; \
fi

## Check if setup-attach succeeded.
.PHONY: check-attach
check-attach:
@if [ -z ${PLUGIN_PID} ]; then \
echo "Could not find plugin PID; the plugin is not running. Exiting."; \
exit 1; \
else \
echo "Located Plugin running with PID: ${PLUGIN_PID}"; \
fi

## Attach dlv to an existing plugin instance.
.PHONY: attach
attach: setup-attach check-attach
dlv attach ${PLUGIN_PID}

## Attach dlv to an existing plugin instance, exposing a headless instance on $DLV_DEBUG_PORT.
.PHONY: attach-headless
attach-headless: setup-attach check-attach
dlv attach ${PLUGIN_PID} --listen :$(DLV_DEBUG_PORT) --headless=true --api-version=2 --accept-multiclient

## Detach dlv from an existing plugin instance, if previously attached.
.PHONY: detach
detach: setup-attach
@DELVE_PID=$(shell ps aux | grep "dlv attach ${PLUGIN_PID}" | grep -v "grep" | awk -F " " '{print $$2}') && \
if [ "$$DELVE_PID" -gt 0 ] > /dev/null 2>&1 ; then \
echo "Located existing delve process running with PID: $$DELVE_PID. Killing." ; \
kill -9 $$DELVE_PID ; \
fi

## Kill all instances of the plugin, detaching any existing dlv instance.
.PHONY: kill
kill: detach
$(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}'))

@for PID in ${PLUGIN_PID}; do \
echo "Killing plugin pid $$PID"; \
kill -9 $$PID; \
done; \
# Help documentation à la https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
help:
@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
File renamed without changes
File renamed without changes
36 changes: 18 additions & 18 deletions build/custom.mk
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ RUDDER_WRITE_KEY = 1d5bMvdrfWClLxgK1FvV3s4U1tg
ifdef MM_RUDDER_PLUGINS_PROD
RUDDER_WRITE_KEY = $(MM_RUDDER_PLUGINS_PROD)
endif
LDFLAGS += -X "github.com/mattermost/mattermost-plugin-mscalendar/server/telemetry.rudderWriteKey=$(RUDDER_WRITE_KEY)"
LDFLAGS += -X "$(REPOSITORY_URL)/server/telemetry.rudderWriteKey=$(RUDDER_WRITE_KEY)"

# Build info
BUILD_DATE = $(shell date -u)
Expand All @@ -21,25 +21,25 @@ GO_BUILD_FLAGS = -ldflags '$(LDFLAGS)'
mock:
ifneq ($(HAS_SERVER),)
go install github.com/golang/mock/[email protected]
mockgen -destination server/jobs/mock_cluster/mock_cluster.go github.com/mattermost/mattermost/server/public/pluginapi/cluster JobPluginAPI
mockgen -destination server/mscalendar/mock_mscalendar/mock_mscalendar.go github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar MSCalendar
mockgen -destination server/mscalendar/mock_welcomer/mock_welcomer.go -package mock_welcomer github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar Welcomer
mockgen -destination server/mscalendar/mock_plugin_api/mock_plugin_api.go -package mock_plugin_api github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar PluginAPI
mockgen -destination server/remote/mock_remote/mock_remote.go github.com/mattermost/mattermost-plugin-mscalendar/server/remote Remote
mockgen -destination server/remote/mock_remote/mock_client.go github.com/mattermost/mattermost-plugin-mscalendar/server/remote Client
mockgen -destination server/utils/bot/mock_bot/mock_poster.go github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot Poster
mockgen -destination server/utils/bot/mock_bot/mock_admin.go github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot Admin
mockgen -destination server/utils/bot/mock_bot/mock_logger.go github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot Logger
mockgen -destination server/store/mock_store/mock_store.go github.com/mattermost/mattermost-plugin-mscalendar/server/store Store
mockgen -destination calendar/jobs/mock_cluster/mock_cluster.go github.com/mattermost/mattermost-plugin-api/cluster JobPluginAPI
mockgen -destination calendar/engine/mock_engine/mock_engine.go $(REPOSITORY_URL)/calendar/engine Engine
mockgen -destination calendar/engine/mock_welcomer/mock_welcomer.go -package mock_welcomer $(REPOSITORY_URL)/calendar/engine Welcomer
mockgen -destination calendar/engine/mock_plugin_api/mock_plugin_api.go -package mock_plugin_api $(REPOSITORY_URL)/calendar/engine PluginAPI
mockgen -destination calendar/remote/mock_remote/mock_remote.go $(REPOSITORY_URL)/calendar/remote Remote
mockgen -destination calendar/remote/mock_remote/mock_client.go $(REPOSITORY_URL)/calendar/remote Client
mockgen -destination calendar/utils/bot/mock_bot/mock_poster.go $(REPOSITORY_URL)/calendar/utils/bot Poster
mockgen -destination calendar/utils/bot/mock_bot/mock_admin.go $(REPOSITORY_URL)/calendar/utils/bot Admin
mockgen -destination calendar/utils/bot/mock_bot/mock_logger.go $(REPOSITORY_URL)/calendar/utils/bot Logger
mockgen -destination calendar/store/mock_store/mock_store.go $(REPOSITORY_URL)/calendar/store Store
endif

clean_mock:
ifneq ($(HAS_SERVER),)
rm -rf ./server/jobs/mock_cluster
rm -rf ./server/mscalendar/mock_mscalendar
rm -rf ./server/mscalendar/mock_welcomer
rm -rf ./server/mscalendar/mock_plugin_api
rm -rf ./server/remote/mock_remote
rm -rf ./server/utils/bot/mock_bot
rm -rf ./server/store/mock_store
rm -rf ./calendar/jobs/mock_cluster
rm -rf ./calendar/engine/mock_engine
rm -rf ./calendar/engine/mock_welcomer
rm -rf ./calendar/engine/mock_plugin_api
rm -rf ./calendar/remote/mock_remote
rm -rf ./calendar/utils/bot/mock_bot
rm -rf ./calendar/store/mock_store
endif
12 changes: 9 additions & 3 deletions build/manifest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,16 @@ func main() {
}

func findManifest() (*model.Manifest, error) {
_, manifestFilePath, err := model.FindManifest(".")
if err != nil {
return nil, errors.Wrap(err, "failed to find manifest in current working directory")
manifestFilePath := os.Getenv("MANIFEST_FILE")

if manifestFilePath == "" {
var err error
_, manifestFilePath, err = model.FindManifest(".")
if err != nil {
return nil, errors.Wrap(err, "failed to find manifest in current working directory")
}
}

manifestFile, err := os.Open(manifestFilePath)
if err != nil {
return nil, errors.Wrapf(err, "failed to open %s", manifestFilePath)
Expand Down
9 changes: 5 additions & 4 deletions build/setup.mk
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,23 @@ $(shell cd build/manifest && $(GO) build -o ../bin/manifest)
$(shell cd build/pluginctl && $(GO) build -o ../bin/pluginctl)

# Extract the plugin id from the manifest.
PLUGIN_ID ?= $(shell build/bin/manifest id)
# TODO: Not working
PLUGIN_ID ?= $(shell MANIFEST_FILE=$(MANIFEST_FILE) build/bin/manifest id)
ifeq ($(PLUGIN_ID),)
$(error "Cannot parse id from $(MANIFEST_FILE)")
endif

# Extract the plugin version from the manifest.
PLUGIN_VERSION ?= $(shell build/bin/manifest version)
PLUGIN_VERSION ?= $(shell MANIFEST_FILE=$(MANIFEST_FILE) build/bin/manifest version)
ifeq ($(PLUGIN_VERSION),)
$(error "Cannot parse version from $(MANIFEST_FILE)")
endif

# Determine if a server is defined in the manifest.
HAS_SERVER ?= $(shell build/bin/manifest has_server)
HAS_SERVER ?= $(shell MANIFEST_FILE=$(MANIFEST_FILE) build/bin/manifest has_server)

# Determine if a webapp is defined in the manifest.
HAS_WEBAPP ?= $(shell build/bin/manifest has_webapp)
HAS_WEBAPP ?= $(shell MANIFEST_FILE=$(MANIFEST_FILE) build/bin/manifest has_webapp)

# Determine if a /public folder is in use
HAS_PUBLIC ?= $(wildcard public/.)
Expand Down
3 changes: 3 additions & 0 deletions calendar/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Calendar Plugin API

This file contain the common logic for creating Calendar plugins for Mattermost.
28 changes: 22 additions & 6 deletions server/api/api.go → calendar/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,25 @@
package api

import (
"github.com/mattermost/mattermost-plugin-mscalendar/server/config"
"github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar"
"github.com/mattermost/mattermost-plugin-mscalendar/server/utils/httputils"
"net/http"

"github.com/mattermost/mattermost-plugin-mscalendar/calendar/config"
"github.com/mattermost/mattermost-plugin-mscalendar/calendar/engine"
"github.com/mattermost/mattermost-plugin-mscalendar/calendar/utils/httputils"
)

type api struct {
mscalendar.Env
mscalendar.NotificationProcessor
engine.Env
engine.NotificationProcessor
}

// Init initializes the router.
func Init(h *httputils.Handler, env mscalendar.Env, notificationProcessor mscalendar.NotificationProcessor) {
func Init(h *httputils.Handler, env engine.Env, notificationProcessor engine.NotificationProcessor) {
api := &api{
Env: env,
NotificationProcessor: notificationProcessor,
}

apiRouter := h.Router.PathPrefix(config.PathAPI).Subrouter()
apiRouter.HandleFunc("/authorized", api.getAuthorized).Methods("GET")

Expand All @@ -32,4 +35,17 @@ func Init(h *httputils.Handler, env mscalendar.Env, notificationProcessor mscale
postActionRouter.HandleFunc(config.PathTentative, api.postActionTentative).Methods("POST")
postActionRouter.HandleFunc(config.PathRespond, api.postActionRespond).Methods("POST")
postActionRouter.HandleFunc(config.PathConfirmStatusChange, api.postActionConfirmStatusChange).Methods("POST")

dialogRouter := h.Router.PathPrefix(config.PathAutocomplete).Subrouter()
dialogRouter.HandleFunc(config.PathUsers, api.autocompleteConnectedUsers)

apiRoutes := h.Router.PathPrefix(config.InternalAPIPath).Subrouter()
eventsRouter := apiRoutes.PathPrefix(config.PathEvents).Subrouter()
eventsRouter.HandleFunc(config.PathCreate, api.createEvent).Methods("POST")
apiRoutes.HandleFunc(config.PathConnectedUser, api.connectedUserHandler)

// Returns provider information for the plugin to use
apiRoutes.HandleFunc(config.PathProvider, func(w http.ResponseWriter, r *http.Request) {
httputils.WriteJSONResponse(w, config.Provider, 200)
})
}
34 changes: 34 additions & 0 deletions calendar/api/autocomplete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package api

import (
"errors"
"fmt"
"net/http"

"github.com/mattermost/mattermost-plugin-mscalendar/calendar/store"
"github.com/mattermost/mattermost-plugin-mscalendar/calendar/utils"
"github.com/mattermost/mattermost-plugin-mscalendar/calendar/utils/bot"
"github.com/mattermost/mattermost-plugin-mscalendar/calendar/utils/httputils"
)

func (api *api) autocompleteConnectedUsers(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get("Mattermost-User-Id")
_, err := api.Store.LoadUser(mattermostUserID)
if mattermostUserID == "" || errors.Is(err, store.ErrNotFound) {
httputils.WriteUnauthorizedError(w, fmt.Errorf("unauthorized"))
return
}

searchString := r.URL.Query().Get("search")
results, err := api.Store.SearchInUserIndex(searchString, 10)
if err != nil {
utils.SlackAttachmentError(w, "unable to search in user index: "+err.Error())
httputils.WriteInternalServerError(w, err)
return
}

if err := httputils.WriteJSONResponse(w, results.ToDTO(), http.StatusOK); err != nil {
api.Logger.With(bot.LogContext{"err": err.Error()}).Errorf("error sending response to user")
httputils.WriteInternalServerError(w, err)
}
}
Loading

0 comments on commit 7f1bbcd

Please sign in to comment.