api

package
v0.0.0-...-9b579c7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2025 License: AGPL-3.0 Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BookingStatusAccepted  = "ACCEPTED"
	BookingStatusRejected  = "REJECTED"
	BookingStatusCancelled = "CANCELLED"
	BookingStatusReturned  = "RETURNED"
	BookingStatusPending   = "PENDING"
	BookingStatusPicked    = "PICKED"
)

Booking status constants for API

View Source
const (
	MessageTypePrivate   = "private"
	MessageTypeCommunity = "community"
	MessageTypeGeneral   = "general"
	MessageTypeAll       = "all"
)

Message type constants

Variables

View Source
var (
	ErrUnauthorized = &HTTPError{
		Code:    http.StatusUnauthorized,
		Message: "unauthorized access",
	}
	ErrInvalidRegisterAuthToken = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid registration token",
	}
	ErrWrongLogin = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid credentials",
	}
	ErrForbidden = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "unauthorized access",
	}
)

Authentication errors

View Source
var (
	ErrInvalidRequestBodyData = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid request body data",
	}
	ErrActualPasswordRequired = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "actual password is required",
	}
	ErrInvalidActualPassword = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "invalid actual password",
	}
	ErrInvalidJSON = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid JSON body",
	}
	ErrInvalidImageFormat = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid image format",
	}
	ErrInvalidHash = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid hash",
	}
	ErrInvalidBookingDates = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid booking dates",
	}
	ErrInvalidRating = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid rating value",
	}
	ErrInvalidBookingStatus = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid booking status",
	}
	ErrAlreadyRated = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "booking already rated",
	}
	ErrNotMember = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "Not member of the community",
	}
)

Request validation errors

View Source
var (
	ErrNoContent = &HTTPError{
		Code:    http.StatusNoContent,
		Message: "no content",
	}
	ErrImageNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "image not found",
	}
	ErrToolNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "tool not found",
	}
	ErrBookingNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "booking not found",
	}
	ErrRatingNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "rating not found",
	}
	ErrUserNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "user not found",
	}
	ErrCommunityNotFound = &HTTPError{
		Code:    http.StatusNotFound,
		Message: "community not found",
	}
	ErrInvalidUserID = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid user id format",
	}
)

Resource not found or empty errors

View Source
var (
	ErrUserNotCommunityMember = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "user is not a member of the community this tool belongs to",
	}
	ErrToolNotOwnedByUser = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "tool not owned by user",
	}
	ErrOnlyOwnerCanReturn = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "only tool owner can mark as returned",
	}
	ErrOnlyOwnerCanAccept = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "only tool owner can accept petitions",
	}
	ErrOnlyOwnerCanDeny = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "only tool owner can deny petitions",
	}
	ErrOnlyRequesterCanCancel = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "only requester can cancel their requests",
	}
	ErrUserNotInvolved = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "user not involved in booking",
	}
	ErrUserInactive = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "user account is inactive",
	}
	ErrRecipientUserInactive = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "recipient user account is inactive",
	}
)

Permission errors

View Source
var (
	ErrEmailChangeNotAllowed = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "email change not allowed",
	}
	ErrBookingDatesConflict = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "booking dates conflict with existing booking",
	}
	ErrBookingAlreadyReturned = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "booking already marked as returned",
	}
	ErrBookingAlreadyRated = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "booking already rated",
	}
	ErrCanOnlyAcceptPending = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "can only accept pending petitions",
	}
	ErrCanOnlyDenyPending = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "can only deny pending petitions",
	}
	ErrCanOnlyCancelPending = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "can only cancel pending requests",
	}
	ErrPasswordTooShort = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "password must be at least 8 characters long",
	}
	ErrMalformedEmail = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "malformed email address",
	}
	ErrLocationNotSet = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "Location is not set",
	}
	ErrInvalidInviteCode = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invalid invite code",
	}
	ErrInviteCodeAlreadyUsed = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "invite code already used",
	}
	ErrHasUnusedInviteCodes = &HTTPError{
		Code:    http.StatusConflict,
		Message: "you still have unused invite codes",
	}
	ErrTooManyInviteCodeRequests = &HTTPError{
		Code:    http.StatusConflict,
		Message: "too many invite code requests, please try again later",
	}
	ErrCanOnlyPickAccepted = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "can only pick accepted bookings",
	}
)

Conflict errors

View Source
var (
	ErrCouldNotInsertToDatabase = &HTTPError{
		Code:    http.StatusInternalServerError,
		Message: "could not insert to database",
	}
	ErrInternalServerError = &HTTPError{
		Code:    http.StatusInternalServerError,
		Message: "internal server error",
	}
	ErrTooManyRequests = &HTTPError{
		Code:    http.StatusTooManyRequests,
		Message: "too many requests",
	}
)

Server errors

View Source
var (
	ErrEmptyTitleOrDescription = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "title and description must not be empty",
	}
	ErrInvalidToolValuationValue = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "estimated value must be greater than 0",
	}
	ErrMayBeFreeRequired = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "may be free must not be nil",
	}
	ErrAskWithFeeRequired = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "ask with fee must not be nil",
	}
	ErrCostRequired = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "cost must not be nil",
	}
	ErrToolLocationTooFar = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "tool location is too far away",
	}
	ErrInvalidToolCategory = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "invalid tool category",
	}
	ErrInvalidTransportOption = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "invalid transport option",
	}
	ErrToolNotNomadic = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "tool is not nomadic",
	}
	ErrToolNomadic = &HTTPError{
		Code:    http.StatusUnprocessableEntity,
		Message: "tool is nomadic",
	}
	ErrNomadicToolWithPastBooking = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "nomadic tool cannot be booked when there is a booking planned or in process",
	}
	ErrOnlyOwnerCanChangeNomadicStatus = &HTTPError{
		Code:    http.StatusForbidden,
		Message: "only the owner can change a tool from nomadic to non-nomadic",
	}
	ErrCannotChangeNomadicWithPendingBookings = &HTTPError{
		Code:    http.StatusBadRequest,
		Message: "cannot change nomadic status when there are pending bookings",
	}
)

Tool validation errors

Functions

func StartDigestScheduler

func StartDigestScheduler(database *db.Database, mailService notifications.NotificationService, dailyDigestHour int) *digest_scheduler.DigestScheduler

StartDigestScheduler creates and starts a digest scheduler

Types

type API

type API struct {
	Router *chi.Mux
	// contains filtered or unexported fields
}

API type represents the API HTTP server with JWT authentication capabilities.

func New

func New(conf *APIConfig) (*API, error)

New creates a new API HTTP server. It does not start the server. Use Start() for that.

func (*API) Close

func (a *API) Close()

Close closes the API service database.

func (*API) EnablePrometheusMetrics

func (a *API) EnablePrometheusMetrics(prometheusID string)

EnablePrometheusMetrics enables go-chi prometheus metrics under specified ID. If ID empty, the default "gochi_http" is used.

func (*API) GetToolByIDWithAccessControl

func (a *API) GetToolByIDWithAccessControl(r *Request, toolId []string) (*db.Tool, error)

func (*API) GetUserByIDWithAccessControl

func (a *API) GetUserByIDWithAccessControl(r *Request, userID primitive.ObjectID) (*db.User, *primitive.ObjectID, error)

GetUserByIDWithAccessControl Get user by ID with access control This method checks if the requesting user has access to the user being requested.

func (*API) HandleCountPendingActions

func (a *API) HandleCountPendingActions(r *Request) (interface{}, error)

HandleCountPendingActions handles GET /profile/pendings

func (*API) HandleCreateBooking

func (a *API) HandleCreateBooking(r *Request) (interface{}, error)

HandleCreateBooking handles POST /bookings

func (*API) HandleGetBooking

func (a *API) HandleGetBooking(r *Request) (interface{}, error)

HandleGetBooking handles GET /bookings/{bookingId}

func (*API) HandleGetBookingRatings

func (a *API) HandleGetBookingRatings(r *Request) (interface{}, error)

HandleGetBookingRatings handles GET /bookings/{bookingId}/ratings

func (*API) HandleGetIncomingRequests

func (a *API) HandleGetIncomingRequests(r *Request) (interface{}, error)

HandleGetIncomingRequests handles GET /bookings/requests/incoming

func (*API) HandleGetOutgoingRequests

func (a *API) HandleGetOutgoingRequests(r *Request) (interface{}, error)

HandleGetOutgoingRequests handles GET /bookings/requests/outgoing

func (*API) HandleGetPendingRatings

func (a *API) HandleGetPendingRatings(r *Request) (interface{}, error)

HandleGetPendingRatings handles GET /bookings/ratings/pending

func (*API) HandleGetToolRatings

func (a *API) HandleGetToolRatings(r *Request) (interface{}, error)

HandleGetToolRatings handles GET /tools/{id}/ratings

func (*API) HandleGetUserRatings

func (a *API) HandleGetUserRatings(r *Request) (interface{}, error)

HandleGetUserRatings handles GET /users/{id}/ratings Returns a unified list of all ratings (both submitted and received) for a user

func (*API) HandleRateBooking

func (a *API) HandleRateBooking(r *Request) (interface{}, error)

HandleRateBooking handles POST /bookings/{bookingId}/ratings

func (*API) HandleUpdateBookingStatus

func (a *API) HandleUpdateBookingStatus(r *Request) (interface{}, error)

HandleUpdateBookingStatus handles POST /bookings/{bookingId} This replaces the individual verb-based endpoints (accept, deny, cancel, return)

func (*API) RegisterBookingRoutes

func (a *API) RegisterBookingRoutes(r chi.Router)

RegisterBookingRoutes registers all booking-related routes to the provided router group

func (*API) RegisterCommunityRoutes

func (a *API) RegisterCommunityRoutes(r chi.Router)

RegisterCommunityRoutes registers all community-related routes to the provided router group

func (*API) RegisterImageRoutes

func (a *API) RegisterImageRoutes(r chi.Router)

RegisterImageRoutes registers all image-related routes to the provided router group

func (*API) RegisterMessageRoutes

func (a *API) RegisterMessageRoutes(r chi.Router)

RegisterMessageRoutes registers all message-related routes

func (*API) RegisterPublicImageRoutes

func (a *API) RegisterPublicImageRoutes(r chi.Router)

RegisterPublicImageRoutes registers all public image-related routes to the provided router group

func (*API) RegisterPublicUserRoutes

func (a *API) RegisterPublicUserRoutes(r chi.Router)

RegisterPublicUserRoutes registers all public user-related routes to the provided router group

func (*API) RegisterToolRoutes

func (a *API) RegisterToolRoutes(r chi.Router)

RegisterToolRoutes registers all tool-related routes to the provided router group

func (*API) RegisterUserRoutes

func (a *API) RegisterUserRoutes(r chi.Router)

RegisterUserRoutes registers all user-related routes to the provided router group

func (*API) Start

func (a *API) Start(host string, port int)

Start starts the API HTTP server (non blocking).

type APIConfig

type APIConfig struct {
	DB                 *db.Database
	MailService        notifications.NotificationService
	DigestScheduler    *digest_scheduler.DigestScheduler
	JwtSecret          string
	RegisterToken      string
	MaxInviteCodes     int
	InviteCodeCooldown int
	Debug              bool
}

type AdditionalContacts

type AdditionalContacts map[string]string

func (AdditionalContacts) Validate

func (ac AdditionalContacts) Validate() error

type BinaryResponse

type BinaryResponse struct {
	ContentType string
	Data        []byte
}

BinaryResponse represents a binary response that should be sent directly to the client

type BookingResponse

type BookingResponse struct {
	ID            string    `json:"id"`
	ToolID        string    `json:"toolId"`
	FromUserID    string    `json:"fromUserId"`
	ToUserID      string    `json:"toUserId"`
	StartDate     int64     `json:"startDate"`
	EndDate       int64     `json:"endDate"`
	Contact       string    `json:"contact"`
	Comments      string    `json:"comments"`
	BookingStatus string    `json:"bookingStatus"`
	IsRated       *bool     `json:"isRated"`
	IsNomadic     bool      `json:"isNomadic"`
	PickupPlace   *Location `json:"pickupPlace,omitempty"`

	// Legacy fields for backward compatibility
	CreatedAt int64 `json:"createdAt"`
	UpdatedAt int64 `json:"updatedAt"`
}

BookingResponse represents the API response for a booking

type BookingStatusUpdate

type BookingStatusUpdate struct {
	Status string `json:"status"`
}

BookingStatusUpdate represents a request to update a booking's status

type CommunityInfo

type CommunityInfo struct {
	ID    string         `json:"id"`
	Name  string         `json:"name"`
	Image types.HexBytes `json:"image,omitempty"`
}

CommunityInfo represents basic community information

type CommunityInviteResponse

type CommunityInviteResponse struct {
	ID          string    `json:"id"`
	CommunityID string    `json:"communityId"`
	UserID      string    `json:"userId"`
	InviterID   string    `json:"inviterId"`
	Status      string    `json:"status"`
	CreatedAt   time.Time `json:"createdAt"`
	Community   struct {
		Name  string         `json:"name"`
		Image types.HexBytes `json:"image"`
	} `json:"community"`
}

CommunityInviteResponse represents a community invitation

type CommunityResponse

type CommunityResponse struct {
	ID           string         `json:"id"`
	Name         string         `json:"name"`
	Image        types.HexBytes `json:"image,omitempty"`
	OwnerID      string         `json:"ownerId"`
	MembersCount int64          `json:"membersCount"`
	ToolsCount   int64          `json:"toolsCount"`
}

CommunityResponse represents a community in API responses

type CommunityUserResponse

type CommunityUserResponse struct {
	UserPreview
	Role db.CommunityRole `json:"role"`
}

CommunityUserResponse represents a user in a community

type ConversationResponse

type ConversationResponse struct {
	ID              string          `json:"id"`
	Type            string          `json:"type"`
	Participants    []UserPreview   `json:"participants,omitempty"`
	Community       *CommunityInfo  `json:"community,omitempty"`
	LastMessage     MessageResponse `json:"lastMessage"`
	UnreadCount     int64           `json:"unreadCount"`
	MessageCount    int64           `json:"messageCount"`
	LastMessageTime int64           `json:"lastMessageTime"`
}

ConversationResponse represents a conversation in API responses

func (*ConversationResponse) FromDB

func (c *ConversationResponse) FromDB(dbConv *db.Conversation, database *db.Database, userID primitive.ObjectID) *ConversationResponse

FromDB converts a database conversation to API response

type CreateBookingRequest

type CreateBookingRequest struct {
	ToolID    string `json:"toolId"`
	StartDate int64  `json:"startDate"`
	EndDate   int64  `json:"endDate"`
	Contact   string `json:"contact"`
	Comments  string `json:"comments"`
}

CreateBookingRequest represents the request to create a new booking

type CreateCommunityRequest

type CreateCommunityRequest struct {
	Name  string         `json:"name"`
	Image types.HexBytes `json:"image,omitempty"`
}

CreateCommunityRequest represents the request to create a new community

type HTTPContext

type HTTPContext struct {
	Writer  http.ResponseWriter
	Request *http.Request
}

HTTPContext is the Context for an HTTP request.

func (*HTTPContext) GetPage

func (h *HTTPContext) GetPage() (int, error)

GetPage returns the page number from the query parameters. If the page parameter is not present, it returns 0 (first page). If the page parameter is invalid, it returns an error. If the page parameter is less than 0, it returns 0 (defaults to first page).

func (*HTTPContext) GetPaginationParams

func (h *HTTPContext) GetPaginationParams() (page, pageSize int, err error)

GetPaginationParams extracts pagination parameters from the request

func (*HTTPContext) GetSearchTerm

func (h *HTTPContext) GetSearchTerm() *string

GetSearchTerm Get search term if provided

func (*HTTPContext) Send

func (h *HTTPContext) Send(msg []byte, httpStatusCode int) error

Send replies the request with the provided message.

func (*HTTPContext) URLParam

func (h *HTTPContext) URLParam(key string) []string

URLParam gets a URL parameter. For path parameters (specified in the path pattern as {key}), it uses chi.URLParam. For query parameters (?key=value and ?key[]=value), it uses URL.Query(). If the key is not found, it returns nil. Else it returns a slice of values with at least one element. If the key is repeated in the query string, it will return all values.

type HTTPError

type HTTPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

HTTPError represents an error with an HTTP status code

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) IsErr

func (e *HTTPError) IsErr(err error) bool

IsErr checks if the HTTPError is the same as the given error. It compares the error code and the base error message, without taking into account the additional error details introduced by WithErr.

func (*HTTPError) WithErr

func (e *HTTPError) WithErr(err error) *HTTPError

WithErr appends an error message to the HTTPError message. Returns a copy of the HTTPError with the appended error message.

type Info

type Info struct {
	Users      int               `json:"users"`
	Tools      int               `json:"tools"`
	Categories []db.ToolCategory `json:"categories"`
	Transports []db.Transport    `json:"transports"`
}

type InviteCode

type InviteCode struct {
	ID        string     `json:"id"`
	Code      string     `json:"code"`
	UsedByID  *string    `json:"usedById,omitempty"`
	UsedOn    *time.Time `json:"usedOn,omitempty"`
	CreatedOn time.Time  `json:"createdOn"`
}

InviteCode represents an invitation code

func (*InviteCode) FromDBInviteCode

func (i *InviteCode) FromDBInviteCode(dbic *db.InviteCode) *InviteCode

FromDBInviteCode converts a DB InviteCode to an API InviteCode

type InviteStatusUpdateRequest

type InviteStatusUpdateRequest struct {
	Status string `json:"status"` // "ACCEPTED", "REJECTED", or "CANCELED"
}

InviteStatusUpdateRequest represents the request to update an invite status

type Location

type Location struct {
	Latitude  int64 `json:"latitude"`  // Latitude in microdegrees
	Longitude int64 `json:"longitude"` // Longitude in microdegrees
}

Location represents a geographical location

func (*Location) FromDBLocation

func (l *Location) FromDBLocation(dbloc db.DBLocation) *Location

FromDBLocation converts a DB Location to an API Location

func (*Location) ToDBLocation

func (l *Location) ToDBLocation() db.DBLocation

ToDBLocation converts an API Location to a DB Location

type Login

type Login struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type LoginResponse

type LoginResponse struct {
	Token    string    `json:"token"`
	Expirity time.Time `json:"expirity"`
}

type MarkMessagesReadRequest

type MarkMessagesReadRequest struct {
	Type             string `json:"type,omitempty"`
	ConversationWith string `json:"conversationWith,omitempty"` // User ID for private, Community ID for community
}

MarkMessagesReadRequest represents a request to mark messages as read

type MessageRateLimiter

type MessageRateLimiter struct {
	// contains filtered or unexported fields
}

MessageRateLimiter provides rate limiting specifically for messages

func NewMessageRateLimiter

func NewMessageRateLimiter() *MessageRateLimiter

NewMessageRateLimiter creates a new message rate limiter

func (*MessageRateLimiter) CheckMessageLimit

func (mrl *MessageRateLimiter) CheckMessageLimit(ctx context.Context, userID primitive.ObjectID, messageType string) error

CheckMessageLimit checks if a user can send a message

type MessageResponse

type MessageResponse struct {
	ID            string           `json:"id"`
	Type          string           `json:"type"`
	SenderID      string           `json:"senderId"`
	SenderName    string           `json:"senderName"`
	RecipientID   string           `json:"recipientId,omitempty"`
	RecipientName string           `json:"recipientName"`
	CommunityID   string           `json:"communityId,omitempty"`
	Content       string           `json:"content,omitempty"`
	Images        []types.HexBytes `json:"images,omitempty"`
	CreatedAt     int64            `json:"createdAt"`
	IsRead        bool             `json:"isRead"`
	ReplyToID     string           `json:"replyToId,omitempty"`
}

MessageResponse represents a message in API responses

func (*MessageResponse) FromDB

func (m *MessageResponse) FromDB(dbMessage *db.Message, database *db.Database, userID ...primitive.ObjectID) *MessageResponse

FromDB converts a database message to API response If userID is provided, it will determine the read status for that user

type NotificationPreferences

type NotificationPreferences map[string]bool

NotificationPreferences represents user notification settings

type PaginatedBookingsResponse

type PaginatedBookingsResponse struct {
	Bookings   []*BookingResponse `json:"bookings"`
	Pagination PaginationInfo     `json:"pagination"`
}

PaginatedBookingsResponse wraps bookings with pagination info

type PaginatedCommunityResponse

type PaginatedCommunityResponse struct {
	Communities []*CommunityResponse `json:"communities"`
	Pagination  PaginationInfo       `json:"pagination"`
}

PaginatedCommunityResponse wraps community with pagination info

type PaginatedCommunityUserResponse

type PaginatedCommunityUserResponse struct {
	Users      []*CommunityUserResponse `json:"users"`
	Pagination PaginationInfo           `json:"pagination"`
}

PaginatedCommunityUserResponse wraps community users with pagination info

type PaginatedConversationsResponse

type PaginatedConversationsResponse struct {
	Conversations []*ConversationResponse `json:"conversations"`
	Pagination    PaginationInfo          `json:"pagination"`
}

PaginatedConversationsResponse wraps conversations with pagination info

type PaginatedMessagesResponse

type PaginatedMessagesResponse struct {
	Messages   []*MessageResponse `json:"messages"`
	Pagination PaginationInfo     `json:"pagination"`
}

PaginatedMessagesResponse wraps messages with pagination info

type PaginatedToolsResponse

type PaginatedToolsResponse struct {
	Tools      []*Tool        `json:"tools"`
	Pagination PaginationInfo `json:"pagination"`
}

PaginatedToolsResponse wraps tools with pagination info

type PaginatedUnifiedRatingsResponse

type PaginatedUnifiedRatingsResponse struct {
	Ratings    []*db.UnifiedRating `json:"ratings"`
	Pagination PaginationInfo      `json:"pagination"`
}

type PaginationInfo

type PaginationInfo struct {
	Current  int   `json:"current"`
	PageSize int   `json:"pageSize"`
	Total    int64 `json:"total"`
	Pages    int   `json:"pages"`
}

PaginationInfo contains pagination metadata

func CalculatePagination

func CalculatePagination(page, pageSize int, total int64) PaginationInfo

CalculatePagination computes pagination metadata

type PendingActionsResponse

type PendingActionsResponse struct {
	PendingRatingsCount  int64 `json:"pendingRatingsCount"`
	PendingRequestsCount int64 `json:"pendingRequestsCount"`
	PendingInvitesCount  int64 `json:"pendingInvitesCount"`
}

PendingActionsResponse represents the response for pending actions

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides rate limiting functionality

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(key string, maxTokens, refillRate int) bool

Allow checks if an action is allowed for the given key

type RateRequest

type RateRequest struct {
	Rating  int              `json:"rating"`
	Comment string           `json:"comment"`
	Images  []types.HexBytes `json:"images,omitempty"`
}

RateRequest represents the request body for rating a booking

type Rating

type Rating struct {
	ID         string           `json:"id"`
	BookingID  string           `json:"bookingId"`
	ToolID     string           `json:"toolId"`
	Rating     int              `json:"rating"`
	Comment    string           `json:"comment"`
	Images     []types.HexBytes `json:"images"`
	FromUserID string           `json:"fromUserId"`
	ToUserID   string           `json:"toUserId"`
	RatedAt    int64            `json:"ratedAt"`
}

Rating represents a rating for a booking

func (*Rating) FromDB

func (r *Rating) FromDB(b *db.BookingRating) *Rating

type Register

type Register struct {
	UserEmail         string `json:"email"`
	RegisterAuthToken string `json:"invitationToken"`
	UserProfile
	Tokens uint64 `json:"tokens,omitempty"`
}

type Request

type Request struct {
	Data    []byte
	Path    []string
	Context *HTTPContext
	UserID  string
}

Request represents an HTTP request to the API. It contains the request Body data, the URL path and the HTTP context. The context can be used for obtaining URL parameters and sending responses.

type Response

type Response struct {
	Header ResponseHeader `json:"header"`
	Data   any            `json:"data,omitempty"`
}

Response is the default response of the API

type ResponseHeader

type ResponseHeader struct {
	Success   bool   `json:"success"`
	Message   string `json:"message,omitempty"`
	ErrorCode int    `json:"errorCode,omitempty"`
}

ResponseHeader is the header of the response

type RouterHandlerFn

type RouterHandlerFn = func(r *Request) (interface{}, error)

RouterHandlerFn is the function signature for adding handlers to the HTTProuter.

type SendMessageRequest

type SendMessageRequest struct {
	Type        string   `json:"type"`                  // private|community|general
	RecipientID string   `json:"recipientId,omitempty"` // User ID for private, Community ID for community
	Content     string   `json:"content,omitempty"`
	ImageHashes []string `json:"imageHashes,omitempty"` // Hashes from image upload
	Images      []string `json:"images,omitempty"`      // Alternative field name for compatibility
	ReplyToID   string   `json:"replyToId,omitempty"`
}

SendMessageRequest represents a request to send a message

func (*SendMessageRequest) Validate

func (r *SendMessageRequest) Validate() error

Validate validates the send message request

type SimpleInviteCode

type SimpleInviteCode struct {
	Code      string    `json:"code"`
	CreatedOn time.Time `json:"createdOn"`
}

SimpleInviteCode represents a simplified invitation code with only essential fields

type StatusResponse

type StatusResponse struct {
	StatusCode int
	Data       interface{}
}

StatusResponse represents a response with a custom HTTP status code

type TokenBucket

type TokenBucket struct {
	// contains filtered or unexported fields
}

TokenBucket represents a token bucket for rate limiting

func NewTokenBucket

func NewTokenBucket(maxTokens, refillRate int) *TokenBucket

NewTokenBucket creates a new token bucket

func (*TokenBucket) Allow

func (tb *TokenBucket) Allow() bool

Allow checks if a token can be consumed from the bucket

type Tool

type Tool struct {
	ID                 int64              `json:"id"`
	UserID             string             `json:"userId"`
	UserActive         bool               `json:"userActive"`
	ActualUserID       string             `json:"actualUserId,omitempty"`
	ActualUserActive   bool               `json:"actualUserActive,omitempty"`
	Title              string             `json:"title"`
	Description        string             `json:"description"`
	IsAvailable        *bool              `json:"isAvailable"`
	MayBeFree          *bool              `json:"mayBeFree"`
	AskWithFee         *bool              `json:"askWithFee"`
	Images             []types.HexBytes   `json:"images"`
	TransportOptions   []int              `json:"transportOptions"`
	Category           int                `json:"toolCategory"`
	Location           Location           `json:"location"`
	Cost               *uint64            `json:"cost,omitempty"`
	ToolValuation      *uint64            `json:"toolValuation"`
	EstimatedDailyCost uint64             `json:"estimatedDailyCost"`
	Height             uint32             `json:"height"`
	Weight             uint32             `json:"weight"`
	MaxDistance        uint32             `json:"maxDistance"`
	ReservedDates      []db.DateRange     `json:"reservedDates"`
	IsNomadic          *bool              `json:"isNomadic"`
	Communities        []string           `json:"communities,omitempty"`
	HistoryEntries     []ToolHistoryEntry `json:"historyEntries,omitempty"`
}

Tool is the type of the tool

func (*Tool) FromDBTool

func (t *Tool) FromDBTool(dbt *db.Tool, database *db.Database, useRealLocation ...bool) *Tool

FromDBTool converts a DB Tool to an API Tool. If database is provided, it will populate UserActive and ActualUserActive fields. If useRealLocation is true, the real location is used instead of the obfuscated one

type ToolHistoryEntry

type ToolHistoryEntry struct {
	ID         string   `json:"id"`
	UserID     string   `json:"userId"`
	UserName   string   `json:"userName"`
	PickupDate int64    `json:"pickupDate"` // Unix timestamp
	Location   Location `json:"location"`
	BookingID  string   `json:"bookingId,omitempty"`
}

ToolHistoryEntry represents an entry in a nomadic tool's history

type ToolID

type ToolID struct {
	ID int64 `json:"id"`
}

type ToolSearch

type ToolSearch struct {
	SearchTerm       string  `json:"searchTerm"`
	Categories       []int   `json:"categories"`
	Distance         int     `json:"distance"`
	MaxCost          *uint64 `json:"maxCost"`
	MayBeFree        *bool   `json:"mayBeFree"`
	AvailableFrom    int     `json:"availableFrom"`
	TransportOptions []int   `json:"transportOptions"`
	CommunityID      string  `json:"communityId,omitempty"`
	Page             int     `json:"page,omitempty"`
}

ToolSearch is the type of the tool search

type UnreadMessageSummary

type UnreadMessageSummary struct {
	Total        int64            `json:"total"`
	Private      int64            `json:"private"`
	Communities  map[string]int64 `json:"communities,omitempty"`
	GeneralForum int64            `json:"generalForum"`
}

UnreadMessageSummary represents unread message counts

type UpdateCommunityRequest

type UpdateCommunityRequest struct {
	Name  string         `json:"name,omitempty"`
	Image types.HexBytes `json:"image,omitempty"`
}

UpdateCommunityRequest represents the request to update a community

type User

type User struct {
	UserPreview
	Email                   string                  `json:"email"`
	Community               string                  `json:"community"`
	Tokens                  uint64                  `json:"tokens"`
	Location                Location                `json:"location"`
	Verified                bool                    `json:"verified"`
	CreatedAt               time.Time               `json:"createdAt"`
	LastSeen                time.Time               `json:"lastSeen"`
	Bio                     string                  `json:"bio"`
	InviteCodes             []*SimpleInviteCode     `json:"inviteCodes,omitempty"`
	Communities             []UserCommunityInfo     `json:"communities,omitempty"`
	NotificationPreferences NotificationPreferences `json:"notificationPreferences,omitempty"`
	AdditionalContacts      AdditionalContacts      `json:"additionalContacts,omitempty"`
	LanguageCode            string                  `json:"lang,omitempty"`
	UnreadMessageCount      *UnreadMessageSummary   `json:"unreadMessageCount,omitempty"`
}

User represents the user type

func (*User) FromDBUser

func (u *User) FromDBUser(dbu *db.User, includePrivateData bool, includeAdditionalContacts bool) *User

FromDBUser converts a DB User to an API User (full version) If includePrivateData is true, private data like notification preferences and useRealLocation will be included

func (*User) ObjectID

func (u *User) ObjectID() primitive.ObjectID

ObjectID returns the ObjectID of the user, or a nil ObjectID if the ID is not a valid ObjectID. This is useful for converting the ID to an ObjectID for use in database queries.

type UserCommunityInfo

type UserCommunityInfo struct {
	ID   string `json:"id"`
	Role string `json:"role"`
}

UserCommunityInfo represents a user's role in a community

type UserPreview

type UserPreview struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	AvatarHash  types.HexBytes `json:"avatarHash"`
	RatingCount int            `json:"ratingCount"`
	Rating      int            `json:"rating"`
	Active      bool           `json:"active"`
	Karma       int64          `json:"karma"`
}

User preview for list calls (does not send full information)

func (*UserPreview) FromDBUserPreview

func (up *UserPreview) FromDBUserPreview(dbu *db.User) *UserPreview

FromDBUserPreview converts a DB User to an API UserPreview

type UserProfile

type UserProfile struct {
	Name                    string                  `json:"name"`
	Community               string                  `json:"community"`
	Location                *Location               `json:"location,omitempty"`
	Active                  *bool                   `json:"active,omitempty"`
	Avatar                  []byte                  `json:"avatar,omitempty"`
	Password                string                  `json:"password,omitempty"`
	ActualPassword          string                  `json:"actualPassword,omitempty"`
	Bio                     string                  `json:"bio,omitempty"`
	NotificationPreferences NotificationPreferences `json:"notificationPreferences,omitempty"`
	InviteCodes             []*SimpleInviteCode     `json:"inviteCodes,omitempty"`
	AdditionalContacts      AdditionalContacts      `json:"additionalContacts,omitempty"`
	LanguageCode            string                  `json:"lang,omitempty"`
}

type UsersWrapper

type UsersWrapper struct {
	Users      []*User        `json:"users"`
	Pagination PaginationInfo `json:"pagination"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL