main

mattermost/focalboard

Last updated at: 29/12/2023 09:46

statistics.go

TLDR

The file statistics.go is a part of the api package in the Demo Projects project. It contains the handleStatistics method, which is responsible for fetching the statistics of the server. The method checks for user authentication and permissions before retrieving and returning the statistics data.

Methods

handleStatistics

This method is responsible for handling the request to fetch the statistics of the server. It performs the following steps:

  1. Checks if the request is authorized by checking for Mattermost authentication.
  2. Verifies if the user has the necessary permissions to access analytics.
  3. Retrieves the board count and the count of used cards from the application.
  4. Creates a model.BoardsStatistics object using the retrieved counts.
  5. Marshals the statistics object into JSON format.
  6. Sends the JSON response containing the statistics data.

Classes

None

package api

import (
	"encoding/json"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/mattermost/focalboard/server/model"
	mmModel "github.com/mattermost/mattermost-server/v6/model"
)

func (a *API) registerStatisticsRoutes(r *mux.Router) {
	// statistics
	r.HandleFunc("/statistics", a.sessionRequired(a.handleStatistics)).Methods("GET")
}

func (a *API) handleStatistics(w http.ResponseWriter, r *http.Request) {
	// swagger:operation GET /statistics handleStatistics
	//
	// Fetches the statistic  of the server.
	//
	// ---
	// produces:
	// - application/json
	// security:
	// - BearerAuth: []
	// responses:
	//   '200':
	//     description: success
	//     schema:
	//         "$ref": "#/definitions/BoardStatistics"
	//   default:
	//     description: internal error
	//     schema:
	//       "$ref": "#/definitions/ErrorResponse"
	if !a.MattermostAuth {
		a.errorResponse(w, r, model.NewErrNotImplemented("not permitted in standalone mode"))
		return
	}

	// user must have right to access analytics
	userID := getUserID(r)
	if !a.permissions.HasPermissionTo(userID, mmModel.PermissionGetAnalytics) {
		a.errorResponse(w, r, model.NewErrPermission("access denied System Statistics"))
		return
	}

	boardCount, err := a.app.GetBoardCount()
	if err != nil {
		a.errorResponse(w, r, err)
		return
	}
	cardCount, err := a.app.GetUsedCardsCount()
	if err != nil {
		a.errorResponse(w, r, err)
		return
	}

	stats := model.BoardsStatistics{
		Boards: int(boardCount),
		Cards:  cardCount,
	}
	data, err := json.Marshal(stats)
	if err != nil {
		a.errorResponse(w, r, err)
		return
	}

	jsonBytesResponse(w, http.StatusOK, data)
}