add app CRUD and public store API endpoints
This commit is contained in:
511
portal/internal/api/handlers/apps.go
Normal file
511
portal/internal/api/handlers/apps.go
Normal file
@@ -0,0 +1,511 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/omixlab/mosis-portal/internal/api/middleware"
|
||||||
|
"github.com/omixlab/mosis-portal/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AppHandler handles app-related endpoints
|
||||||
|
type AppHandler struct {
|
||||||
|
db *database.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAppHandler creates a new app handler
|
||||||
|
func NewAppHandler(db *database.DB) *AppHandler {
|
||||||
|
return &AppHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateAppRequest is the request body for creating an app
|
||||||
|
type CreateAppRequest struct {
|
||||||
|
PackageID string `json:"package_id" validate:"required,package_id"`
|
||||||
|
Name string `json:"name" validate:"required,min=1,max=50"`
|
||||||
|
Description string `json:"description,omitempty" validate:"max=500"`
|
||||||
|
Category string `json:"category,omitempty" validate:"max=50"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAppRequest is the request body for updating an app
|
||||||
|
type UpdateAppRequest struct {
|
||||||
|
Name *string `json:"name,omitempty" validate:"omitempty,min=1,max=50"`
|
||||||
|
Description *string `json:"description,omitempty" validate:"omitempty,max=500"`
|
||||||
|
Category *string `json:"category,omitempty" validate:"omitempty,max=50"`
|
||||||
|
Tags []string `json:"tags,omitempty" validate:"omitempty,max=10,dive,max=30"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List lists the developer's apps
|
||||||
|
func (h *AppHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse query parameters
|
||||||
|
status := r.URL.Query().Get("status")
|
||||||
|
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if limit < 1 || limit > 100 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
apps, total, err := h.db.ListApps(r.Context(), developerID, status, page, limit)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to list apps: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"apps": apps,
|
||||||
|
"total": total,
|
||||||
|
"pagination": map[string]interface{}{
|
||||||
|
"page": page,
|
||||||
|
"limit": limit,
|
||||||
|
"total": total,
|
||||||
|
"total_pages": (total + limit - 1) / limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create creates a new app
|
||||||
|
func (h *AppHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req CreateAppRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
Error(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate package ID format
|
||||||
|
if !isValidPackageID(req.PackageID) {
|
||||||
|
Error(w, "invalid package_id format (must be like com.example.app)", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if package_id already exists
|
||||||
|
existing, _ := h.db.GetAppByPackageID(r.Context(), req.PackageID)
|
||||||
|
if existing != nil {
|
||||||
|
Error(w, "package_id already exists", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
app, err := h.db.CreateApp(r.Context(), &database.App{
|
||||||
|
DeveloperID: developerID,
|
||||||
|
PackageID: req.PackageID,
|
||||||
|
Name: req.Name,
|
||||||
|
Description: req.Description,
|
||||||
|
Category: req.Category,
|
||||||
|
Status: "draft",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to create app: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusCreated, app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a specific app
|
||||||
|
func (h *AppHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update updates an app
|
||||||
|
func (h *AppHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req UpdateAppRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
Error(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply updates
|
||||||
|
if req.Name != nil {
|
||||||
|
app.Name = *req.Name
|
||||||
|
}
|
||||||
|
if req.Description != nil {
|
||||||
|
app.Description = *req.Description
|
||||||
|
}
|
||||||
|
if req.Category != nil {
|
||||||
|
app.Category = *req.Category
|
||||||
|
}
|
||||||
|
if req.Tags != nil {
|
||||||
|
app.Tags = req.Tags
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.UpdateApp(r.Context(), app); err != nil {
|
||||||
|
Error(w, "failed to update app: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete deletes an app
|
||||||
|
func (h *AppHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if app has published versions
|
||||||
|
hasPublished, err := h.db.AppHasPublishedVersions(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to check versions: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasPublished {
|
||||||
|
Error(w, "cannot delete app with published versions", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.DeleteApp(r.Context(), appID); err != nil {
|
||||||
|
Error(w, "failed to delete app: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListVersions lists versions for an app
|
||||||
|
func (h *AppHandler) ListVersions(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse query parameters
|
||||||
|
status := r.URL.Query().Get("status")
|
||||||
|
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if limit < 1 || limit > 100 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
versions, total, err := h.db.ListVersions(r.Context(), appID, status, page, limit)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to list versions: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"versions": versions,
|
||||||
|
"total": total,
|
||||||
|
"pagination": map[string]interface{}{
|
||||||
|
"page": page,
|
||||||
|
"limit": limit,
|
||||||
|
"total": total,
|
||||||
|
"total_pages": (total + limit - 1) / limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateVersionRequest is the request body for creating a version
|
||||||
|
type CreateVersionRequest struct {
|
||||||
|
VersionName string `json:"version_name" validate:"required"`
|
||||||
|
VersionCode int `json:"version_code" validate:"required,min=1"`
|
||||||
|
ReleaseNotes string `json:"release_notes,omitempty" validate:"max=5000"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateVersion creates a new app version
|
||||||
|
func (h *AppHandler) CreateVersion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req CreateVersionRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
Error(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if version code already exists
|
||||||
|
exists, err := h.db.VersionCodeExists(r.Context(), appID, req.VersionCode)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to check version: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
Error(w, "version_code already exists for this app", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := h.db.CreateVersion(r.Context(), &database.AppVersion{
|
||||||
|
AppID: appID,
|
||||||
|
VersionName: req.VersionName,
|
||||||
|
VersionCode: req.VersionCode,
|
||||||
|
ReleaseNotes: req.ReleaseNotes,
|
||||||
|
Status: "draft",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to create version: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate upload URL (for now, just a placeholder path)
|
||||||
|
uploadURL := "/packages/" + appID + "/" + version.ID + ".mosis"
|
||||||
|
uploadExpires := time.Now().Add(1 * time.Hour).Format(time.RFC3339)
|
||||||
|
|
||||||
|
JSON(w, http.StatusCreated, map[string]interface{}{
|
||||||
|
"version": version,
|
||||||
|
"upload_url": uploadURL,
|
||||||
|
"upload_expires": uploadExpires,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVersion retrieves a specific version
|
||||||
|
func (h *AppHandler) GetVersion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
versionID := chi.URLParam(r, "versionID")
|
||||||
|
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := h.db.GetVersion(r.Context(), versionID)
|
||||||
|
if err != nil || version.AppID != appID {
|
||||||
|
Error(w, "version not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitVersion submits a version for review
|
||||||
|
func (h *AppHandler) SubmitVersion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
versionID := chi.URLParam(r, "versionID")
|
||||||
|
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := h.db.GetVersion(r.Context(), versionID)
|
||||||
|
if err != nil || version.AppID != appID {
|
||||||
|
Error(w, "version not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check current status
|
||||||
|
if version.Status != "draft" && version.Status != "rejected" {
|
||||||
|
Error(w, "version cannot be submitted (current status: "+version.Status+")", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if package is uploaded
|
||||||
|
if version.PackageURL == "" {
|
||||||
|
Error(w, "package must be uploaded before submitting", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version.Status = "review"
|
||||||
|
if err := h.db.UpdateVersionStatus(r.Context(), versionID, "review"); err != nil {
|
||||||
|
Error(w, "failed to submit version: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublishVersion publishes an approved version
|
||||||
|
func (h *AppHandler) PublishVersion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
developerID := middleware.GetDeveloperID(r.Context())
|
||||||
|
if developerID == "" {
|
||||||
|
Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
appID := chi.URLParam(r, "appID")
|
||||||
|
versionID := chi.URLParam(r, "versionID")
|
||||||
|
|
||||||
|
app, err := h.db.GetApp(r.Context(), appID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify ownership
|
||||||
|
if app.DeveloperID != developerID {
|
||||||
|
Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := h.db.GetVersion(r.Context(), versionID)
|
||||||
|
if err != nil || version.AppID != appID {
|
||||||
|
Error(w, "version not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check current status - must be approved
|
||||||
|
if version.Status != "approved" {
|
||||||
|
Error(w, "version must be approved before publishing (current status: "+version.Status+")", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
version.Status = "published"
|
||||||
|
version.PublishedAt = &now
|
||||||
|
|
||||||
|
if err := h.db.PublishVersion(r.Context(), versionID); err != nil {
|
||||||
|
Error(w, "failed to publish version: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update app status to published
|
||||||
|
if app.Status == "draft" {
|
||||||
|
app.Status = "published"
|
||||||
|
h.db.UpdateAppStatus(r.Context(), appID, "published")
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isValidPackageID validates package ID format (com.example.app)
|
||||||
|
func isValidPackageID(id string) bool {
|
||||||
|
if len(id) < 5 || len(id) > 100 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Simple validation: lowercase letters, digits, and dots; must have at least 2 dots
|
||||||
|
dots := 0
|
||||||
|
for i, c := range id {
|
||||||
|
if c == '.' {
|
||||||
|
dots++
|
||||||
|
// No consecutive dots, no leading/trailing dots
|
||||||
|
if i == 0 || i == len(id)-1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return dots >= 2
|
||||||
|
}
|
||||||
120
portal/internal/api/handlers/store.go
Normal file
120
portal/internal/api/handlers/store.go
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/omixlab/mosis-portal/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StoreHandler handles public store endpoints
|
||||||
|
type StoreHandler struct {
|
||||||
|
db *database.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStoreHandler creates a new store handler
|
||||||
|
func NewStoreHandler(db *database.DB) *StoreHandler {
|
||||||
|
return &StoreHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListApps returns published apps for the store
|
||||||
|
func (h *StoreHandler) ListApps(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Parse query parameters
|
||||||
|
query := r.URL.Query().Get("q")
|
||||||
|
category := r.URL.Query().Get("category")
|
||||||
|
sort := r.URL.Query().Get("sort")
|
||||||
|
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if limit < 1 || limit > 100 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
apps, total, err := h.db.ListPublishedApps(r.Context(), query, category, sort, page, limit)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "failed to list apps: "+err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"apps": apps,
|
||||||
|
"total": total,
|
||||||
|
"pagination": map[string]interface{}{
|
||||||
|
"page": page,
|
||||||
|
"limit": limit,
|
||||||
|
"total": total,
|
||||||
|
"total_pages": (total + limit - 1) / limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetApp returns a published app by package ID
|
||||||
|
func (h *StoreHandler) GetApp(w http.ResponseWriter, r *http.Request) {
|
||||||
|
packageID := chi.URLParam(r, "packageID")
|
||||||
|
|
||||||
|
app, err := h.db.GetPublishedApp(r.Context(), packageID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "app not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download returns download info for the latest version of an app
|
||||||
|
func (h *StoreHandler) Download(w http.ResponseWriter, r *http.Request) {
|
||||||
|
packageID := chi.URLParam(r, "packageID")
|
||||||
|
|
||||||
|
version, err := h.db.GetLatestPublishedVersion(r.Context(), packageID)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "no published version found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"download_url": version.PackageURL,
|
||||||
|
"version": version.VersionName,
|
||||||
|
"version_code": version.VersionCode,
|
||||||
|
"size": version.PackageSize,
|
||||||
|
"signature": version.Signature,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadVersion returns download info for a specific version
|
||||||
|
func (h *StoreHandler) DownloadVersion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
packageID := chi.URLParam(r, "packageID")
|
||||||
|
versionCodeStr := chi.URLParam(r, "versionCode")
|
||||||
|
|
||||||
|
versionCode, err := strconv.Atoi(versionCodeStr)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "invalid version code", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := h.db.GetPublishedVersionByCode(r.Context(), packageID, versionCode)
|
||||||
|
if err != nil {
|
||||||
|
Error(w, "version not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"download_url": version.PackageURL,
|
||||||
|
"version": version.VersionName,
|
||||||
|
"version_code": version.VersionCode,
|
||||||
|
"size": version.PackageSize,
|
||||||
|
"signature": version.Signature,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckUpdates checks for app updates
|
||||||
|
func (h *StoreHandler) CheckUpdates(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Parse request body for installed apps
|
||||||
|
// For now, return empty updates
|
||||||
|
JSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"updates": []interface{}{},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -32,6 +32,8 @@ func NewRouter(cfg *config.Config, db *database.DB) http.Handler {
|
|||||||
)
|
)
|
||||||
authMiddleware := middleware.NewAuthMiddleware(jwtManager, db)
|
authMiddleware := middleware.NewAuthMiddleware(jwtManager, db)
|
||||||
authHandler := handlers.NewAuthHandler(oauthManager, jwtManager, db)
|
authHandler := handlers.NewAuthHandler(oauthManager, jwtManager, db)
|
||||||
|
appHandler := handlers.NewAppHandler(db)
|
||||||
|
storeHandler := handlers.NewStoreHandler(db)
|
||||||
|
|
||||||
// Health check
|
// Health check
|
||||||
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
|
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -63,19 +65,19 @@ func NewRouter(cfg *config.Config, db *database.DB) http.Handler {
|
|||||||
|
|
||||||
// Developer apps
|
// Developer apps
|
||||||
r.Route("/apps", func(r chi.Router) {
|
r.Route("/apps", func(r chi.Router) {
|
||||||
r.Get("/", handlers.NotImplemented)
|
r.Get("/", appHandler.List)
|
||||||
r.Post("/", handlers.NotImplemented)
|
r.Post("/", appHandler.Create)
|
||||||
r.Get("/{appID}", handlers.NotImplemented)
|
r.Get("/{appID}", appHandler.Get)
|
||||||
r.Patch("/{appID}", handlers.NotImplemented)
|
r.Patch("/{appID}", appHandler.Update)
|
||||||
r.Delete("/{appID}", handlers.NotImplemented)
|
r.Delete("/{appID}", appHandler.Delete)
|
||||||
|
|
||||||
// Versions
|
// Versions
|
||||||
r.Route("/{appID}/versions", func(r chi.Router) {
|
r.Route("/{appID}/versions", func(r chi.Router) {
|
||||||
r.Get("/", handlers.NotImplemented)
|
r.Get("/", appHandler.ListVersions)
|
||||||
r.Post("/", handlers.NotImplemented)
|
r.Post("/", appHandler.CreateVersion)
|
||||||
r.Get("/{versionID}", handlers.NotImplemented)
|
r.Get("/{versionID}", appHandler.GetVersion)
|
||||||
r.Post("/{versionID}/submit", handlers.NotImplemented)
|
r.Post("/{versionID}/submit", appHandler.SubmitVersion)
|
||||||
r.Post("/{versionID}/publish", handlers.NotImplemented)
|
r.Post("/{versionID}/publish", appHandler.PublishVersion)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -96,10 +98,11 @@ func NewRouter(cfg *config.Config, db *database.DB) http.Handler {
|
|||||||
|
|
||||||
// Public store endpoints
|
// Public store endpoints
|
||||||
r.Route("/store", func(r chi.Router) {
|
r.Route("/store", func(r chi.Router) {
|
||||||
r.Get("/apps", handlers.NotImplemented)
|
r.Get("/apps", storeHandler.ListApps)
|
||||||
r.Get("/apps/{appID}", handlers.NotImplemented)
|
r.Get("/apps/updates", storeHandler.CheckUpdates)
|
||||||
r.Get("/apps/{appID}/download", handlers.NotImplemented)
|
r.Get("/apps/{packageID}", storeHandler.GetApp)
|
||||||
r.Get("/apps/updates", handlers.NotImplemented)
|
r.Get("/apps/{packageID}/download", storeHandler.Download)
|
||||||
|
r.Get("/apps/{packageID}/versions/{versionCode}/download", storeHandler.DownloadVersion)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Telemetry (API key auth preferred, but can work without for initial setup)
|
// Telemetry (API key auth preferred, but can work without for initial setup)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package database
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -360,3 +361,512 @@ func (db *DB) LogAudit(ctx context.Context, developerID, action, ipAddress, user
|
|||||||
VALUES (?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?)
|
||||||
`, developerID, action, details, ipAddress, userAgent)
|
`, developerID, action, details, ipAddress, userAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// App represents an app in the database
|
||||||
|
type App struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
DeveloperID string `json:"developer_id"`
|
||||||
|
PackageID string `json:"package_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
Tags []string `json:"tags"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppVersion represents an app version in the database
|
||||||
|
type AppVersion struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
AppID string `json:"app_id"`
|
||||||
|
VersionCode int `json:"version_code"`
|
||||||
|
VersionName string `json:"version_name"`
|
||||||
|
PackageURL string `json:"package_url,omitempty"`
|
||||||
|
PackageSize int64 `json:"package_size,omitempty"`
|
||||||
|
Signature string `json:"signature,omitempty"`
|
||||||
|
Permissions []string `json:"permissions"`
|
||||||
|
MinMosisVersion string `json:"min_mosis_version,omitempty"`
|
||||||
|
ReleaseNotes string `json:"release_notes,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
ReviewNotes string `json:"review_notes,omitempty"`
|
||||||
|
PublishedAt *time.Time `json:"published_at,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateApp creates a new app
|
||||||
|
func (db *DB) CreateApp(ctx context.Context, app *App) (*App, error) {
|
||||||
|
app.ID = uuid.New().String()
|
||||||
|
app.Tags = []string{}
|
||||||
|
app.CreatedAt = time.Now()
|
||||||
|
app.UpdatedAt = app.CreatedAt
|
||||||
|
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
INSERT INTO apps (id, developer_id, package_id, name, description, category, tags, status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, '[]', ?, datetime('now'), datetime('now'))
|
||||||
|
`, app.ID, app.DeveloperID, app.PackageID, app.Name, app.Description, app.Category, app.Status)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return app, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetApp retrieves an app by ID
|
||||||
|
func (db *DB) GetApp(ctx context.Context, id string) (*App, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT id, developer_id, package_id, name, description, category, tags, status, created_at, updated_at
|
||||||
|
FROM apps WHERE id = ?
|
||||||
|
`, id)
|
||||||
|
|
||||||
|
return scanApp(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAppByPackageID retrieves an app by package ID
|
||||||
|
func (db *DB) GetAppByPackageID(ctx context.Context, packageID string) (*App, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT id, developer_id, package_id, name, description, category, tags, status, created_at, updated_at
|
||||||
|
FROM apps WHERE package_id = ?
|
||||||
|
`, packageID)
|
||||||
|
|
||||||
|
return scanApp(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanApp(row *sql.Row) (*App, error) {
|
||||||
|
var app App
|
||||||
|
var desc, cat, tagsJSON sql.NullString
|
||||||
|
var createdAt, updatedAt string
|
||||||
|
|
||||||
|
err := row.Scan(&app.ID, &app.DeveloperID, &app.PackageID, &app.Name, &desc, &cat, &tagsJSON, &app.Status, &createdAt, &updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Description = desc.String
|
||||||
|
app.Category = cat.String
|
||||||
|
app.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||||
|
app.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||||
|
|
||||||
|
// Parse tags JSON
|
||||||
|
app.Tags = []string{}
|
||||||
|
if tagsJSON.Valid && tagsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(tagsJSON.String), &app.Tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &app, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListApps lists apps for a developer
|
||||||
|
func (db *DB) ListApps(ctx context.Context, developerID, status string, page, limit int) ([]*App, int, error) {
|
||||||
|
offset := (page - 1) * limit
|
||||||
|
|
||||||
|
// Build query
|
||||||
|
query := "SELECT id, developer_id, package_id, name, description, category, tags, status, created_at, updated_at FROM apps WHERE developer_id = ?"
|
||||||
|
countQuery := "SELECT COUNT(*) FROM apps WHERE developer_id = ?"
|
||||||
|
args := []interface{}{developerID}
|
||||||
|
countArgs := []interface{}{developerID}
|
||||||
|
|
||||||
|
if status != "" {
|
||||||
|
query += " AND status = ?"
|
||||||
|
countQuery += " AND status = ?"
|
||||||
|
args = append(args, status)
|
||||||
|
countArgs = append(countArgs, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
query += " ORDER BY updated_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
// Get total count
|
||||||
|
var total int
|
||||||
|
db.QueryRowContext(ctx, countQuery, countArgs...).Scan(&total)
|
||||||
|
|
||||||
|
// Get apps
|
||||||
|
rows, err := db.QueryContext(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var apps []*App
|
||||||
|
for rows.Next() {
|
||||||
|
var app App
|
||||||
|
var desc, cat, tagsJSON sql.NullString
|
||||||
|
var createdAt, updatedAt string
|
||||||
|
|
||||||
|
err := rows.Scan(&app.ID, &app.DeveloperID, &app.PackageID, &app.Name, &desc, &cat, &tagsJSON, &app.Status, &createdAt, &updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Description = desc.String
|
||||||
|
app.Category = cat.String
|
||||||
|
app.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||||
|
app.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||||
|
app.Tags = []string{}
|
||||||
|
if tagsJSON.Valid && tagsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(tagsJSON.String), &app.Tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
apps = append(apps, &app)
|
||||||
|
}
|
||||||
|
|
||||||
|
return apps, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateApp updates an app
|
||||||
|
func (db *DB) UpdateApp(ctx context.Context, app *App) error {
|
||||||
|
tagsJSON, _ := json.Marshal(app.Tags)
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
UPDATE apps SET name = ?, description = ?, category = ?, tags = ?, updated_at = datetime('now')
|
||||||
|
WHERE id = ?
|
||||||
|
`, app.Name, app.Description, app.Category, string(tagsJSON), app.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAppStatus updates an app's status
|
||||||
|
func (db *DB) UpdateAppStatus(ctx context.Context, id, status string) error {
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
UPDATE apps SET status = ?, updated_at = datetime('now') WHERE id = ?
|
||||||
|
`, status, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteApp deletes an app and its versions
|
||||||
|
func (db *DB) DeleteApp(ctx context.Context, id string) error {
|
||||||
|
_, err := db.ExecContext(ctx, `DELETE FROM apps WHERE id = ?`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppHasPublishedVersions checks if an app has any published versions
|
||||||
|
func (db *DB) AppHasPublishedVersions(ctx context.Context, appID string) (bool, error) {
|
||||||
|
var count int
|
||||||
|
err := db.QueryRowContext(ctx, `
|
||||||
|
SELECT COUNT(*) FROM app_versions WHERE app_id = ? AND status = 'published'
|
||||||
|
`, appID).Scan(&count)
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateVersion creates a new app version
|
||||||
|
func (db *DB) CreateVersion(ctx context.Context, version *AppVersion) (*AppVersion, error) {
|
||||||
|
version.ID = uuid.New().String()
|
||||||
|
version.Permissions = []string{}
|
||||||
|
version.CreatedAt = time.Now()
|
||||||
|
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
INSERT INTO app_versions (id, app_id, version_code, version_name, package_url, package_size, signature, permissions, min_mosis_version, release_notes, status, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, '', 0, '', '[]', '', ?, 'draft', datetime('now'))
|
||||||
|
`, version.ID, version.AppID, version.VersionCode, version.VersionName, version.ReleaseNotes)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return version, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVersion retrieves a version by ID
|
||||||
|
func (db *DB) GetVersion(ctx context.Context, id string) (*AppVersion, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT id, app_id, version_code, version_name, package_url, package_size, signature, permissions, min_mosis_version, release_notes, status, review_notes, published_at, created_at
|
||||||
|
FROM app_versions WHERE id = ?
|
||||||
|
`, id)
|
||||||
|
|
||||||
|
return scanVersion(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanVersion(row *sql.Row) (*AppVersion, error) {
|
||||||
|
var v AppVersion
|
||||||
|
var packageURL, signature, permsJSON, minVersion, releaseNotes, reviewNotes sql.NullString
|
||||||
|
var publishedAt, createdAt sql.NullString
|
||||||
|
var packageSize sql.NullInt64
|
||||||
|
|
||||||
|
err := row.Scan(&v.ID, &v.AppID, &v.VersionCode, &v.VersionName, &packageURL, &packageSize, &signature, &permsJSON, &minVersion, &releaseNotes, &v.Status, &reviewNotes, &publishedAt, &createdAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v.PackageURL = packageURL.String
|
||||||
|
v.PackageSize = packageSize.Int64
|
||||||
|
v.Signature = signature.String
|
||||||
|
v.MinMosisVersion = minVersion.String
|
||||||
|
v.ReleaseNotes = releaseNotes.String
|
||||||
|
v.ReviewNotes = reviewNotes.String
|
||||||
|
|
||||||
|
v.Permissions = []string{}
|
||||||
|
if permsJSON.Valid && permsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(permsJSON.String), &v.Permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
if createdAt.Valid {
|
||||||
|
v.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt.String)
|
||||||
|
}
|
||||||
|
if publishedAt.Valid {
|
||||||
|
t, _ := time.Parse("2006-01-02 15:04:05", publishedAt.String)
|
||||||
|
v.PublishedAt = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
return &v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListVersions lists versions for an app
|
||||||
|
func (db *DB) ListVersions(ctx context.Context, appID, status string, page, limit int) ([]*AppVersion, int, error) {
|
||||||
|
offset := (page - 1) * limit
|
||||||
|
|
||||||
|
query := "SELECT id, app_id, version_code, version_name, package_url, package_size, signature, permissions, min_mosis_version, release_notes, status, review_notes, published_at, created_at FROM app_versions WHERE app_id = ?"
|
||||||
|
countQuery := "SELECT COUNT(*) FROM app_versions WHERE app_id = ?"
|
||||||
|
args := []interface{}{appID}
|
||||||
|
countArgs := []interface{}{appID}
|
||||||
|
|
||||||
|
if status != "" {
|
||||||
|
query += " AND status = ?"
|
||||||
|
countQuery += " AND status = ?"
|
||||||
|
args = append(args, status)
|
||||||
|
countArgs = append(countArgs, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
query += " ORDER BY version_code DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
var total int
|
||||||
|
db.QueryRowContext(ctx, countQuery, countArgs...).Scan(&total)
|
||||||
|
|
||||||
|
rows, err := db.QueryContext(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var versions []*AppVersion
|
||||||
|
for rows.Next() {
|
||||||
|
var v AppVersion
|
||||||
|
var packageURL, signature, permsJSON, minVersion, releaseNotes, reviewNotes sql.NullString
|
||||||
|
var publishedAt, createdAt sql.NullString
|
||||||
|
var packageSize sql.NullInt64
|
||||||
|
|
||||||
|
err := rows.Scan(&v.ID, &v.AppID, &v.VersionCode, &v.VersionName, &packageURL, &packageSize, &signature, &permsJSON, &minVersion, &releaseNotes, &v.Status, &reviewNotes, &publishedAt, &createdAt)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
v.PackageURL = packageURL.String
|
||||||
|
v.PackageSize = packageSize.Int64
|
||||||
|
v.Signature = signature.String
|
||||||
|
v.MinMosisVersion = minVersion.String
|
||||||
|
v.ReleaseNotes = releaseNotes.String
|
||||||
|
v.ReviewNotes = reviewNotes.String
|
||||||
|
|
||||||
|
v.Permissions = []string{}
|
||||||
|
if permsJSON.Valid && permsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(permsJSON.String), &v.Permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
if createdAt.Valid {
|
||||||
|
v.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt.String)
|
||||||
|
}
|
||||||
|
if publishedAt.Valid {
|
||||||
|
t, _ := time.Parse("2006-01-02 15:04:05", publishedAt.String)
|
||||||
|
v.PublishedAt = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
versions = append(versions, &v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return versions, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VersionCodeExists checks if a version code exists for an app
|
||||||
|
func (db *DB) VersionCodeExists(ctx context.Context, appID string, code int) (bool, error) {
|
||||||
|
var count int
|
||||||
|
err := db.QueryRowContext(ctx, `
|
||||||
|
SELECT COUNT(*) FROM app_versions WHERE app_id = ? AND version_code = ?
|
||||||
|
`, appID, code).Scan(&count)
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateVersionStatus updates a version's status
|
||||||
|
func (db *DB) UpdateVersionStatus(ctx context.Context, id, status string) error {
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
UPDATE app_versions SET status = ? WHERE id = ?
|
||||||
|
`, status, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublishVersion publishes a version
|
||||||
|
func (db *DB) PublishVersion(ctx context.Context, id string) error {
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
UPDATE app_versions SET status = 'published', published_at = datetime('now') WHERE id = ?
|
||||||
|
`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublicApp represents a published app for the store
|
||||||
|
type PublicApp struct {
|
||||||
|
PackageID string `json:"package_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
Tags []string `json:"tags"`
|
||||||
|
AuthorName string `json:"author_name"`
|
||||||
|
LatestVersion string `json:"latest_version"`
|
||||||
|
DownloadCount int64 `json:"download_count"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPublishedApps lists published apps for the store
|
||||||
|
func (db *DB) ListPublishedApps(ctx context.Context, query, category, sort string, page, limit int) ([]*PublicApp, int, error) {
|
||||||
|
offset := (page - 1) * limit
|
||||||
|
|
||||||
|
// Base query
|
||||||
|
baseQuery := `
|
||||||
|
SELECT a.package_id, a.name, a.description, a.category, a.tags, d.name as author_name,
|
||||||
|
COALESCE(v.version_name, '') as latest_version, 0 as download_count,
|
||||||
|
a.created_at, a.updated_at
|
||||||
|
FROM apps a
|
||||||
|
JOIN developers d ON d.id = a.developer_id
|
||||||
|
LEFT JOIN app_versions v ON v.app_id = a.id AND v.status = 'published'
|
||||||
|
WHERE a.status = 'published'
|
||||||
|
`
|
||||||
|
countQuery := `SELECT COUNT(*) FROM apps WHERE status = 'published'`
|
||||||
|
var args []interface{}
|
||||||
|
var countArgs []interface{}
|
||||||
|
|
||||||
|
// Search filter
|
||||||
|
if query != "" {
|
||||||
|
baseQuery += " AND (a.name LIKE ? OR a.description LIKE ? OR a.package_id LIKE ?)"
|
||||||
|
countQuery += " AND (name LIKE ? OR description LIKE ? OR package_id LIKE ?)"
|
||||||
|
searchTerm := "%" + query + "%"
|
||||||
|
args = append(args, searchTerm, searchTerm, searchTerm)
|
||||||
|
countArgs = append(countArgs, searchTerm, searchTerm, searchTerm)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category filter
|
||||||
|
if category != "" {
|
||||||
|
baseQuery += " AND a.category = ?"
|
||||||
|
countQuery += " AND category = ?"
|
||||||
|
args = append(args, category)
|
||||||
|
countArgs = append(countArgs, category)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group by to handle multiple versions (pick latest)
|
||||||
|
baseQuery += " GROUP BY a.id"
|
||||||
|
|
||||||
|
// Sorting
|
||||||
|
switch sort {
|
||||||
|
case "name":
|
||||||
|
baseQuery += " ORDER BY a.name ASC"
|
||||||
|
case "recent":
|
||||||
|
baseQuery += " ORDER BY a.updated_at DESC"
|
||||||
|
default: // popular
|
||||||
|
baseQuery += " ORDER BY a.updated_at DESC" // TODO: implement download count sorting
|
||||||
|
}
|
||||||
|
|
||||||
|
baseQuery += " LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
// Get total count
|
||||||
|
var total int
|
||||||
|
db.QueryRowContext(ctx, countQuery, countArgs...).Scan(&total)
|
||||||
|
|
||||||
|
// Get apps
|
||||||
|
rows, err := db.QueryContext(ctx, baseQuery, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var apps []*PublicApp
|
||||||
|
for rows.Next() {
|
||||||
|
var app PublicApp
|
||||||
|
var desc, cat, tagsJSON, latestVersion sql.NullString
|
||||||
|
var createdAt, updatedAt string
|
||||||
|
|
||||||
|
err := rows.Scan(&app.PackageID, &app.Name, &desc, &cat, &tagsJSON, &app.AuthorName,
|
||||||
|
&latestVersion, &app.DownloadCount, &createdAt, &updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Description = desc.String
|
||||||
|
app.Category = cat.String
|
||||||
|
app.LatestVersion = latestVersion.String
|
||||||
|
app.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||||
|
app.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||||
|
|
||||||
|
app.Tags = []string{}
|
||||||
|
if tagsJSON.Valid && tagsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(tagsJSON.String), &app.Tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
apps = append(apps, &app)
|
||||||
|
}
|
||||||
|
|
||||||
|
return apps, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPublishedApp retrieves a published app by package ID for the store
|
||||||
|
func (db *DB) GetPublishedApp(ctx context.Context, packageID string) (*PublicApp, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT a.package_id, a.name, a.description, a.category, a.tags, d.name as author_name,
|
||||||
|
COALESCE(v.version_name, '') as latest_version, 0 as download_count,
|
||||||
|
a.created_at, a.updated_at
|
||||||
|
FROM apps a
|
||||||
|
JOIN developers d ON d.id = a.developer_id
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT app_id, version_name FROM app_versions
|
||||||
|
WHERE status = 'published'
|
||||||
|
ORDER BY version_code DESC LIMIT 1
|
||||||
|
) v ON v.app_id = a.id
|
||||||
|
WHERE a.package_id = ? AND a.status = 'published'
|
||||||
|
`, packageID)
|
||||||
|
|
||||||
|
var app PublicApp
|
||||||
|
var desc, cat, tagsJSON, latestVersion sql.NullString
|
||||||
|
var createdAt, updatedAt string
|
||||||
|
|
||||||
|
err := row.Scan(&app.PackageID, &app.Name, &desc, &cat, &tagsJSON, &app.AuthorName,
|
||||||
|
&latestVersion, &app.DownloadCount, &createdAt, &updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Description = desc.String
|
||||||
|
app.Category = cat.String
|
||||||
|
app.LatestVersion = latestVersion.String
|
||||||
|
app.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||||
|
app.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||||
|
|
||||||
|
app.Tags = []string{}
|
||||||
|
if tagsJSON.Valid && tagsJSON.String != "" {
|
||||||
|
json.Unmarshal([]byte(tagsJSON.String), &app.Tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &app, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLatestPublishedVersion retrieves the latest published version for an app by package ID
|
||||||
|
func (db *DB) GetLatestPublishedVersion(ctx context.Context, packageID string) (*AppVersion, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT v.id, v.app_id, v.version_code, v.version_name, v.package_url, v.package_size, v.signature,
|
||||||
|
v.permissions, v.min_mosis_version, v.release_notes, v.status, v.review_notes, v.published_at, v.created_at
|
||||||
|
FROM app_versions v
|
||||||
|
JOIN apps a ON a.id = v.app_id
|
||||||
|
WHERE a.package_id = ? AND v.status = 'published'
|
||||||
|
ORDER BY v.version_code DESC
|
||||||
|
LIMIT 1
|
||||||
|
`, packageID)
|
||||||
|
|
||||||
|
return scanVersion(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPublishedVersionByCode retrieves a specific published version by package ID and version code
|
||||||
|
func (db *DB) GetPublishedVersionByCode(ctx context.Context, packageID string, versionCode int) (*AppVersion, error) {
|
||||||
|
row := db.QueryRowContext(ctx, `
|
||||||
|
SELECT v.id, v.app_id, v.version_code, v.version_name, v.package_url, v.package_size, v.signature,
|
||||||
|
v.permissions, v.min_mosis_version, v.release_notes, v.status, v.review_notes, v.published_at, v.created_at
|
||||||
|
FROM app_versions v
|
||||||
|
JOIN apps a ON a.id = v.app_id
|
||||||
|
WHERE a.package_id = ? AND v.version_code = ? AND v.status = 'published'
|
||||||
|
`, packageID, versionCode)
|
||||||
|
|
||||||
|
return scanVersion(row)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user