Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c642763035 | ||
|
|
b869f70922 |
@@ -17,6 +17,9 @@ var expectedRoutes = []string{
|
||||
"GET /api/v1/files/folders",
|
||||
"GET /api/v1/files/:id",
|
||||
"GET /api/v1/files/:id/ocr",
|
||||
"GET /api/v1/files/:id/content",
|
||||
"GET /api/v1/files/:id/shares",
|
||||
"GET /api/v1/files/:id/links",
|
||||
"DELETE /api/v1/files/:id",
|
||||
"POST /api/v1/files/upload",
|
||||
|
||||
|
||||
@@ -107,6 +107,33 @@ func FilesGetOcr(c *gin.Context) {
|
||||
api.OK(c, dto)
|
||||
}
|
||||
|
||||
// FilesContent streame les octets physiques d'un fichier visible (viewer+,
|
||||
// own ou shared) : GET /files/:id/content. Réponse binaire (Content-Type du
|
||||
// fichier, Content-Disposition inline) — jamais d'enveloppe {data}. Supporte
|
||||
// Range via http.ServeContent (Gin c.File). Sans bytes serveur (ressource
|
||||
// metadata-only jamais uploadée) → 404 NOT_FOUND, comme invisible (pas
|
||||
// d'énumération). V1 streaming : le client ne persiste rien.
|
||||
func FilesContent(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
|
||||
return
|
||||
}
|
||||
info, err := Store.OpenContent(userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", info.MimeType)
|
||||
c.Header("Content-Disposition", "inline; filename=\""+info.Name+"\"")
|
||||
c.File(info.Path)
|
||||
}
|
||||
|
||||
func FilesDelete(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
|
||||
@@ -686,3 +686,147 @@ func TestSearchQTooLong(t *testing.T) {
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/search?q="+string(long), token, nil, "")
|
||||
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "search-q-too-long")
|
||||
}
|
||||
|
||||
func TestFilesContentStreaming(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
ownerDevice := repository.NewID()
|
||||
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "ct"), "content-test-password", ownerDevice)
|
||||
granteeDevice := repository.NewID()
|
||||
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "cg"), "content-test-password-b", granteeDevice)
|
||||
outsiderDevice := repository.NewID()
|
||||
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "ch"), "content-test-password-c", outsiderDevice)
|
||||
|
||||
// Ressource metadata-only (outbox) puis upload ciblé des octets (≤10o, cf. setup).
|
||||
fileID := repository.NewID()
|
||||
if err := repo.Resources.InsertFile(owner, fileID, "note.txt", "", 0, nil, nil); err != nil {
|
||||
t.Fatalf("insert file: %v", err)
|
||||
}
|
||||
rec := uploadMultipartToResource(t, r, ownerToken, fileID, "note.txt", []byte("hello"))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("upload ciblé: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Owner : octets + Content-Type.
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", ownerToken, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("content-owner: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.String() != "hello" {
|
||||
t.Errorf("content-owner = %q, attendu %q", rec.Body.String(), "hello")
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct == "" {
|
||||
t.Errorf("content-owner: Content-Type manquant")
|
||||
}
|
||||
|
||||
// Grantée viewer : mêmes octets (résolution dir owner, pas requester).
|
||||
if err := repo.Shares.Upsert(fileID, grantee, "viewer", false, nil, owner); err != nil {
|
||||
t.Fatalf("share: %v", err)
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", granteeToken, nil, "")
|
||||
if rec.Code != http.StatusOK || rec.Body.String() != "hello" {
|
||||
t.Errorf("content-grantee: attendu 200 hello, got %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Outsider : 404 (pas d'énumération).
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", outsiderToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-outsider")
|
||||
|
||||
// Metadata-only sans octets : 404 (jamais uploadé).
|
||||
bareID := repository.NewID()
|
||||
if err := repo.Resources.InsertFile(owner, bareID, "vide.txt", "", 0, nil, nil); err != nil {
|
||||
t.Fatalf("insert bare: %v", err)
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+bareID+"/content", ownerToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-no-bytes")
|
||||
|
||||
// ID invalide → 404 ; sans token → 401.
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/content", ownerToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-invalid-id")
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", "", nil, "")
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("content-sans-token: attendu 401, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilesSharesLinksListing(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
ownerDevice := repository.NewID()
|
||||
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "sl"), "shares-list-password", ownerDevice)
|
||||
granteeDevice := repository.NewID()
|
||||
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "sg"), "shares-list-password-b", granteeDevice)
|
||||
outsiderDevice := repository.NewID()
|
||||
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "sh"), "shares-list-password-c", outsiderDevice)
|
||||
|
||||
fileID := repository.NewID()
|
||||
if err := repo.Resources.InsertFile(owner, fileID, "shared.txt", "", 4, nil, nil); err != nil {
|
||||
t.Fatalf("insert file: %v", err)
|
||||
}
|
||||
|
||||
// Vide au départ (pas d'erreur).
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", ownerToken, nil, "")
|
||||
env := expectOK(t, rec, "shares-empty")
|
||||
var emptyShares []map[string]any
|
||||
if err := json.Unmarshal(env.Data, &emptyShares); err != nil {
|
||||
t.Fatalf("shares-empty: unmarshal: %v", err)
|
||||
}
|
||||
if len(emptyShares) != 0 {
|
||||
t.Errorf("shares-empty = %d grants, attendu 0", len(emptyShares))
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", ownerToken, nil, "")
|
||||
env = expectOK(t, rec, "links-empty")
|
||||
var emptyLinks []map[string]any
|
||||
if err := json.Unmarshal(env.Data, &emptyLinks); err != nil {
|
||||
t.Fatalf("links-empty: unmarshal: %v", err)
|
||||
}
|
||||
if len(emptyLinks) != 0 {
|
||||
t.Errorf("links-empty = %d links, attendu 0", len(emptyLinks))
|
||||
}
|
||||
|
||||
// Un grant + un lien côté serveur (comme après des ops `share`/`create_link`).
|
||||
if err := repo.Shares.Upsert(fileID, grantee, "editor", true, nil, owner); err != nil {
|
||||
t.Fatalf("share: %v", err)
|
||||
}
|
||||
linkToken := repository.NewID()
|
||||
if err := repo.Shares.CreateLink(linkToken, fileID, "viewer", nil, owner); err != nil {
|
||||
t.Fatalf("create link: %v", err)
|
||||
}
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", ownerToken, nil, "")
|
||||
env = expectOK(t, rec, "shares-owner")
|
||||
var grants []struct {
|
||||
GranteeUserID string `json:"granteeUserId"`
|
||||
Username string `json:"username"`
|
||||
Access string `json:"access"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &grants); err != nil {
|
||||
t.Fatalf("shares-owner: unmarshal: %v", err)
|
||||
}
|
||||
if len(grants) != 1 || grants[0].GranteeUserID != grantee || grants[0].Access != "editor" || grants[0].Username == "" {
|
||||
t.Errorf("shares-owner = %+v, attendu 1 grant editor du grantee", grants)
|
||||
}
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", ownerToken, nil, "")
|
||||
env = expectOK(t, rec, "links-owner")
|
||||
var links []struct {
|
||||
Token string `json:"token"`
|
||||
Access string `json:"access"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &links); err != nil {
|
||||
t.Fatalf("links-owner: unmarshal: %v", err)
|
||||
}
|
||||
if len(links) != 1 || links[0].Token != linkToken || links[0].Access != "viewer" {
|
||||
t.Errorf("links-owner = %+v, attendu 1 lien viewer", links)
|
||||
}
|
||||
|
||||
// Granté et outsider : 404 (pas d'énumération).
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", granteeToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-grantee")
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/links", granteeToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "links-grantee")
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/shares", outsiderToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-outsider")
|
||||
|
||||
// ID invalide → 404.
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/shares", ownerToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-invalid-id")
|
||||
}
|
||||
|
||||
@@ -33,6 +33,9 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
protected.GET("/files/folders", FoldersList)
|
||||
protected.GET("/files/:id", FilesGet)
|
||||
protected.GET("/files/:id/ocr", FilesGetOcr)
|
||||
protected.GET("/files/:id/content", FilesContent)
|
||||
protected.GET("/files/:id/shares", SharesList)
|
||||
protected.GET("/files/:id/links", LinksList)
|
||||
protected.DELETE("/files/:id", FilesDelete)
|
||||
protected.POST("/files/upload", FilesUpload)
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/kazier/backend/pkg/api"
|
||||
)
|
||||
|
||||
// SharesList exposes the active user-to-user grants of a resource the caller
|
||||
// OWNS : GET /files/:id/shares. Non-owner (or unknown resource) → 404
|
||||
// NOT_FOUND (no enumeration, same scoping as the share outbox ops).
|
||||
func SharesList(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
|
||||
return
|
||||
}
|
||||
grants, err := Store.ListShares(userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, grants)
|
||||
}
|
||||
|
||||
// LinksList exposes the active public links of a resource the caller OWNS :
|
||||
// GET /files/:id/links. Same owner-only scoping as SharesList.
|
||||
func LinksList(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
|
||||
return
|
||||
}
|
||||
links, err := Store.ListLinks(userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, links)
|
||||
}
|
||||
@@ -455,5 +455,49 @@ func (s *Shares) ListActiveLinksForResource(resourceID string) ([]LinkInfo, erro
|
||||
return links, rows.Err()
|
||||
}
|
||||
|
||||
// ShareGrant is one active user-to-user grant on a resource (owner view).
|
||||
type ShareGrant struct {
|
||||
GranteeUserID string
|
||||
Username string
|
||||
Access string
|
||||
Inherit bool
|
||||
ExpiresAt *time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// ListActiveForResource returns the active (non-revoked) grants on a resource,
|
||||
// oldest first. Expired grants are included (the owner sees what will lapse);
|
||||
// the caller filters display. Empty (not error) when nothing is shared.
|
||||
func (s *Shares) ListActiveForResource(resourceID string) ([]ShareGrant, error) {
|
||||
rows, err := s.DB.Query(
|
||||
`SELECT s.grantee_user_id, COALESCE(u.username, s.grantee_user_id),
|
||||
s.access, s.inherit, s.expires_at, s.updated_at
|
||||
FROM shares s
|
||||
LEFT JOIN users u ON u.id = s.grantee_user_id AND u.deleted_at IS NULL
|
||||
WHERE s.resource_id = $1 AND s.revoked_at IS NULL
|
||||
ORDER BY s.created_at ASC`,
|
||||
resourceID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var grants []ShareGrant
|
||||
for rows.Next() {
|
||||
var (
|
||||
g ShareGrant
|
||||
expiresAt sql.NullTime
|
||||
)
|
||||
if err := rows.Scan(&g.GranteeUserID, &g.Username, &g.Access, &g.Inherit, &expiresAt, &g.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if expiresAt.Valid {
|
||||
g.ExpiresAt = &expiresAt.Time
|
||||
}
|
||||
grants = append(grants, g)
|
||||
}
|
||||
return grants, rows.Err()
|
||||
}
|
||||
|
||||
// Errors specific to shares.
|
||||
var ErrGranteeNotFound = errors.New("grantee user not found")
|
||||
|
||||
@@ -146,6 +146,66 @@ type FileOcrDTO struct {
|
||||
UpdatedAt string `json:"updatedAt,omitempty"`
|
||||
}
|
||||
|
||||
// ContentInfo describes the physical bytes of a file the user can see
|
||||
// (viewer+, own or shared) for GET /files/:id/content (streaming lecture,
|
||||
// jamais persisté côté client en V1 streaming).
|
||||
type ContentInfo struct {
|
||||
Path string
|
||||
Name string
|
||||
MimeType string
|
||||
Size int64
|
||||
}
|
||||
|
||||
// OpenContent resolves the physical file of a visible resource. Auth is
|
||||
// viewer+ (GetFileVisible, own or shared) ; the bytes live under the OWNER
|
||||
// dir (UPLOAD_DIR/<owner_id>/<resource_id>.<ext>), never under the requester.
|
||||
// No physical file (metadata-only outbox resource, never uploaded) →
|
||||
// repository.ErrNotFound (handler maps to 404 NOT_FOUND, same as invisible).
|
||||
func (s *Resources) OpenContent(userID, resourceID string) (ContentInfo, error) {
|
||||
row, err := s.Repo.GetFileVisible(userID, resourceID)
|
||||
if err != nil {
|
||||
return ContentInfo{}, err
|
||||
}
|
||||
ownerID, err := s.Repo.GetResourceOwner(resourceID)
|
||||
if err != nil {
|
||||
return ContentInfo{}, err
|
||||
}
|
||||
if !idPattern.MatchString(ownerID) || !idPattern.MatchString(resourceID) {
|
||||
return ContentInfo{}, repository.ErrNotFound
|
||||
}
|
||||
base, err := filepath.EvalSymlinks(s.UploadDir)
|
||||
if err != nil {
|
||||
return ContentInfo{}, repository.ErrNotFound
|
||||
}
|
||||
matches, err := filepath.Glob(filepath.Join(s.UploadDir, ownerID, resourceID+".*"))
|
||||
if err != nil {
|
||||
return ContentInfo{}, repository.ErrNotFound
|
||||
}
|
||||
for _, m := range matches {
|
||||
if !strings.HasPrefix(filepath.Base(m), resourceID+".") {
|
||||
continue
|
||||
}
|
||||
fi, err := os.Lstat(m)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(m)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
rel, err := filepath.Rel(base, resolved)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
continue
|
||||
}
|
||||
mime := row.MimeType
|
||||
if mime == "" {
|
||||
mime = "application/octet-stream"
|
||||
}
|
||||
return ContentInfo{Path: resolved, Name: row.Name, MimeType: mime, Size: fi.Size()}, nil
|
||||
}
|
||||
return ContentInfo{}, repository.ErrNotFound
|
||||
}
|
||||
|
||||
// GetFileOcr returns the OCR text of a file the user can see (viewer+, own or
|
||||
// shared). Absent text → Text empty ("") with 200 (the caller decides).
|
||||
func (s *Resources) GetFileOcr(ownerID, id string) (FileOcrDTO, error) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// ShareGrantDTO serializes one active grant for GET /files/:id/shares.
|
||||
// Milliseconds epoch (null = never), mirroring the permissions snapshot
|
||||
// (docs/api-v1.md §6.2) for cheap client-side expiry checks.
|
||||
type ShareGrantDTO struct {
|
||||
GranteeUserID string `json:"granteeUserId"`
|
||||
Username string `json:"username"`
|
||||
Access string `json:"access"`
|
||||
Inherit bool `json:"inherit"`
|
||||
ExpiresAt *int64 `json:"expiresAt"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// LinkDTO serializes one active public link for GET /files/:id/links —
|
||||
// same shape as the public GET /shares/links/:token resolution.
|
||||
type LinkDTO struct {
|
||||
Token string `json:"token"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
ResourceType string `json:"resourceType"`
|
||||
Name string `json:"name"`
|
||||
Access string `json:"access"`
|
||||
ExpiresAt *string `json:"expiresAt"`
|
||||
}
|
||||
|
||||
// ListShares returns the active grants on a resource the user OWNS.
|
||||
// Non-owner (or unknown resource) → repository.ErrNotFound (no enumeration,
|
||||
// same scoping as the share outbox ops).
|
||||
func (s *Resources) ListShares(userID, resourceID string) ([]ShareGrantDTO, error) {
|
||||
ownerID, err := s.Repo.GetResourceOwner(resourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ownerID != userID {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
grants, err := s.Repository.Shares.ListActiveForResource(resourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ShareGrantDTO, 0, len(grants))
|
||||
for _, g := range grants {
|
||||
var expires *int64
|
||||
if g.ExpiresAt != nil {
|
||||
ms := g.ExpiresAt.UnixMilli()
|
||||
expires = &ms
|
||||
}
|
||||
out = append(out, ShareGrantDTO{
|
||||
GranteeUserID: g.GranteeUserID,
|
||||
Username: g.Username,
|
||||
Access: g.Access,
|
||||
Inherit: g.Inherit,
|
||||
ExpiresAt: expires,
|
||||
UpdatedAt: g.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListLinks returns the active public links of a resource the user OWNS.
|
||||
// Same owner-only scoping as ListShares.
|
||||
func (s *Resources) ListLinks(userID, resourceID string) ([]LinkDTO, error) {
|
||||
ownerID, err := s.Repo.GetResourceOwner(resourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ownerID != userID {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
links, err := s.Repository.Shares.ListActiveLinksForResource(resourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]LinkDTO, 0, len(links))
|
||||
for _, l := range links {
|
||||
var expires *string
|
||||
if l.ExpiresAt != nil {
|
||||
// Même forme que ShareLinkGet (time.Time marshaled en RFC3339).
|
||||
str := l.ExpiresAt.UTC().Format(time.RFC3339)
|
||||
expires = &str
|
||||
}
|
||||
out = append(out, LinkDTO{
|
||||
Token: l.Token,
|
||||
ResourceID: l.ResourceID,
|
||||
ResourceType: l.ResourceType,
|
||||
Name: l.Name,
|
||||
Access: l.Access,
|
||||
ExpiresAt: expires,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -37,6 +37,7 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
|
||||
| PATCH | `/users/me/password` | `{ "current_password", "new_password" }` | `{ "id" }` | `INVALID_PASSWORD` (403) |
|
||||
| GET | `/files` | query `folderId?`, `page?`, `pageSize?`, `sort?` | `FileDto[]` (+ `meta`) | — |
|
||||
| GET | `/files/:id` | — | `FileDto` | `NOT_FOUND` |
|
||||
| GET | `/files/:id/content` | — (binaire brut, hors enveloppe `{data}` ; `Range` supporté) | octets physiques (`Content-Type` du fichier, `Content-Disposition: inline`) — streaming lecture seule, jamais persisté côté client | `NOT_FOUND` (invisible OU metadata-only jamais uploadé — indistinguables) |
|
||||
| DELETE | `/files/:id` | — | `{ "id": "…" }` | `NOT_FOUND` |
|
||||
| GET | `/files/search` | query `q` (obligatoire), `page?`, `pageSize?` | `FileDto[]` (+ `meta`) | — |
|
||||
| GET | `/files/folders` | — | `FolderDto[]` (racines) | — |
|
||||
@@ -44,6 +45,8 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
|
||||
| POST | `/ocr/jobs` | `{ "fileId": "…" }` | `OcrJob` | — |
|
||||
| GET | `/ocr/jobs/:id` | — | `OcrJob` | `NOT_FOUND` |
|
||||
| GET | `/files/:id/ocr` | — | `FileOcr` (`{ text, updatedAt }`) | `NOT_FOUND` |
|
||||
| GET | `/files/:id/shares` | — (owner uniquement) | `ShareGrant[]` (`{ granteeUserId, username, access, inherit, expiresAt (ms\|null), updatedAt (ms) }`) | `NOT_FOUND` (non-owner ou inconnue — pas d'énumération) |
|
||||
| GET | `/files/:id/links` | — (owner uniquement) | `ShareLink[]` (même forme que `GET /shares/links/:token`) | `NOT_FOUND` (non-owner ou inconnue) |
|
||||
| POST | `/sync/ops` | voir §6 | voir §6 | — |
|
||||
| GET | `/sync/permissions` | query `after?` (cached_at ms) | `ResourcePermission[]` | — |
|
||||
|
||||
|
||||
@@ -41,6 +41,16 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- Liens de partage `kazier://share/<token>` (32-hex) : ouverture
|
||||
dans l'écran de résolution (route publique, sans auth). -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data
|
||||
android:scheme="kazier"
|
||||
android:host="share" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
|
||||
@@ -51,6 +51,20 @@ class SecureTokenStore @Inject constructor(
|
||||
override fun getExpiresAt(): Long? =
|
||||
prefs.getLong(KEY_EXPIRES_AT, -1L).takeIf { it >= 0L }
|
||||
|
||||
override fun getCredentials(): Credentials? {
|
||||
val username = prefs.getString(KEY_USERNAME, null)?.takeIf { it.isNotBlank() } ?: return null
|
||||
val password = prefs.getString(KEY_PASSWORD, null)?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return Credentials(username, password)
|
||||
}
|
||||
|
||||
override fun saveCredentials(username: String, password: String) {
|
||||
prefs.edit().putString(KEY_USERNAME, username).putString(KEY_PASSWORD, password).apply()
|
||||
}
|
||||
|
||||
override fun clearCredentials() {
|
||||
prefs.edit().remove(KEY_USERNAME).remove(KEY_PASSWORD).apply()
|
||||
}
|
||||
|
||||
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||
prefs.edit()
|
||||
.putString(KEY_TOKEN, token)
|
||||
@@ -70,5 +84,7 @@ class SecureTokenStore @Inject constructor(
|
||||
private const val KEY_TOKEN = "kazier.auth_token"
|
||||
private const val KEY_ACCOUNT = "kazier.account"
|
||||
private const val KEY_EXPIRES_AT = "kazier.expires_at"
|
||||
private const val KEY_USERNAME = "kazier.auth_username"
|
||||
private const val KEY_PASSWORD = "kazier.auth_password"
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package com.kazier.mobile.auth
|
||||
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.remote.dto.UserDto
|
||||
import com.kazier.mobile.data.repository.AuthRepository
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.LocalModeStore
|
||||
import javax.inject.Inject
|
||||
@@ -10,8 +12,23 @@ import javax.inject.Singleton
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
|
||||
/** Événements de session vers l'UI (re-login silencieux, lot 3). */
|
||||
sealed interface AuthEvent {
|
||||
/** Le token a été renouvelé sans action utilisateur — rester connecté. */
|
||||
data class Reauthenticated(val user: UserDto) : AuthEvent
|
||||
|
||||
/** Plus de session récupérable — afficher le login (pré-rempli si possible). */
|
||||
data class SessionExpired(val username: String?) : AuthEvent
|
||||
}
|
||||
|
||||
/**
|
||||
* Orchestration de la session (restauration/sauvegarde/purge) : relie le store
|
||||
@@ -20,8 +37,15 @@ import kotlinx.coroutines.withContext
|
||||
* ([LocalModeStore]) pour survivre aux redémarrages.
|
||||
*
|
||||
* Le callback 401 est possédé ici (singleton, M25) — jamais par un ViewModel :
|
||||
* après `onCleared`, un token expiré/révoqué continue de purger la session
|
||||
* (le worker cesse alors de rejouer l'outbox sous un token mort).
|
||||
* après `onCleared`, un token expiré/révoqué continue d'être traité (le worker
|
||||
* cesse alors de rejouer l'outbox sous un token mort).
|
||||
*
|
||||
* Re-login silencieux (lot 3) : les identifiants saisis au login sont
|
||||
* persistés chiffrés ; sur 401 (ou token expiré détecté en proactif), une
|
||||
* seule tentative de `POST /auth/login` est jouée (single-flight). Succès →
|
||||
* [AuthEvent.Reauthenticated] (file conservée si même compte) ; identifiants
|
||||
* rejetés → purge complète + [AuthEvent.SessionExpired]. La requête en vol
|
||||
* ayant subi le 401 n'est PAS rejouée — l'appelant la relance (pull, retry).
|
||||
*/
|
||||
@Singleton
|
||||
class SessionManager @Inject constructor(
|
||||
@@ -31,14 +55,22 @@ class SessionManager @Inject constructor(
|
||||
private val localModeStore: LocalModeStore,
|
||||
private val pendingOperationDao: PendingOperationDao,
|
||||
private val apiClient: ApiClient,
|
||||
private val authRepository: AuthRepository,
|
||||
) {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
/** Single-flight du re-login : N 401 concurrents → 1 seul `POST /auth/login`. */
|
||||
private val reloginMutex = Mutex()
|
||||
|
||||
private val _events = MutableSharedFlow<AuthEvent>(extraBufferCapacity = 4)
|
||||
val events: SharedFlow<AuthEvent> = _events.asSharedFlow()
|
||||
|
||||
init {
|
||||
// 401 sur un endpoint protégé (token expiré/révoqué, compte supprimé)
|
||||
// → purge de la session. Le 401 du login et des routes publiques est
|
||||
// exonéré côté ApiClient (skipUnauthorizedHandling).
|
||||
// → re-login silencieux puis purge si irrécupérable. Le 401 du login
|
||||
// et des routes publiques est exonéré côté ApiClient
|
||||
// (skipUnauthorizedHandling).
|
||||
apiClient.onUnauthorized = { handleUnauthorized() }
|
||||
}
|
||||
|
||||
@@ -50,10 +82,18 @@ class SessionManager @Inject constructor(
|
||||
AuthSession(token = token, user = user, expiresAt = tokenStore.getExpiresAt())
|
||||
}
|
||||
|
||||
suspend fun save(token: String, user: UserDto, expiresAt: Long? = null) =
|
||||
withContext(Dispatchers.IO) {
|
||||
suspend fun save(
|
||||
token: String,
|
||||
user: UserDto,
|
||||
expiresAt: Long? = null,
|
||||
username: String? = null,
|
||||
password: String? = null,
|
||||
) = withContext(Dispatchers.IO) {
|
||||
val previousUserId = activeUserStore.get()
|
||||
tokenStore.save(token, user, expiresAt)
|
||||
if (username != null && password != null) {
|
||||
tokenStore.saveCredentials(username, password)
|
||||
}
|
||||
activeUserStore.set(user.id)
|
||||
localModeStore.clear()
|
||||
tokenProvider.current = token
|
||||
@@ -69,6 +109,7 @@ class SessionManager @Inject constructor(
|
||||
|
||||
suspend fun clear() = withContext(Dispatchers.IO) {
|
||||
tokenStore.clear()
|
||||
tokenStore.clearCredentials()
|
||||
activeUserStore.clear()
|
||||
tokenProvider.current = null
|
||||
// Sign-out explicite : la file non poussée est abandonnée (C5, voir
|
||||
@@ -77,16 +118,73 @@ class SessionManager @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge fire-and-forget sur 401 (appelée depuis le thread OkHttp via
|
||||
* 401 sur endpoint protégé (appelée depuis le thread OkHttp via
|
||||
* `ApiClient`) : le token en mémoire tombe synchronement pour ne plus
|
||||
* émettre de requêtes authentifiées, la persistance suit en IO.
|
||||
* émettre de requêtes authentifiées, puis le re-login silencieux est tenté
|
||||
* en IO (single-flight).
|
||||
*/
|
||||
fun handleUnauthorized() {
|
||||
tokenProvider.current = null
|
||||
scope.launch {
|
||||
reloginMutex.withLock { silentReloginLocked() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-login proactif (démarrage, retour foreground) : si le token en
|
||||
* mémoire est absent ou expiré et que des identifiants sont sauvés, tente
|
||||
* un renouvellement. Vrai si un token frais est disponible au retour.
|
||||
*/
|
||||
suspend fun trySilentRelogin(nowMs: Long = System.currentTimeMillis()): Boolean =
|
||||
withContext(Dispatchers.IO) {
|
||||
if (tokenProvider.current != null && !isTokenExpired(nowMs)) return@withContext true
|
||||
reloginMutex.withLock { silentReloginLocked() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Corps du re-login, sous [reloginMutex]. Vrai si la session est (à
|
||||
* nouveau) valide. Émet [AuthEvent.Reauthenticated] en cas de succès et
|
||||
* [AuthEvent.SessionExpired] quand rien n'est récupérable.
|
||||
*/
|
||||
private suspend fun silentReloginLocked(): Boolean {
|
||||
// Re-vérification sous mutex : un re-login concurrent vient peut-être
|
||||
// de rafraîchir le token pendant l'attente du verrou (N 401 → 1 login).
|
||||
if (tokenProvider.current != null && !isTokenExpired()) return true
|
||||
val creds = runCatching { tokenStore.getCredentials() }.getOrNull()
|
||||
if (creds == null) {
|
||||
purgeToExpired(username = null)
|
||||
return false
|
||||
}
|
||||
return try {
|
||||
val response = authRepository.login(creds.username, creds.password)
|
||||
save(response.token, response.user, response.expiresAt)
|
||||
Timber.d("auth: re-login silencieux OK pour %s", creds.username)
|
||||
_events.tryEmit(AuthEvent.Reauthenticated(response.user))
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
if (e is ApiException && e.code == "UNAUTHORIZED") {
|
||||
// Identifiants rejetés (mot de passe changé ailleurs, compte
|
||||
// supprimé) : ne plus jamais les rejouer.
|
||||
Timber.w("auth: re-login rejeté, purge des identifiants")
|
||||
runCatching { tokenStore.clearCredentials() }
|
||||
purgeToExpired(username = creds.username)
|
||||
} else {
|
||||
// Transitoire (réseau/5xx) : token mort, identifiants conservés
|
||||
// pour une tentative ultérieure (prochain démarrage/login).
|
||||
Timber.w(e, "auth: re-login transitoire, session expirée")
|
||||
purgeToExpired(username = creds.username)
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Purge token + compte actif (file intacte, cf. C5) + événement UI. */
|
||||
private suspend fun purgeToExpired(username: String?) {
|
||||
val knownUsername = username ?: runCatching { tokenStore.getUser()?.username }.getOrNull()
|
||||
tokenProvider.current = null
|
||||
runCatching { tokenStore.clear() }
|
||||
runCatching { activeUserStore.clear() }
|
||||
}
|
||||
_events.tryEmit(AuthEvent.SessionExpired(knownUsername))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,11 @@ import com.kazier.mobile.data.remote.dto.UserDto
|
||||
* Persistance du token paseto, du profil compte et de l'expiration du token
|
||||
* (claim `expires_at` du login, TTL 7 j). Implémentation : [SecureTokenStore]
|
||||
* (Keystore + AES, jamais en clair dans SQLite).
|
||||
*
|
||||
* Les identifiants (username + password) sont persistés à part pour le
|
||||
* re-login silencieux sur 401 (lot 3) : ils survivent à la purge du token
|
||||
* ([clear] ne les touche pas) et ne tombent qu'au sign-out explicite
|
||||
* ([clearCredentials]) ou quand le serveur les rejette (401 au re-login).
|
||||
*/
|
||||
interface TokenStore {
|
||||
|
||||
@@ -18,5 +23,19 @@ interface TokenStore {
|
||||
|
||||
fun save(token: String, user: UserDto, expiresAt: Long?)
|
||||
|
||||
/** Purge token + compte + expiration — jamais les identifiants. */
|
||||
fun clear()
|
||||
|
||||
/** Identifiants du re-login silencieux — null si jamais connectés. */
|
||||
fun getCredentials(): Credentials?
|
||||
|
||||
fun saveCredentials(username: String, password: String)
|
||||
|
||||
fun clearCredentials()
|
||||
}
|
||||
|
||||
/** Identifiants persistés (chiffrés) pour le re-login silencieux. */
|
||||
data class Credentials(
|
||||
val username: String,
|
||||
val password: String,
|
||||
)
|
||||
|
||||
+15
@@ -198,4 +198,19 @@ interface PendingOperationDao {
|
||||
AND status IN ('pending', 'synced')
|
||||
""")
|
||||
suspend fun countMoveOperations(resourceId: String): Int
|
||||
|
||||
/**
|
||||
* Ops de partage encore en attente de push pour cette ressource
|
||||
* (`share`, `update_share`, `revoke_share`, `create_link`, `revoke_link`).
|
||||
* Le sheet de partage les affiche comme « en attente d'envoi » : la liste
|
||||
* serveur ne les reflète qu'après le drain du worker.
|
||||
*/
|
||||
@Query("""
|
||||
SELECT * FROM pending_operations
|
||||
WHERE resource_id = :resourceId
|
||||
AND operation IN ('share', 'update_share', 'revoke_share', 'create_link', 'revoke_link')
|
||||
AND status = 'pending'
|
||||
ORDER BY id ASC
|
||||
""")
|
||||
suspend fun pendingShareOps(resourceId: String): List<PendingOperationEntity>
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
@@ -161,6 +162,96 @@ class ApiClient @Inject constructor(
|
||||
suspend fun getShareLink(token: String): ShareLinkDto =
|
||||
unwrap({ apiService.getShareLink(token) }, skipUnauthorizedHandling = true)
|
||||
|
||||
/**
|
||||
* Grants actifs d'une ressource possédée — `GET /files/:id/shares`
|
||||
* (owner uniquement, 404 sinon).
|
||||
*/
|
||||
suspend fun listShares(fileId: String): List<ShareGrantDto> =
|
||||
unwrap({ apiService.listShares(fileId) })
|
||||
|
||||
/**
|
||||
* Liens publics actifs d'une ressource possédée — `GET /files/:id/links`
|
||||
* (owner uniquement, 404 sinon).
|
||||
*/
|
||||
suspend fun listLinks(fileId: String): List<ShareLinkDto> =
|
||||
unwrap({ apiService.listLinks(fileId) })
|
||||
|
||||
/**
|
||||
* Octets physiques d'un fichier visible — `GET /files/:id/content`
|
||||
* (binaire brut, hors enveloppe). Streaming sans cache : lecture bornée
|
||||
* à [maxBytes] (+1 pour détecter le dépassement → `FILE_TOO_LARGE`),
|
||||
* jamais persistée. 404 = invisible ou metadata-only sans octets.
|
||||
*/
|
||||
suspend fun downloadContentBytes(
|
||||
fileId: String,
|
||||
maxBytes: Long = MAX_CONTENT_BYTES,
|
||||
): ByteArray {
|
||||
val response = try {
|
||||
apiService.downloadContent(fileId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
Timber.d(e, "api: transport error (content)")
|
||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||
} catch (e: Exception) {
|
||||
if (e is CancellationException) throw e
|
||||
Timber.d(e, "api: unexpected error (content)")
|
||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||
}
|
||||
if (!response.isSuccessful) {
|
||||
val status = response.code()
|
||||
if (status == 401) {
|
||||
onUnauthorized?.invoke()
|
||||
}
|
||||
val error = response.errorBody()?.use { body ->
|
||||
body.string().let { raw ->
|
||||
runCatching { errorEnvelopeAdapter.fromJson(raw)?.error }.getOrNull()
|
||||
}
|
||||
}
|
||||
throw ApiException(
|
||||
code = error?.code ?: if (status == 404) "NOT_FOUND" else "HTTP_$status",
|
||||
message = error?.message ?: "HTTP $status",
|
||||
httpCode = status,
|
||||
)
|
||||
}
|
||||
val body = response.body()
|
||||
?: throw ApiException("INVALID_RESPONSE", "Réponse serveur invalide (corps vide)", response.code())
|
||||
if (body.contentLength() > maxBytes) {
|
||||
body.close()
|
||||
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
|
||||
}
|
||||
try {
|
||||
body.byteStream().use { input ->
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buf = ByteArray(32 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buf)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > maxBytes) {
|
||||
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
|
||||
}
|
||||
out.write(buf, 0, read)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
throw e
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||
} finally {
|
||||
body.close()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */
|
||||
const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L
|
||||
}
|
||||
|
||||
private suspend fun <T> unwrap(
|
||||
call: suspend () -> Response<ApiEnvelope<T>>,
|
||||
skipUnauthorizedHandling: Boolean = false,
|
||||
|
||||
@@ -13,11 +13,13 @@ import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.DELETE
|
||||
@@ -28,6 +30,7 @@ import retrofit2.http.POST
|
||||
import retrofit2.http.Part
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
import retrofit2.http.Streaming
|
||||
|
||||
/**
|
||||
* Contrat HTTP V1 — copie de `mobile/api/client.ts` (le client mobile est la
|
||||
@@ -119,6 +122,18 @@ interface ApiService {
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<FileDto>>
|
||||
|
||||
/**
|
||||
* Octets physiques d'un fichier visible (viewer+, own ou shared) —
|
||||
* `GET /files/:id/content` (binaire brut, hors enveloppe `{data}`).
|
||||
* Streaming lecture seule : le client ne persiste rien (V1 streaming).
|
||||
* 404 = invisible OU metadata-only jamais uploadé (indistinguables).
|
||||
*/
|
||||
@Streaming
|
||||
@GET("files/{id}/content")
|
||||
suspend fun downloadContent(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ResponseBody>
|
||||
|
||||
/** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */
|
||||
@DELETE("files/{id}")
|
||||
suspend fun deleteFile(
|
||||
@@ -154,4 +169,22 @@ interface ApiService {
|
||||
suspend fun getShareLink(
|
||||
@Path("token") token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>>
|
||||
|
||||
/**
|
||||
* Grants actifs d'une ressource possédée (`GET /files/:id/shares`,
|
||||
* owner uniquement — 404 sinon, pas d'énumération).
|
||||
*/
|
||||
@GET("files/{id}/shares")
|
||||
suspend fun listShares(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>>
|
||||
|
||||
/**
|
||||
* Liens publics actifs d'une ressource possédée (`GET /files/:id/links`,
|
||||
* owner uniquement — même forme que `getShareLink`).
|
||||
*/
|
||||
@GET("files/{id}/links")
|
||||
suspend fun listLinks(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>>
|
||||
}
|
||||
@@ -112,6 +112,21 @@ data class ShareLinkDto(
|
||||
@Json(name = "expiresAt") val expiresAt: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Grant actif `GET /files/:id/shares` (owner uniquement) — miroir de
|
||||
* `ShareGrantDTO` Go. `expiresAt` en ms epoch (null = jamais), même
|
||||
* convention que le snapshot `ResourcePermissionDto` pour les comparaisons
|
||||
* locales (`System.currentTimeMillis()`).
|
||||
*/
|
||||
data class ShareGrantDto(
|
||||
@Json(name = "granteeUserId") val granteeUserId: String,
|
||||
@Json(name = "username") val username: String,
|
||||
@Json(name = "access") val access: String,
|
||||
@Json(name = "inherit") val inherit: Boolean,
|
||||
@Json(name = "expiresAt") val expiresAt: Long? = null,
|
||||
@Json(name = "updatedAt") val updatedAt: Long = 0L,
|
||||
)
|
||||
|
||||
/** Outbox — une op du batch `POST /sync/ops` (docs/api-v1.md §6.1). */
|
||||
data class SyncOpDto(
|
||||
@Json(name = "operation_id") val operationId: String,
|
||||
|
||||
@@ -222,6 +222,13 @@ class OutboxRepository @Inject constructor(
|
||||
/** Nombre d'ops en attente de push (stats UI optionnelles). */
|
||||
suspend fun countPending(): Int = pendingOperationDao.countPending()
|
||||
|
||||
/**
|
||||
* Ops de partage en attente pour une ressource (sheet de partage :
|
||||
* « en attente d'envoi », pas encore reflétées par les listes serveur).
|
||||
*/
|
||||
suspend fun pendingShareOps(resourceId: String): List<PendingOperationEntity> =
|
||||
pendingOperationDao.pendingShareOps(resourceId)
|
||||
|
||||
/**
|
||||
* Un `create_resource` (pending ou synced) existe-t-il déjà pour ce fichier ?
|
||||
* Utilisé par le gate « processed » : seuls les fichiers traités déclenchent
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.kazier.mobile.data.repository
|
||||
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Contenu distant en streaming (V1 finitions, lot download).
|
||||
*
|
||||
* Lit les octets physiques d'un fichier visible via
|
||||
* `GET /files/:id/content` (binaire brut, hors enveloppe) sans jamais les
|
||||
* persister : ni Room, ni SAF, ni fichier durable. Seul le rendu PDF exige
|
||||
* un fichier temporaire du `cacheDir`, créé à la volée par le viewer et
|
||||
* supprimé à sa sortie (éphémère, pas un cache).
|
||||
*/
|
||||
@Singleton
|
||||
class RemoteContentRepository @Inject constructor(
|
||||
private val apiClient: ApiClient,
|
||||
) {
|
||||
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
|
||||
suspend fun fetch(fileId: String): ByteArray =
|
||||
apiClient.downloadContentBytes(fileId)
|
||||
}
|
||||
@@ -6,7 +6,17 @@ import com.kazier.mobile.data.remote.dto.UserDto
|
||||
/** État global de connexion — équivalent de `AuthStatus` JS. */
|
||||
sealed interface AuthState {
|
||||
data object Loading : AuthState
|
||||
data object SignedOut : AuthState
|
||||
|
||||
/**
|
||||
* Déconnecté. `expired` = la session précédente est tombée (401 / token
|
||||
* expiré) plutôt qu'un sign-out volontaire — le login affiche un avis et
|
||||
* pré-remplit `username` quand il est connu.
|
||||
*/
|
||||
data class SignedOut(
|
||||
val expired: Boolean = false,
|
||||
val username: String? = null,
|
||||
) : AuthState
|
||||
|
||||
data object Local : AuthState
|
||||
data class SignedIn(val user: UserDto) : AuthState
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.kazier.mobile.ui.auth
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.kazier.mobile.auth.AuthEvent
|
||||
import com.kazier.mobile.auth.SessionManager
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.repository.AuthRepository
|
||||
@@ -37,19 +38,38 @@ class AuthViewModel @Inject constructor(
|
||||
|
||||
init {
|
||||
// Le 401 est géré par SessionManager (singleton) — jamais ici (M25) :
|
||||
// ce callback survivrait sinon à onCleared et figerait l'outbox.
|
||||
// ce callback survivrait sinon à onCleared et figerait l'outbox. On ne
|
||||
// consomme que ses événements (re-login silencieux / expiration).
|
||||
viewModelScope.launch {
|
||||
sessionManager.events.collect { event ->
|
||||
when (event) {
|
||||
is AuthEvent.Reauthenticated -> enterSignedIn(event.user, reseed = true)
|
||||
is AuthEvent.SessionExpired ->
|
||||
_authState.value = AuthState.SignedOut(expired = true, username = event.username)
|
||||
}
|
||||
}
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val session = sessionManager.restore()
|
||||
_authState.value = when {
|
||||
session != null -> AuthState.SignedIn(session.user)
|
||||
sessionManager.isLocalMode() -> AuthState.Local
|
||||
else -> AuthState.SignedOut
|
||||
session == null && sessionManager.isLocalMode() -> AuthState.Local
|
||||
session == null -> AuthState.SignedOut()
|
||||
sessionManager.isTokenExpired() -> {
|
||||
// Token périmé connu : re-login proactif avant tout 401.
|
||||
// Échec → login avec avis d'expiration (username pré-rempli).
|
||||
if (sessionManager.trySilentRelogin()) {
|
||||
AuthState.SignedIn(session.user)
|
||||
} else {
|
||||
AuthState.SignedOut(expired = true, username = session.user.username)
|
||||
}
|
||||
}
|
||||
else -> AuthState.SignedIn(session.user)
|
||||
}
|
||||
authRepository.registerDevice()
|
||||
// Session restaurée → drainer l'outbox laissée en attente.
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
if (session != null) {
|
||||
if (session != null && _authState.value is AuthState.SignedIn) {
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on restore failed: %s", e.message) }
|
||||
@@ -66,15 +86,9 @@ class AuthViewModel @Inject constructor(
|
||||
_loginUiState.update { LoginUiState(isSubmitting = true) }
|
||||
runCatching { authRepository.login(username, password) }
|
||||
.onSuccess { response ->
|
||||
sessionManager.save(response.token, response.user, response.expiresAt)
|
||||
sessionManager.save(response.token, response.user, response.expiresAt, username.trim(), password)
|
||||
_loginUiState.value = LoginUiState()
|
||||
_authState.value = AuthState.SignedIn(response.user)
|
||||
// Connexion réussie → pousser les mutations locales en attente.
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
|
||||
enterSignedIn(response.user, reseed = true)
|
||||
}
|
||||
.onFailure { e ->
|
||||
val error = when (e) {
|
||||
@@ -86,6 +100,19 @@ class AuthViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Session (re)connectée : état + drain + snapshot permissions. */
|
||||
private fun enterSignedIn(user: com.kazier.mobile.data.remote.dto.UserDto, reseed: Boolean) {
|
||||
_authState.value = AuthState.SignedIn(user)
|
||||
if (reseed) {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
viewModelScope.launch {
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun continueWithoutAccount() {
|
||||
viewModelScope.launch {
|
||||
sessionManager.setLocalMode()
|
||||
@@ -112,7 +139,7 @@ class AuthViewModel @Inject constructor(
|
||||
sessionManager.clear()
|
||||
sessionManager.clearLocalMode()
|
||||
}
|
||||
_authState.value = AuthState.SignedOut
|
||||
_authState.value = AuthState.SignedOut()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,16 +33,22 @@ import com.kazier.mobile.R
|
||||
* Premier écran : choix explicite entre compte serveur et mode local, puis
|
||||
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
|
||||
* (pas un petit lien d'esquive sous le formulaire).
|
||||
*
|
||||
* Après expiration de session (`expired`), le formulaire s'ouvre directement
|
||||
* avec le username pré-rempli et un avis explicite — pas de repassage par
|
||||
* l'écran de choix.
|
||||
*/
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
viewModel: AuthViewModel = hiltViewModel(),
|
||||
expired: Boolean = false,
|
||||
initialUsername: String? = null,
|
||||
) {
|
||||
val loginUi by viewModel.loginUiState.collectAsStateWithLifecycle()
|
||||
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var username by rememberSaveable { mutableStateOf(initialUsername.orEmpty()) }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var showForm by rememberSaveable { mutableStateOf(false) }
|
||||
var showForm by rememberSaveable { mutableStateOf(expired) }
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -94,6 +100,15 @@ fun LoginScreen(
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (expired) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.login_session_expired),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(32.dp))
|
||||
|
||||
LoginForm(
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.kazier.mobile.ui.document
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.repository.RemoteContentRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Chargement streaming d'un fichier cloud-only (V1 finitions).
|
||||
*
|
||||
* Stateless : [load] lit les octets via `GET /files/:id/content` sans les
|
||||
* persister. Le composant appelant garde l'état (idle/loading/loaded/error).
|
||||
*/
|
||||
@HiltViewModel
|
||||
class RemoteContentViewModel @Inject constructor(
|
||||
private val repository: RemoteContentRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
suspend fun load(fileId: String): Result<ByteArray> =
|
||||
runCatching { repository.fetch(fileId) }
|
||||
|
||||
companion object {
|
||||
/** Code quand le serveur n'a aucun octet (metadata-only jamais uploadé). */
|
||||
fun isNoContent(e: Throwable): Boolean =
|
||||
e is ApiException && e.code == "NOT_FOUND"
|
||||
|
||||
fun isTooLarge(e: Throwable): Boolean =
|
||||
e is ApiException && e.code == "FILE_TOO_LARGE"
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -42,7 +42,7 @@ fun DocumentContentViewer(
|
||||
}
|
||||
|
||||
if (file.uri == null) {
|
||||
CloudOnlyPlaceholder(file, modifier)
|
||||
RemoteDocumentViewer(file, onOpenExternalFailed, modifier)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
package com.kazier.mobile.ui.document.content
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import coil.compose.AsyncImage
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.domain.FileCategory
|
||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||
import com.kazier.mobile.ui.components.categoryValue
|
||||
import com.kazier.mobile.ui.document.RemoteContentViewModel
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Lecteur streaming d'un fichier cloud-only (`uri == null`).
|
||||
*
|
||||
* V1 finitions, choix « streaming sans cache » : les octets sont lus via
|
||||
* `GET /files/:id/content` sur demande (bouton, jamais d'auto-load au swipe),
|
||||
* gardés en RAM le temps de l'affichage, jamais persistés (ni Room, ni SAF).
|
||||
* Seul le PDF exige un fichier temporaire du `cacheDir` (le `PdfRenderer`
|
||||
* système ne sait lire que depuis un descripteur) — éphémère, supprimé à la
|
||||
* sortie du viewer. 404 = aucun octet serveur (metadata-only jamais uploadé).
|
||||
*/
|
||||
@Composable
|
||||
fun RemoteDocumentViewer(
|
||||
file: FileEntity,
|
||||
onOpenExternalFailed: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: RemoteContentViewModel = hiltViewModel(),
|
||||
) {
|
||||
var started by remember(file.resourceId) { mutableStateOf(false) }
|
||||
var loading by remember(file.resourceId) { mutableStateOf(false) }
|
||||
var bytes by remember(file.resourceId) { mutableStateOf<ByteArray?>(null) }
|
||||
var error by remember(file.resourceId) { mutableStateOf<Throwable?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun reload() {
|
||||
loading = true
|
||||
error = null
|
||||
scope.launch {
|
||||
viewModel.load(file.resourceId)
|
||||
.onSuccess {
|
||||
bytes = it
|
||||
loading = false
|
||||
}
|
||||
.onFailure {
|
||||
error = it
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val loaded = bytes
|
||||
when {
|
||||
loaded != null -> RemoteContentBody(
|
||||
file = file,
|
||||
bytes = loaded,
|
||||
onOpenExternalFailed = onOpenExternalFailed,
|
||||
modifier = modifier,
|
||||
)
|
||||
loading -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_stream_loading),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
error != null -> RemoteContentError(
|
||||
error = error!!,
|
||||
onRetry = ::reload,
|
||||
modifier = modifier,
|
||||
)
|
||||
!started -> RemoteContentGate(
|
||||
file = file,
|
||||
onLoad = {
|
||||
started = true
|
||||
reload()
|
||||
},
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** État initial : métadonnées + bouton de lecture à la demande (pas d'auto-load). */
|
||||
@Composable
|
||||
private fun RemoteContentGate(
|
||||
file: FileEntity,
|
||||
onLoad: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
FileCategoryIcon(file = file, size = 64.dp)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_cloud_only),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_cloud_only_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Button(onClick = onLoad) {
|
||||
Text(stringResource(R.string.document_stream_load))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Échec de streaming : message + réessai (404 → aucun contenu serveur). */
|
||||
@Composable
|
||||
private fun RemoteContentError(
|
||||
error: Throwable,
|
||||
onRetry: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val message = when {
|
||||
RemoteContentViewModel.isNoContent(error) ->
|
||||
stringResource(R.string.document_stream_no_content)
|
||||
RemoteContentViewModel.isTooLarge(error) ->
|
||||
stringResource(R.string.document_stream_too_large)
|
||||
else -> stringResource(R.string.document_stream_error)
|
||||
}
|
||||
Column(
|
||||
modifier = modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
TextButton(onClick = onRetry) {
|
||||
Text(stringResource(R.string.document_stream_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch du contenu distant par catégorie (PDF / image / texte supportés). */
|
||||
@Composable
|
||||
private fun RemoteContentBody(
|
||||
file: FileEntity,
|
||||
bytes: ByteArray,
|
||||
onOpenExternalFailed: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
when (file.categoryValue()) {
|
||||
FileCategory.IMAGE -> RemoteImageViewer(bytes = bytes, description = file.name, modifier = modifier)
|
||||
FileCategory.TEXT -> RemoteTextViewer(bytes = bytes, modifier = modifier)
|
||||
FileCategory.PDF -> RemotePdfViewer(file = file, bytes = bytes, modifier = modifier)
|
||||
else -> Column(
|
||||
modifier = modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.document_stream_unsupported),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
ExternalOpenButton(file = file, onOpenExternalFailed = onOpenExternalFailed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemoteImageViewer(bytes: ByteArray, description: String, modifier: Modifier = Modifier) {
|
||||
val bitmap = remember(bytes) {
|
||||
runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }.getOrNull()
|
||||
}
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = description,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
} else {
|
||||
// Repli : Coil décode depuis le ByteArray (mêmes bytes, autre décodeur).
|
||||
AsyncImage(
|
||||
model = bytes,
|
||||
contentDescription = description,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Texte distant : décodage UTF-8 borné, même présentation que le viewer local. */
|
||||
@Composable
|
||||
private fun RemoteTextViewer(bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||
val text = remember(bytes) {
|
||||
val capped = bytes.size > REMOTE_TEXT_MAX
|
||||
val length = minOf(bytes.size, REMOTE_TEXT_MAX)
|
||||
String(bytes, 0, length, Charsets.UTF_8).removePrefix("") to capped
|
||||
}
|
||||
Column(modifier.fillMaxSize()) {
|
||||
if (text.second) {
|
||||
Text(
|
||||
text = stringResource(R.string.document_truncated_notice),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
SelectionContainer(Modifier.weight(1f)) {
|
||||
LazyColumn(contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
item {
|
||||
Text(text = text.first, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PDF distant : le `PdfRenderer` système exige un descripteur de fichier —
|
||||
* les octets sont écrits dans un fichier temporaire du `cacheDir`
|
||||
* (`stream-<resourceId>.pdf`), supprimé à la sortie. Première page affichée
|
||||
* (aperçu streaming, pas de navigation complète).
|
||||
*/
|
||||
@Composable
|
||||
private fun RemotePdfViewer(file: FileEntity, bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
var tmpFile by remember(file.resourceId) { mutableStateOf<File?>(null) }
|
||||
var loadFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(file.resourceId, bytes) {
|
||||
loadFailed = false
|
||||
tmpFile = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val tmp = File(context.cacheDir, "stream-${file.resourceId}.pdf")
|
||||
tmp.writeBytes(bytes)
|
||||
tmp
|
||||
}.getOrNull()
|
||||
}
|
||||
if (tmpFile == null) loadFailed = true
|
||||
}
|
||||
DisposableEffect(file.resourceId) {
|
||||
onDispose {
|
||||
val tmp = tmpFile
|
||||
tmpFile = null
|
||||
if (tmp != null) {
|
||||
runCatching {
|
||||
kotlinx.coroutines.runBlocking(Dispatchers.IO) { tmp.delete() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val tmp = tmpFile
|
||||
when {
|
||||
loadFailed || (tmp != null && !tmp.exists()) -> Text(
|
||||
text = stringResource(R.string.document_cannot_read),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = modifier,
|
||||
)
|
||||
tmp == null -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
else -> RemotePdfFirstPage(tmp = tmp, modifier = modifier)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemotePdfFirstPage(tmp: File, modifier: Modifier = Modifier) {
|
||||
var bitmap by remember(tmp.absolutePath) { mutableStateOf<android.graphics.Bitmap?>(null) }
|
||||
var failed by remember(tmp.absolutePath) { mutableStateOf(false) }
|
||||
LaunchedEffect(tmp.absolutePath) {
|
||||
failed = false
|
||||
bitmap = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val pfd = ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
val renderer = PdfRenderer(pfd)
|
||||
try {
|
||||
if (renderer.pageCount <= 0) return@runCatching null
|
||||
val page = renderer.openPage(0)
|
||||
try {
|
||||
val width = (page.width * 2f).toInt().coerceIn(1, 4096)
|
||||
val height = (page.height * 2f).toInt().coerceIn(1, 4096)
|
||||
val bmp = android.graphics.Bitmap.createBitmap(
|
||||
width, height, android.graphics.Bitmap.Config.ARGB_8888,
|
||||
)
|
||||
page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bmp
|
||||
} finally {
|
||||
page.close()
|
||||
}
|
||||
} finally {
|
||||
renderer.close()
|
||||
pfd.close()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
if (bitmap == null) failed = true
|
||||
}
|
||||
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
bitmap != null -> Image(
|
||||
bitmap = bitmap!!.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
failed -> Text(
|
||||
text = stringResource(R.string.document_cannot_read),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
else -> CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val REMOTE_TEXT_MAX = 512 * 1024
|
||||
+7
-6
@@ -328,18 +328,19 @@ fun FolderDetailScreen(
|
||||
}
|
||||
|
||||
if (showShareSheet) {
|
||||
LaunchedEffect(folderResourceId) {
|
||||
shareViewModel.load(folderResourceId, "folder")
|
||||
}
|
||||
ShareBottomSheet(
|
||||
resourceId = folderResourceId,
|
||||
resourceType = "folder",
|
||||
resourceName = uiState.folder?.name ?: stringResource(R.string.folder),
|
||||
viewModel = shareViewModel,
|
||||
state = shareState,
|
||||
onDismiss = {
|
||||
showShareSheet = false
|
||||
shareViewModel.reset()
|
||||
},
|
||||
onShare = { username, access ->
|
||||
shareViewModel.share(folderResourceId, "folder", username, access)
|
||||
},
|
||||
sharing = shareState.sharing,
|
||||
error = shareState.error,
|
||||
enqueued = shareState.enqueued,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -585,18 +585,19 @@ fun FolderListScreen(
|
||||
}
|
||||
|
||||
shareTarget?.let { target ->
|
||||
LaunchedEffect(target.resourceId) {
|
||||
shareViewModel.load(target.resourceId, "folder")
|
||||
}
|
||||
ShareBottomSheet(
|
||||
resourceId = target.resourceId,
|
||||
resourceType = "folder",
|
||||
resourceName = target.name,
|
||||
viewModel = shareViewModel,
|
||||
state = shareState,
|
||||
onDismiss = {
|
||||
shareTarget = null
|
||||
shareViewModel.reset()
|
||||
},
|
||||
onShare = { username, access ->
|
||||
shareViewModel.share(target.resourceId, "folder", username, access)
|
||||
},
|
||||
sharing = shareState.sharing,
|
||||
error = shareState.error,
|
||||
enqueued = shareState.enqueued,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,10 @@ fun KazierApp(
|
||||
|
||||
when (authState) {
|
||||
AuthState.Loading -> SplashScreen()
|
||||
AuthState.SignedOut -> LoginScreen()
|
||||
is AuthState.SignedOut -> {
|
||||
val signedOut = authState as AuthState.SignedOut
|
||||
LoginScreen(expired = signedOut.expired, initialUsername = signedOut.username)
|
||||
}
|
||||
AuthState.Local -> NavGraph(
|
||||
authViewModel = authViewModel,
|
||||
syncViewModel = syncViewModel,
|
||||
|
||||
@@ -15,6 +15,7 @@ import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.navArgument
|
||||
import androidx.navigation.navDeepLink
|
||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||
@@ -27,6 +28,7 @@ import com.kazier.mobile.ui.review.SwipeReviewScreen
|
||||
import com.kazier.mobile.ui.scan.ScanFlowScreen
|
||||
import com.kazier.mobile.ui.search.SearchScreen
|
||||
import com.kazier.mobile.ui.settings.SettingsScreen
|
||||
import com.kazier.mobile.ui.share.OpenLinkScreen
|
||||
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersScreen
|
||||
|
||||
object Routes {
|
||||
@@ -43,6 +45,10 @@ object Routes {
|
||||
const val PDF_BUILDER = "pdfbuilder/{ids}"
|
||||
const val ARG_BUILDER_IDS = "ids"
|
||||
const val SCAN = "scan"
|
||||
const val OPEN_LINK = "openlink/{token}"
|
||||
const val ARG_LINK_TOKEN = "token"
|
||||
|
||||
fun openLink(token: String): String = "openlink/$token"
|
||||
|
||||
fun folder(folderResourceId: String): String = "folder/$folderResourceId"
|
||||
fun document(documentResourceId: String): String = "document/$documentResourceId"
|
||||
@@ -233,6 +239,23 @@ fun NavGraph(
|
||||
},
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = Routes.OPEN_LINK,
|
||||
arguments = listOf(
|
||||
navArgument(Routes.ARG_LINK_TOKEN) { type = NavType.StringType },
|
||||
),
|
||||
deepLinks = listOf(
|
||||
navDeepLink { uriPattern = "kazier://share/{token}" },
|
||||
),
|
||||
) { backStackEntry ->
|
||||
val token = checkNotNull(
|
||||
backStackEntry.arguments?.getString(Routes.ARG_LINK_TOKEN),
|
||||
)
|
||||
OpenLinkScreen(
|
||||
token = token,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.kazier.mobile.ui.share
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
|
||||
/**
|
||||
* Ouverture d'un lien de partage reçu (deep-link `kazier://share/<token>`).
|
||||
*
|
||||
* Résolution publique (`GET /shares/links/:token`, sans auth) : affiche les
|
||||
* métadonnées du lien. Un lien seul ne crée aucun grant — le contenu
|
||||
* n'apparaît dans l'app que via un partage direct du propriétaire (snapshot
|
||||
* `GET /sync/permissions`), d'où le hint explicite.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun OpenLinkScreen(
|
||||
token: String,
|
||||
onBack: () -> Unit,
|
||||
viewModel: ShareViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(token) {
|
||||
viewModel.reset()
|
||||
viewModel.resolveLink(token)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.share_section_open_link)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
when {
|
||||
state.resolving -> {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_stream_loading),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
state.resolvedLink != null -> {
|
||||
val link = state.resolvedLink!!
|
||||
Text(
|
||||
text = link.name,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "${link.resourceType} · ${link.access}",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.share_resolved_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
else -> {
|
||||
Text(
|
||||
text = stringResource(
|
||||
when (state.resolveError) {
|
||||
"LINK_INVALID" -> R.string.share_error_link_invalid
|
||||
"LINK_NOT_FOUND" -> R.string.share_error_link_not_found
|
||||
else -> R.string.share_error_link_failed
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,40 @@
|
||||
package com.kazier.mobile.ui.share
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -33,7 +44,10 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -52,24 +66,29 @@ private val ACCESS_OPTIONS = listOf(
|
||||
AccessOption(R.string.share_access_editor, ShareAccessLevel.EDITOR),
|
||||
)
|
||||
|
||||
/**
|
||||
* Gestion du partage d'une ressource possédée : grants actifs (accès
|
||||
* modifiable, révocation), ajout par username, liens publics (création,
|
||||
* copie, révocation) et ouverture d'un lien reçu. Les mutations sont
|
||||
* enqueued dans l'outbox ([ShareViewModel]) — le badge « en attente »
|
||||
* couvre le délai avant le drain.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ShareBottomSheet(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
resourceName: String,
|
||||
viewModel: ShareViewModel,
|
||||
state: ShareUiState,
|
||||
onDismiss: () -> Unit,
|
||||
onShare: (username: String, access: String) -> Unit,
|
||||
sharing: Boolean,
|
||||
error: String?,
|
||||
enqueued: Boolean,
|
||||
) {
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||
// Confirmation visible avant fermeture : fini l'auto-dismiss silencieux.
|
||||
var justShared by rememberSaveable { mutableStateOf(false) }
|
||||
val sheetState = rememberModalBottomSheetState()
|
||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
|
||||
LaunchedEffect(enqueued) {
|
||||
if (enqueued && !justShared) {
|
||||
LaunchedEffect(state.enqueued) {
|
||||
if (state.enqueued && !justShared) {
|
||||
justShared = true
|
||||
delay(1_200)
|
||||
onDismiss()
|
||||
@@ -83,6 +102,7 @@ fun ShareBottomSheet(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp)
|
||||
.padding(bottom = 24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
@@ -99,6 +119,229 @@ fun ShareBottomSheet(
|
||||
maxLines = 1,
|
||||
)
|
||||
|
||||
if (state.pendingCount > 0) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_pending, state.pendingCount),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
|
||||
when {
|
||||
state.loading -> Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(28.dp))
|
||||
}
|
||||
state.loadError != null -> LoadErrorRow(
|
||||
code = state.loadError,
|
||||
onRetry = { viewModel.refresh() },
|
||||
)
|
||||
else -> {
|
||||
GrantsSection(
|
||||
grants = state.shares,
|
||||
onChangeAccess = { grant, access ->
|
||||
viewModel.changeAccess(resourceId, resourceType, grant, access)
|
||||
},
|
||||
onRevoke = { grant -> viewModel.revoke(resourceId, resourceType, grant) },
|
||||
)
|
||||
AddShareSection(
|
||||
sharing = state.sharing,
|
||||
error = state.error,
|
||||
enqueued = state.enqueued,
|
||||
justShared = justShared,
|
||||
onShare = { username, access ->
|
||||
viewModel.share(resourceId, resourceType, username, access)
|
||||
},
|
||||
)
|
||||
LinksSection(
|
||||
links = state.links,
|
||||
lastCreated = state.lastCreatedLink,
|
||||
onCreate = { access -> viewModel.createLink(resourceId, resourceType, access) },
|
||||
onRevoke = { link -> viewModel.revokeLink(resourceId, resourceType, link) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
state.actionError?.let {
|
||||
Text(
|
||||
text = stringResource(R.string.share_error_generic),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
OpenLinkSection(
|
||||
resolving = state.resolving,
|
||||
resolved = state.resolvedLink,
|
||||
resolveError = state.resolveError,
|
||||
onResolve = { viewModel.resolveLink(it) },
|
||||
onClear = { viewModel.clearResolved() },
|
||||
)
|
||||
|
||||
OutlinedButton(
|
||||
onClick = onDismiss,
|
||||
enabled = !state.sharing,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.share_cancel))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadErrorRow(code: String, onRetry: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (code == "FORBIDDEN") R.string.share_error_forbidden else R.string.share_error_load,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
TextButton(onClick = onRetry) {
|
||||
Text(stringResource(R.string.share_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionTitle(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GrantsSection(
|
||||
grants: List<ShareGrantUi>,
|
||||
onChangeAccess: (ShareGrantUi, String) -> Unit,
|
||||
onRevoke: (ShareGrantUi) -> Unit,
|
||||
) {
|
||||
var pendingRevoke by rememberSaveable { mutableStateOf<ShareGrantUi?>(null) }
|
||||
|
||||
SectionTitle(stringResource(R.string.share_section_grants))
|
||||
if (grants.isEmpty()) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_empty_grants),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
grants.forEach { grant ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = grant.username,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
)
|
||||
if (grant.expired) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_expired),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
GrantAccessPicker(
|
||||
selected = grant.access,
|
||||
onSelect = { onChangeAccess(grant, it) },
|
||||
)
|
||||
IconButton(onClick = { pendingRevoke = grant }) {
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
contentDescription = stringResource(R.string.share_revoke),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pendingRevoke?.let { grant ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingRevoke = null },
|
||||
text = { Text(stringResource(R.string.share_revoke_confirm, grant.username)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
onRevoke(grant)
|
||||
pendingRevoke = null
|
||||
}) {
|
||||
Text(stringResource(R.string.share_confirm))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingRevoke = null }) {
|
||||
Text(stringResource(R.string.share_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Sélecteur d'accès compact pour une ligne de grant existant. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun GrantAccessPicker(selected: String, onSelect: (String) -> Unit) {
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
val label = ACCESS_OPTIONS.firstOrNull { it.value == selected }?.labelRes
|
||||
?: ACCESS_OPTIONS.first().labelRes
|
||||
ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
|
||||
OutlinedTextField(
|
||||
value = stringResource(label),
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
singleLine = true,
|
||||
textStyle = MaterialTheme.typography.labelLarge,
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||
modifier = Modifier
|
||||
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||
.width(150.dp),
|
||||
)
|
||||
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||
ACCESS_OPTIONS.forEach { option ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(option.labelRes)) },
|
||||
onClick = {
|
||||
onSelect(option.value)
|
||||
expanded = false
|
||||
},
|
||||
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddShareSection(
|
||||
sharing: Boolean,
|
||||
error: String?,
|
||||
enqueued: Boolean,
|
||||
justShared: Boolean,
|
||||
onShare: (username: String, access: String) -> Unit,
|
||||
) {
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||
|
||||
SectionTitle(stringResource(R.string.share_section_add))
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
@@ -107,12 +350,6 @@ fun ShareBottomSheet(
|
||||
enabled = !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.share_access_label),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
AccessDropdown(
|
||||
selected = access,
|
||||
onSelect = { access = it },
|
||||
@@ -130,7 +367,7 @@ fun ShareBottomSheet(
|
||||
)
|
||||
}
|
||||
|
||||
if (justShared) {
|
||||
if (justShared && enqueued) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
@@ -156,25 +393,218 @@ fun ShareBottomSheet(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (sharing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Icon(Icons.Filled.Share, contentDescription = null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.share_submit))
|
||||
}
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onDismiss,
|
||||
enabled = !sharing && !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LinksSection(
|
||||
links: List<ShareLinkUi>,
|
||||
lastCreated: ShareLinkUi?,
|
||||
onCreate: (String) -> Unit,
|
||||
onRevoke: (ShareLinkUi) -> Unit,
|
||||
) {
|
||||
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||
var pendingRevoke by rememberSaveable { mutableStateOf<ShareLinkUi?>(null) }
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val context = LocalContext.current
|
||||
|
||||
SectionTitle(stringResource(R.string.share_section_links))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
AccessDropdown(
|
||||
selected = access,
|
||||
onSelect = { access = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Button(onClick = { onCreate(access) }) {
|
||||
Icon(Icons.Filled.Link, contentDescription = null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.share_link_create))
|
||||
}
|
||||
}
|
||||
|
||||
lastCreated?.let { link ->
|
||||
// Le token n'existe que côté client jusqu'au drain : la carte reste
|
||||
// affichée pour copie avant fermeture.
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_link_created),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = link.url,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 2,
|
||||
)
|
||||
OutlinedButton(onClick = {
|
||||
clipboard.setText(AnnotatedString(link.url))
|
||||
Toast.makeText(context, context.getString(R.string.share_link_copied), Toast.LENGTH_SHORT).show()
|
||||
}) {
|
||||
Icon(Icons.Filled.ContentCopy, contentDescription = null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.share_link_copy))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (links.isEmpty()) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_empty_links),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = link.url,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
)
|
||||
Text(
|
||||
text = accessLabel(link.access),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
clipboard.setText(AnnotatedString(link.url))
|
||||
Toast.makeText(context, context.getString(R.string.share_link_copied), Toast.LENGTH_SHORT).show()
|
||||
}) {
|
||||
Icon(
|
||||
Icons.Filled.ContentCopy,
|
||||
contentDescription = stringResource(R.string.share_link_copy),
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { pendingRevoke = link }) {
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
contentDescription = stringResource(R.string.share_revoke),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pendingRevoke?.let { link ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingRevoke = null },
|
||||
text = { Text(stringResource(R.string.share_link_revoke_confirm)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
onRevoke(link)
|
||||
pendingRevoke = null
|
||||
}) {
|
||||
Text(stringResource(R.string.share_confirm))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingRevoke = null }) {
|
||||
Text(stringResource(R.string.share_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun accessLabel(access: String): String = stringResource(
|
||||
when (access) {
|
||||
ShareAccessLevel.COMMENTER -> R.string.share_access_commenter
|
||||
ShareAccessLevel.EDITOR -> R.string.share_access_editor
|
||||
else -> R.string.share_access_viewer
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun OpenLinkSection(
|
||||
resolving: Boolean,
|
||||
resolved: ResolvedLinkUi?,
|
||||
resolveError: String?,
|
||||
onResolve: (String) -> Unit,
|
||||
onClear: () -> Unit,
|
||||
) {
|
||||
var input by rememberSaveable { mutableStateOf("") }
|
||||
|
||||
SectionTitle(stringResource(R.string.share_section_open_link))
|
||||
OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = {
|
||||
input = it
|
||||
if (resolved != null || resolveError != null) onClear()
|
||||
},
|
||||
label = { Text(stringResource(R.string.share_open_link_hint)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = { onResolve(input) },
|
||||
enabled = input.isNotBlank() && !resolving,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (resolving) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Text(stringResource(R.string.share_open_link_button))
|
||||
}
|
||||
}
|
||||
|
||||
resolveError?.let { code ->
|
||||
Text(
|
||||
text = stringResource(
|
||||
when (code) {
|
||||
"LINK_INVALID" -> R.string.share_error_link_invalid
|
||||
"LINK_NOT_FOUND" -> R.string.share_error_link_not_found
|
||||
else -> R.string.share_error_link_failed
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
resolved?.let { link ->
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
text = link.name,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
Text(
|
||||
text = "${link.resourceType} · ${link.access}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.share_resolved_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.kazier.mobile.ui.share
|
||||
|
||||
/**
|
||||
* Extraction d'un token de lien de partage depuis une saisie utilisateur.
|
||||
*
|
||||
* Formats acceptés : 32-hex brut, URL deep-link `kazier://share/<token>`,
|
||||
* ou URL API `…/shares/links/<token>`. Retourne le token normalisé
|
||||
* (lowercase) ou null si rien d'exploitable.
|
||||
*/
|
||||
object ShareLinkParser {
|
||||
private val HEX32 = Regex("^[0-9a-f]{32}$")
|
||||
private val HEX32_LOOSE = Regex("^[0-9a-fA-F]{32}$")
|
||||
private val IN_URL = Regex("(?:shares/links|/share)[:/]([0-9a-fA-F]{32})(?![0-9a-fA-F])")
|
||||
|
||||
fun extractToken(input: String): String? {
|
||||
val trimmed = input.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
val lowered = trimmed.lowercase()
|
||||
if (HEX32.matches(lowered)) return lowered
|
||||
if (HEX32_LOOSE.matches(trimmed)) return lowered
|
||||
return IN_URL.find(trimmed)?.groupValues?.get(1)?.lowercase()
|
||||
}
|
||||
|
||||
/** Texte à copier/partager pour un lien : deep-link ouvrable par l'app. */
|
||||
fun shareUrl(token: String): String = "kazier://share/$token"
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import androidx.lifecycle.viewModelScope
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.repository.OutboxRepository
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.features.sync.OutboxSyncWorker
|
||||
import com.kazier.mobile.features.ocr.OcrAutoWorker
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -18,14 +18,6 @@ import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
data class ShareUiState(
|
||||
val sharing: Boolean = false,
|
||||
/** Code d'erreur contractuel (`USER_NOT_FOUND`, `SHARE_FAILED`) ou null. */
|
||||
val error: String? = null,
|
||||
/** L'op `share` a été enqueued avec succès (prête pour le drain). */
|
||||
val enqueued: Boolean = false,
|
||||
)
|
||||
|
||||
/** Accès partage — valeur du payload `access` (docs/api-v1.md §6.1). */
|
||||
object ShareAccessLevel {
|
||||
const val VIEWER = "viewer"
|
||||
@@ -33,27 +25,145 @@ object ShareAccessLevel {
|
||||
const val EDITOR = "editor"
|
||||
}
|
||||
|
||||
/** Grant actif affiché dans le sheet (miroir `ShareGrantDto`). */
|
||||
data class ShareGrantUi(
|
||||
val granteeUserId: String,
|
||||
val username: String,
|
||||
val access: String,
|
||||
val inherit: Boolean,
|
||||
val expiresAt: Long?,
|
||||
val expired: Boolean,
|
||||
)
|
||||
|
||||
/** Lien public actif affiché dans le sheet (miroir `ShareLinkDto`). */
|
||||
data class ShareLinkUi(
|
||||
val token: String,
|
||||
val access: String,
|
||||
val expiresAt: String?,
|
||||
/** Texte à copier : deep-link `kazier://share/<token>`. */
|
||||
val url: String,
|
||||
)
|
||||
|
||||
/** Lien résolu via `GET /shares/links/:token` (ouverture d'un lien reçu). */
|
||||
data class ResolvedLinkUi(
|
||||
val token: String,
|
||||
val resourceId: String,
|
||||
val resourceType: String,
|
||||
val name: String,
|
||||
val access: String,
|
||||
)
|
||||
|
||||
data class ShareUiState(
|
||||
val loading: Boolean = false,
|
||||
/** Cible courante du sheet (resource partagée). */
|
||||
val resourceId: String? = null,
|
||||
val resourceType: String? = null,
|
||||
val shares: List<ShareGrantUi> = emptyList(),
|
||||
val links: List<ShareLinkUi> = emptyList(),
|
||||
/** Ops de partage en attente d'envoi (pas encore reflétées serveur). */
|
||||
val pendingCount: Int = 0,
|
||||
/** Erreur de chargement des listes (`LOAD_FAILED`, `FORBIDDEN`). */
|
||||
val loadError: String? = null,
|
||||
/** Ajout d'un partage en cours. */
|
||||
val sharing: Boolean = false,
|
||||
/** Code d'erreur du formulaire d'ajout (`USER_NOT_FOUND`, `SHARE_FAILED`). */
|
||||
val error: String? = null,
|
||||
/** Succès transitoire d'ajout (affiché puis effacé). */
|
||||
val enqueued: Boolean = false,
|
||||
/** Erreur transitoire d'une action ligne (update/revoke/link). */
|
||||
val actionError: String? = null,
|
||||
/** Dernier lien créé — à copier (consommé puis effacé). */
|
||||
val lastCreatedLink: ShareLinkUi? = null,
|
||||
/** Résolution d'un lien reçu en cours. */
|
||||
val resolving: Boolean = false,
|
||||
val resolvedLink: ResolvedLinkUi? = null,
|
||||
/** Erreur de résolution (`LINK_INVALID`, `LINK_NOT_FOUND`). */
|
||||
val resolveError: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Partage d'une ressource locale avec un autre utilisateur : résout le
|
||||
* destinataire par username (exact), puis enqueue l'op `share` dans l'outbox
|
||||
* (drainée par [OutboxSyncWorker]).
|
||||
* Gestion complète du partage d'une ressource possédée :
|
||||
*
|
||||
* - listes serveur (`GET /files/:id/shares`, `GET /files/:id/links`,
|
||||
* owner uniquement) + compteur d'ops en attente (outbox locale) ;
|
||||
* - ajout (`share`), changement d'accès (`update_share`), révocation
|
||||
* (`revoke_share`) — enqueued dans l'outbox, drainés par
|
||||
* [OutboxSyncWorker] ;
|
||||
* - liens publics (`create_link` avec token [GenerateId], `revoke_link`) +
|
||||
* copie du deep-link `kazier://share/<token>` ;
|
||||
* - ouverture d'un lien reçu (collé ou deep-link) via `getShareLink`.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class ShareViewModel @Inject constructor(
|
||||
private val apiClient: ApiClient,
|
||||
private val outboxRepository: OutboxRepository,
|
||||
private val generateId: GenerateId,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(ShareUiState())
|
||||
val uiState: StateFlow<ShareUiState> = _uiState.asStateFlow()
|
||||
|
||||
/**
|
||||
* Charge les listes d'une ressource (appelé à l'ouverture du sheet).
|
||||
* 404 serveur → la ressource n'est pas possédée (`FORBIDDEN`) : le sheet
|
||||
* n'affiche que l'erreur, sans listes.
|
||||
*/
|
||||
fun load(resourceId: String, resourceType: String) {
|
||||
val current = _uiState.value
|
||||
if (current.resourceId == resourceId && current.loading) return
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
loading = true, loadError = null, resourceId = resourceId,
|
||||
resourceType = resourceType, actionError = null,
|
||||
)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
val shares = apiClient.listShares(resourceId)
|
||||
val links = apiClient.listLinks(resourceId)
|
||||
val pending = outboxRepository.pendingShareOps(resourceId).size
|
||||
Triple(shares, links, pending)
|
||||
}.onSuccess { (shares, links, pending) ->
|
||||
val now = System.currentTimeMillis()
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
shares = shares.map { dto ->
|
||||
ShareGrantUi(
|
||||
granteeUserId = dto.granteeUserId,
|
||||
username = dto.username,
|
||||
access = dto.access,
|
||||
inherit = dto.inherit,
|
||||
expiresAt = dto.expiresAt,
|
||||
expired = dto.expiresAt != null && dto.expiresAt <= now,
|
||||
)
|
||||
},
|
||||
links = links.map { dto ->
|
||||
ShareLinkUi(
|
||||
token = dto.token,
|
||||
access = dto.access,
|
||||
expiresAt = dto.expiresAt,
|
||||
url = ShareLinkParser.shareUrl(dto.token),
|
||||
)
|
||||
},
|
||||
pendingCount = pending,
|
||||
)
|
||||
}
|
||||
}.onFailure { e ->
|
||||
val code = if (e is ApiException && e.code == "NOT_FOUND") "FORBIDDEN" else "LOAD_FAILED"
|
||||
Timber.w(e, "share: load failed for %s", resourceId)
|
||||
_uiState.update { it.copy(loading = false, loadError = code) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Partage [resourceId] avec l'utilisateur [username] au niveau [access].
|
||||
*
|
||||
* 1. `GET /users/resolve` (username exact) → user id ;
|
||||
* 2. enqueue `share` dans l'outbox ;
|
||||
* 3. déclenche le drain du worker.
|
||||
* 3. déclenche le drain du worker + recharge le compteur pending.
|
||||
*/
|
||||
fun share(resourceId: String, resourceType: String, username: String, access: String) {
|
||||
if (_uiState.value.sharing) return
|
||||
@@ -69,9 +179,9 @@ class ShareViewModel @Inject constructor(
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
Timber.d("share: op enqueued for %s", resourceId)
|
||||
_uiState.update { it.copy(sharing = false, enqueued = true) }
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
val error = when {
|
||||
e is ApiException && e.code == "NOT_FOUND" -> "USER_NOT_FOUND"
|
||||
@@ -83,11 +193,173 @@ class ShareViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Consomme l'état clone (succès/erreur affiché) avant de rouvrir le sheet. */
|
||||
/** Change l'accès d'un grant existant (`update_share`, upsert serveur). */
|
||||
fun changeAccess(resourceId: String, resourceType: String, grant: ShareGrantUi, access: String) {
|
||||
if (grant.access == access) return
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(actionError = null) }
|
||||
runCatching {
|
||||
outboxRepository.enqueueUpdateShare(
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
granteeUserId = grant.granteeUserId,
|
||||
access = access,
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
_uiState.update { state ->
|
||||
state.copy(
|
||||
shares = state.shares.map {
|
||||
if (it.granteeUserId == grant.granteeUserId) it.copy(access = access) else it
|
||||
},
|
||||
)
|
||||
}
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "share: update failed")
|
||||
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Révoque un grant (`revoke_share`, idempotent serveur). */
|
||||
fun revoke(resourceId: String, resourceType: String, grant: ShareGrantUi) {
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(actionError = null) }
|
||||
runCatching {
|
||||
outboxRepository.enqueueRevokeShare(
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
granteeUserId = grant.granteeUserId,
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
_uiState.update { state ->
|
||||
state.copy(shares = state.shares.filter { it.granteeUserId != grant.granteeUserId })
|
||||
}
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "share: revoke failed")
|
||||
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée un lien public (`create_link`, token 32-hex généré localement).
|
||||
* Le lien est exposé en [ShareUiState.lastCreatedLink] pour copie.
|
||||
*/
|
||||
fun createLink(resourceId: String, resourceType: String, access: String) {
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(actionError = null, lastCreatedLink = null) }
|
||||
val token = generateId.newResourceId()
|
||||
runCatching {
|
||||
outboxRepository.enqueueCreateLink(
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
token = token,
|
||||
access = access,
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
_uiState.update {
|
||||
it.copy(lastCreatedLink = ShareLinkUi(token, access, null, ShareLinkParser.shareUrl(token)))
|
||||
}
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "share: create link failed")
|
||||
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Révoque un lien public (`revoke_link`, idempotent serveur). */
|
||||
fun revokeLink(resourceId: String, resourceType: String, link: ShareLinkUi) {
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(actionError = null) }
|
||||
runCatching {
|
||||
outboxRepository.enqueueRevokeLink(
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
token = link.token,
|
||||
)
|
||||
}.onSuccess {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
_uiState.update { state ->
|
||||
state.copy(links = state.links.filter { it.token != link.token })
|
||||
}
|
||||
refreshPending(resourceId)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "share: revoke link failed")
|
||||
_uiState.update { it.copy(actionError = "SHARE_FAILED") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout un lien reçu (token brut, deep-link `kazier://share/…` ou URL
|
||||
* `…/shares/links/…` collé) via la route publique `getShareLink`.
|
||||
*/
|
||||
fun resolveLink(input: String) {
|
||||
val token = ShareLinkParser.extractToken(input)
|
||||
if (token == null) {
|
||||
_uiState.update { it.copy(resolvedLink = null, resolveError = "LINK_INVALID") }
|
||||
return
|
||||
}
|
||||
if (_uiState.value.resolving) return
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(resolving = true, resolvedLink = null, resolveError = null) }
|
||||
runCatching { apiClient.getShareLink(token) }
|
||||
.onSuccess { dto ->
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
resolving = false,
|
||||
resolvedLink = ResolvedLinkUi(
|
||||
token = dto.token,
|
||||
resourceId = dto.resourceId,
|
||||
resourceType = dto.resourceType,
|
||||
name = dto.name,
|
||||
access = dto.access,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
.onFailure { e ->
|
||||
val code = if (e is ApiException && e.code == "NOT_FOUND") "LINK_NOT_FOUND" else "LINK_FAILED"
|
||||
Timber.w(e, "share: resolve link failed")
|
||||
_uiState.update { it.copy(resolving = false, resolveError = code) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Recharge les listes serveur (bouton réessayer / après drain). */
|
||||
fun refresh() {
|
||||
val state = _uiState.value
|
||||
val id = state.resourceId ?: return
|
||||
val type = state.resourceType ?: return
|
||||
load(id, type)
|
||||
}
|
||||
|
||||
private suspend fun refreshPending(resourceId: String) {
|
||||
val pending = runCatching { outboxRepository.pendingShareOps(resourceId).size }.getOrDefault(0)
|
||||
_uiState.update { it.copy(pendingCount = pending) }
|
||||
}
|
||||
|
||||
/** Consomme l'état transitoire avant de rouvrir le sheet. */
|
||||
fun reset() {
|
||||
_uiState.value = ShareUiState()
|
||||
}
|
||||
|
||||
/** Consomme le lien à copier après affichage. */
|
||||
fun clearLastCreatedLink() {
|
||||
_uiState.update { it.copy(lastCreatedLink = null) }
|
||||
}
|
||||
|
||||
/** Consomme le lien résolu après affichage. */
|
||||
fun clearResolved() {
|
||||
_uiState.update { it.copy(resolvedLink = null, resolveError = null) }
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
}
|
||||
|
||||
@@ -84,6 +84,13 @@
|
||||
<string name="document_truncated_notice">Preview truncated — the full file is not displayed.</string>
|
||||
<string name="document_loading">Reading document…</string>
|
||||
<string name="document_cannot_read">Could not read this document.</string>
|
||||
<string name="document_stream_load">Stream</string>
|
||||
<string name="document_stream_loading">Loading from the server…</string>
|
||||
<string name="document_stream_retry">Retry</string>
|
||||
<string name="document_stream_error">Streaming failed. Check your connection and retry.</string>
|
||||
<string name="document_stream_no_content">No server content for this file.</string>
|
||||
<string name="document_stream_too_large">File too large for streaming (max 12 MB).</string>
|
||||
<string name="document_stream_unsupported">Streaming preview not supported for this file type.</string>
|
||||
<string name="document_page_unreadable">Unreadable page</string>
|
||||
<string name="focus_tap_to_exit">Tap to exit</string>
|
||||
<string name="login_show_password">Show password</string>
|
||||
@@ -170,6 +177,7 @@
|
||||
<string name="login_error_required">Username and password are required</string>
|
||||
<string name="login_error_generic">Could not sign in right now</string>
|
||||
<string name="login_error_unauthorized">Incorrect username or password</string>
|
||||
<string name="login_session_expired">Session expired — sign in again to continue.</string>
|
||||
<string name="login_skip">Continue without account</string>
|
||||
<string name="login_choice_subtitle">Choose how to use Kazier</string>
|
||||
<string name="skip_message">Local mode — your folders stay on this device and are not synced.</string>
|
||||
@@ -309,6 +317,31 @@
|
||||
<string name="share_error_not_found">No user found with this username.</string>
|
||||
<string name="share_error_generic">Could not share right now.</string>
|
||||
<string name="share_enqueued">Share saved — syncing.</string>
|
||||
<string name="share_pending">%1$d change(s) pending upload.</string>
|
||||
<string name="share_section_grants">People with access</string>
|
||||
<string name="share_section_add">Add access</string>
|
||||
<string name="share_section_links">Public links</string>
|
||||
<string name="share_section_open_link">Open a received link</string>
|
||||
<string name="share_empty_grants">Nobody yet — add access below.</string>
|
||||
<string name="share_empty_links">No links — create one to share without a recipient account.</string>
|
||||
<string name="share_expired">expired</string>
|
||||
<string name="share_revoke">Revoke</string>
|
||||
<string name="share_revoke_confirm">Revoke access for %1$s?</string>
|
||||
<string name="share_link_create">Create link</string>
|
||||
<string name="share_link_created">Link created — copy it before closing.</string>
|
||||
<string name="share_link_copy">Copy</string>
|
||||
<string name="share_link_copied">Link copied.</string>
|
||||
<string name="share_link_revoke_confirm">Revoke this link? It will stop working.</string>
|
||||
<string name="share_open_link_hint">Paste a received link or token</string>
|
||||
<string name="share_open_link_button">Open</string>
|
||||
<string name="share_resolved_hint">Valid link — ask the owner for a direct share to see the content in the app.</string>
|
||||
<string name="share_error_link_invalid">Unreadable link — paste the full link or token.</string>
|
||||
<string name="share_error_link_not_found">Unknown, revoked or expired link.</string>
|
||||
<string name="share_error_link_failed">Could not open this link right now.</string>
|
||||
<string name="share_error_load">Could not load shares.</string>
|
||||
<string name="share_error_forbidden">You do not own this resource.</string>
|
||||
<string name="share_retry">Retry</string>
|
||||
<string name="share_confirm">Confirm</string>
|
||||
<string name="share_content_description">Share this folder</string>
|
||||
<string name="share_action">Share</string>
|
||||
<string name="more_actions">More actions</string>
|
||||
|
||||
@@ -84,6 +84,13 @@
|
||||
<string name="document_truncated_notice">Aperçu tronqué — le fichier complet n\'est pas affiché.</string>
|
||||
<string name="document_loading">Lecture du document…</string>
|
||||
<string name="document_cannot_read">Impossible de lire ce document.</string>
|
||||
<string name="document_stream_load">Lire en streaming</string>
|
||||
<string name="document_stream_loading">Chargement depuis le serveur…</string>
|
||||
<string name="document_stream_retry">Réessayer</string>
|
||||
<string name="document_stream_error">Échec du streaming. Vérifie ta connexion puis réessaie.</string>
|
||||
<string name="document_stream_no_content">Aucun contenu sur le serveur pour ce fichier.</string>
|
||||
<string name="document_stream_too_large">Fichier trop volumineux pour le streaming (max 12 Mo).</string>
|
||||
<string name="document_stream_unsupported">Aperçu en streaming non supporté pour ce type de fichier.</string>
|
||||
<string name="document_page_unreadable">Page illisible</string>
|
||||
<string name="focus_tap_to_exit">Toucher pour quitter</string>
|
||||
<string name="login_show_password">Afficher le mot de passe</string>
|
||||
@@ -170,6 +177,7 @@
|
||||
<string name="login_error_required">Nom d\'utilisateur et mot de passe requis</string>
|
||||
<string name="login_error_generic">Impossible de se connecter pour le moment</string>
|
||||
<string name="login_error_unauthorized">Nom d\'utilisateur ou mot de passe incorrect</string>
|
||||
<string name="login_session_expired">Session expirée — reconnecte-toi pour continuer.</string>
|
||||
<string name="login_skip">Continuer sans compte</string>
|
||||
<string name="login_choice_subtitle">Choisis comment utiliser Kazier</string>
|
||||
<string name="skip_message">Mode local — tes dossiers restent sur cet appareil et ne sont pas synchronisés.</string>
|
||||
@@ -309,6 +317,31 @@
|
||||
<string name="share_error_not_found">Aucun utilisateur connu sous ce nom.</string>
|
||||
<string name="share_error_generic">Impossible de partager pour le moment.</string>
|
||||
<string name="share_enqueued">Partage enregistré — synchronisation en cours.</string>
|
||||
<string name="share_pending">%1$d modification(s) en attente d\'envoi.</string>
|
||||
<string name="share_section_grants">Personnes avec accès</string>
|
||||
<string name="share_section_add">Ajouter un accès</string>
|
||||
<string name="share_section_links">Liens publics</string>
|
||||
<string name="share_section_open_link">Ouvrir un lien reçu</string>
|
||||
<string name="share_empty_grants">Personne pour l\'instant — ajoutez un accès ci-dessous.</string>
|
||||
<string name="share_empty_links">Aucun lien — créez-en un pour partager sans compte destinataire.</string>
|
||||
<string name="share_expired">expiré</string>
|
||||
<string name="share_revoke">Révoquer</string>
|
||||
<string name="share_revoke_confirm">Révoquer l\'accès de %1$s ?</string>
|
||||
<string name="share_link_create">Créer un lien</string>
|
||||
<string name="share_link_created">Lien créé — copiez-le avant de fermer.</string>
|
||||
<string name="share_link_copy">Copier</string>
|
||||
<string name="share_link_copied">Lien copié.</string>
|
||||
<string name="share_link_revoke_confirm">Révoquer ce lien ? Il ne fonctionnera plus.</string>
|
||||
<string name="share_open_link_hint">Collez un lien ou un token reçu</string>
|
||||
<string name="share_open_link_button">Ouvrir</string>
|
||||
<string name="share_resolved_hint">Lien valide — demandez au propriétaire un partage direct pour voir le contenu dans l\'app.</string>
|
||||
<string name="share_error_link_invalid">Lien illisible — collez le lien complet ou le token.</string>
|
||||
<string name="share_error_link_not_found">Lien inconnu, révoqué ou expiré.</string>
|
||||
<string name="share_error_link_failed">Impossible d\'ouvrir ce lien pour le moment.</string>
|
||||
<string name="share_error_load">Impossible de charger les partages.</string>
|
||||
<string name="share_error_forbidden">Vous ne possédez pas cette ressource.</string>
|
||||
<string name="share_retry">Réessayer</string>
|
||||
<string name="share_confirm">Confirmer</string>
|
||||
<string name="share_content_description">Partager ce dossier</string>
|
||||
<string name="share_action">Partager</string>
|
||||
<string name="more_actions">Plus d\'actions</string>
|
||||
|
||||
@@ -25,10 +25,14 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import com.kazier.mobile.data.remote.dto.UserDto
|
||||
import com.kazier.mobile.data.repository.AuthRepository
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.domain.LocalModeStore
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.runBlocking
|
||||
@@ -36,6 +40,7 @@ import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -82,6 +87,7 @@ class Auth401Test {
|
||||
LocalModeStore(db.userPreferenceDao()),
|
||||
db.pendingOperationDao(),
|
||||
apiClient,
|
||||
AuthRepository(apiClient, DeviceIdentity(db.userPreferenceDao(), GenerateId())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -208,6 +214,7 @@ class Auth401Test {
|
||||
private var token: String? = null
|
||||
private var user: UserDto? = null
|
||||
private var expiresAt: Long? = null
|
||||
private var credentials: com.kazier.mobile.auth.Credentials? = null
|
||||
|
||||
override fun getToken(): String? = token
|
||||
override fun getUser(): UserDto? = user
|
||||
@@ -224,6 +231,16 @@ class Auth401Test {
|
||||
user = null
|
||||
expiresAt = null
|
||||
}
|
||||
|
||||
override fun getCredentials(): com.kazier.mobile.auth.Credentials? = credentials
|
||||
|
||||
override fun saveCredentials(username: String, password: String) {
|
||||
credentials = com.kazier.mobile.auth.Credentials(username, password)
|
||||
}
|
||||
|
||||
override fun clearCredentials() {
|
||||
credentials = null
|
||||
}
|
||||
}
|
||||
|
||||
/** `listFolders` et `login` répondent 401 ; le reste est inutilisé. */
|
||||
@@ -303,5 +320,17 @@ class Auth401Test {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import com.kazier.mobile.data.repository.FileRepository
|
||||
@@ -30,6 +31,7 @@ import com.kazier.mobile.domain.GenerateId
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
@@ -192,5 +194,17 @@ class PaginationTest {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.kazier.mobile.data.remote
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
|
||||
/**
|
||||
* Streaming `GET /files/:id/content` (V1 finitions) : octets bruts bornés,
|
||||
* jamais persistés ; 404 = invisible ou metadata-only sans octets.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class RemoteContentTest {
|
||||
|
||||
private fun client(fake: ContentFake): ApiClient {
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
return ApiClient(fake, moshi)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_retourne_les_octets_bruts`() = runTest {
|
||||
val fake = ContentFake { Response.success("hello".toResponseBody("text/plain".toMediaType())) }
|
||||
val bytes = client(fake).downloadContentBytes("aabbccddeeff11223344556677889900")
|
||||
assertArrayEquals("hello".toByteArray(), bytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_404_mappe_NOT_FOUND`() = runTest {
|
||||
val fake = ContentFake {
|
||||
Response.error(404, "{\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"file not found\"}}".toResponseBody("application/json".toMediaType()))
|
||||
}
|
||||
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_borne_maxBytes_FILE_TOO_LARGE`() = runTest {
|
||||
val fake = ContentFake { Response.success("0123456789ABCDEF".toResponseBody("text/plain".toMediaType())) }
|
||||
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900", maxBytes = 4) }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("FILE_TOO_LARGE", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_401_declenche_onUnauthorized`() = runTest {
|
||||
var unauthorized = 0
|
||||
val fake = ContentFake {
|
||||
Response.error(401, "{\"error\":{\"code\":\"UNAUTHORIZED\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType()))
|
||||
}
|
||||
val c = client(fake)
|
||||
c.onUnauthorized = { unauthorized++ }
|
||||
val ex = runCatching { c.downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals(1, unauthorized)
|
||||
}
|
||||
|
||||
private class ContentFake(
|
||||
private val content: () -> Response<ResponseBody>,
|
||||
) : ApiService {
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||
Response.success(ApiEnvelope(data = body))
|
||||
|
||||
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||
|
||||
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content()
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.kazier.mobile.data.remote
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import com.kazier.mobile.auth.AuthEvent
|
||||
import com.kazier.mobile.auth.Credentials
|
||||
import com.kazier.mobile.auth.SessionManager
|
||||
import com.kazier.mobile.auth.TokenProvider
|
||||
import com.kazier.mobile.auth.TokenStore
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import com.kazier.mobile.data.remote.dto.UserDto
|
||||
import com.kazier.mobile.data.repository.AuthRepository
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.domain.LocalModeStore
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
|
||||
/**
|
||||
* Re-login silencieux (lot 3) : sur 401, `SessionManager` rejoue
|
||||
* `POST /auth/login` avec les identifiants chiffrés persistés au login
|
||||
* (single-flight), sans purger la file du même compte. Identifiants rejetés
|
||||
* → purge complète + `SessionExpired`.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class SessionReloginTest {
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var db: AppDatabase
|
||||
|
||||
private lateinit var tokenStore: FakeTokenStore
|
||||
private lateinit var tokenProvider: TokenProvider
|
||||
private lateinit var fake: ReloginFake
|
||||
private lateinit var apiClient: ApiClient
|
||||
private lateinit var sessionManager: SessionManager
|
||||
private val events = CopyOnWriteArrayList<AuthEvent>()
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context = ApplicationProvider.getApplicationContext<Context>()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
tokenStore = FakeTokenStore()
|
||||
tokenProvider = TokenProvider()
|
||||
fake = ReloginFake()
|
||||
apiClient = ApiClient(fake, moshi)
|
||||
sessionManager = SessionManager(
|
||||
tokenStore,
|
||||
ActiveUserStore(db.userPreferenceDao()),
|
||||
tokenProvider,
|
||||
LocalModeStore(db.userPreferenceDao()),
|
||||
db.pendingOperationDao(),
|
||||
apiClient,
|
||||
AuthRepository(apiClient, DeviceIdentity(db.userPreferenceDao(), GenerateId())),
|
||||
)
|
||||
CoroutineScope(Dispatchers.Unconfined).launch {
|
||||
sessionManager.events.collect { events += it }
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
private fun seed(token: String = "tok-old", withCreds: Boolean = true) {
|
||||
tokenStore.save(token, UserDto(id = "u1", username = "alice"), expiresAt = 9_999_999_999_999L)
|
||||
if (withCreds) tokenStore.saveCredentials("alice", "secret")
|
||||
tokenProvider.current = token
|
||||
}
|
||||
|
||||
private suspend fun awaitToken(value: String?) = withTimeout(5_000L) {
|
||||
while (tokenProvider.current != value) delay(10L)
|
||||
}
|
||||
|
||||
private suspend fun awaitEvent(count: Int) = withTimeout(5_000L) {
|
||||
while (events.size < count) delay(10L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `401_relogine_silencieusement_et_conserve_la_file`() = runBlocking {
|
||||
seed()
|
||||
db.pendingOperationDao().insert(op("create-1"))
|
||||
|
||||
runCatching { apiClient.listFolders() }
|
||||
awaitToken("tok-fresh")
|
||||
awaitEvent(1)
|
||||
|
||||
assertEquals("tok-fresh", tokenStore.getToken())
|
||||
assertEquals("alice", tokenStore.getUser()?.username)
|
||||
assertEquals(1, db.pendingOperationDao().countPending())
|
||||
assertTrue(events.single() is AuthEvent.Reauthenticated)
|
||||
// Identifiants conservés pour le prochain renouvellement.
|
||||
assertEquals(Credentials("alice", "secret"), tokenStore.getCredentials())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `401_login_rejete_purge_tout_et_emet_expired`() = runBlocking {
|
||||
seed()
|
||||
fake.loginMode = ReloginFake.LoginMode.REJECT
|
||||
db.pendingOperationDao().insert(op("create-1"))
|
||||
|
||||
runCatching { apiClient.listFolders() }
|
||||
awaitToken(null)
|
||||
awaitEvent(1)
|
||||
|
||||
withTimeout(5_000L) { while (tokenStore.getToken() != null) delay(10L) }
|
||||
assertNull(tokenStore.getCredentials())
|
||||
val expired = events.single() as AuthEvent.SessionExpired
|
||||
assertEquals("alice", expired.username)
|
||||
// La file n'est pas purgée par le 401 (C5) — seul un changement de
|
||||
// compte la purge.
|
||||
assertEquals(1, db.pendingOperationDao().countPending())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `401_sans_identifiants_purge_et_emet_expired`() = runBlocking {
|
||||
seed(withCreds = false)
|
||||
|
||||
runCatching { apiClient.listFolders() }
|
||||
awaitToken(null)
|
||||
awaitEvent(1)
|
||||
|
||||
assertEquals(0, fake.loginCalls.get())
|
||||
val expired = events.single() as AuthEvent.SessionExpired
|
||||
assertEquals("alice", expired.username)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `401_concurrents_un_seul_login`() = runBlocking {
|
||||
seed()
|
||||
|
||||
(1..5).map { async { runCatching { apiClient.listFolders() } } }.awaitAll()
|
||||
awaitToken("tok-fresh")
|
||||
awaitEvent(1)
|
||||
|
||||
assertEquals("un seul POST /auth/login malgré 5 401", 1, fake.loginCalls.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `relogin_proactif_sur_token_expire`() = runBlocking {
|
||||
seed(token = "tok-old")
|
||||
tokenProvider.current = null
|
||||
|
||||
assertTrue(sessionManager.trySilentRelogin())
|
||||
assertEquals("tok-fresh", tokenProvider.current)
|
||||
assertEquals("tok-fresh", tokenStore.getToken())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `relogin_proactif_sans_identifiants_echoue`() = runBlocking {
|
||||
seed(withCreds = false)
|
||||
tokenProvider.current = null
|
||||
|
||||
assertEquals(false, sessionManager.trySilentRelogin())
|
||||
assertEquals(0, fake.loginCalls.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `signOut_purge_aussi_les_identifiants`() = runBlocking {
|
||||
seed()
|
||||
sessionManager.clear()
|
||||
assertNull(tokenStore.getCredentials())
|
||||
assertNull(tokenProvider.current)
|
||||
}
|
||||
|
||||
private fun op(operationId: String) = PendingOperationEntity(
|
||||
operationId = operationId,
|
||||
resourceId = "r".repeat(32),
|
||||
resourceType = "file",
|
||||
operation = PendingOperationType.CREATE_RESOURCE,
|
||||
payload = "{}",
|
||||
status = PendingOpStatus.PENDING,
|
||||
createdAt = 1L,
|
||||
updatedAt = 1L,
|
||||
)
|
||||
|
||||
private class FakeTokenStore : TokenStore {
|
||||
private var token: String? = null
|
||||
private var user: UserDto? = null
|
||||
private var expiresAt: Long? = null
|
||||
private var credentials: Credentials? = null
|
||||
|
||||
override fun getToken(): String? = token
|
||||
override fun getUser(): UserDto? = user
|
||||
override fun getExpiresAt(): Long? = expiresAt
|
||||
override fun save(token: String, user: UserDto, expiresAt: Long?) {
|
||||
this.token = token
|
||||
this.user = user
|
||||
this.expiresAt = expiresAt
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
token = null
|
||||
user = null
|
||||
expiresAt = null
|
||||
}
|
||||
|
||||
override fun getCredentials(): Credentials? = credentials
|
||||
override fun saveCredentials(username: String, password: String) {
|
||||
credentials = Credentials(username, password)
|
||||
}
|
||||
|
||||
override fun clearCredentials() {
|
||||
credentials = null
|
||||
}
|
||||
}
|
||||
|
||||
/** `listFolders` → 401 ; `login` rejoue un token frais (ou 401 si REJECT). */
|
||||
private class ReloginFake : ApiService {
|
||||
enum class LoginMode { SUCCESS, REJECT }
|
||||
|
||||
var loginMode = LoginMode.SUCCESS
|
||||
val loginCalls = AtomicInteger(0)
|
||||
|
||||
private fun envelopeError(code: String): ResponseBody =
|
||||
"{\"error\":{\"code\":\"$code\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType())
|
||||
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.error(401, envelopeError("UNAUTHORIZED"))
|
||||
|
||||
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> {
|
||||
loginCalls.incrementAndGet()
|
||||
delay(20L)
|
||||
return when (loginMode) {
|
||||
LoginMode.REJECT -> Response.error(401, envelopeError("UNAUTHORIZED"))
|
||||
LoginMode.SUCCESS -> Response.success(
|
||||
ApiEnvelope(
|
||||
data = LoginResponseDto(
|
||||
token = "tok-fresh",
|
||||
expiresAt = 9_999_999_999_999L,
|
||||
user = UserDto(id = "u1", username = body.username),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||
Response.success(ApiEnvelope(data = body))
|
||||
|
||||
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||
|
||||
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
|
||||
Response.success(ByteArray(0).toResponseBody(null))
|
||||
|
||||
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.kazier.mobile.data.remote
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
|
||||
/**
|
||||
* Listes de partage (lot 2) : `GET /files/:id/shares` et `/links`
|
||||
* (owner uniquement) — mapping DTO et 404 non-owner.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ShareManagementTest {
|
||||
|
||||
private fun client(fake: SharesFake): ApiClient {
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
return ApiClient(fake, moshi)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `listShares_retourne_les_grants`() = runTest {
|
||||
val grants = listOf(
|
||||
ShareGrantDto("aa01", "alice", "editor", true, null, 1_700_000_000_000L),
|
||||
ShareGrantDto("bb02", "bob", "viewer", false, 1_800_000_000_000L, 1_700_000_000_001L),
|
||||
)
|
||||
val fake = SharesFake(shares = grants)
|
||||
val got = client(fake).listShares("f".repeat(32))
|
||||
assertEquals(2, got.size)
|
||||
assertEquals("alice", got[0].username)
|
||||
assertEquals("editor", got[0].access)
|
||||
assertEquals(1_800_000_000_000L, got[1].expiresAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `listLinks_retourne_les_liens`() = runTest {
|
||||
val links = listOf(
|
||||
ShareLinkDto("t".repeat(32), "f".repeat(32), "folder", "Docs", "viewer", null),
|
||||
)
|
||||
val fake = SharesFake(links = links)
|
||||
val got = client(fake).listLinks("f".repeat(32))
|
||||
assertEquals(1, got.size)
|
||||
assertEquals("t".repeat(32), got[0].token)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `listShares_404_non_owner_mappe_NOT_FOUND`() = runTest {
|
||||
val fake = SharesFake(failShares = true)
|
||||
val ex = runCatching { client(fake).listShares("f".repeat(32)) }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getShareLink_invalide_mappe_LINK`() = runTest {
|
||||
val fake = SharesFake(failLink = true)
|
||||
val ex = runCatching { client(fake).getShareLink("t".repeat(32)) }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
private class SharesFake(
|
||||
private val shares: List<ShareGrantDto> = emptyList(),
|
||||
private val links: List<ShareLinkDto> = emptyList(),
|
||||
private val failShares: Boolean = false,
|
||||
private val failLink: Boolean = false,
|
||||
) : ApiService {
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||
Response.success(ApiEnvelope(data = body))
|
||||
|
||||
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||
|
||||
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
if (failLink) {
|
||||
Response.error(404, errBody("NOT_FOUND"))
|
||||
} else {
|
||||
Response.success(ApiEnvelope(data = ShareLinkDto(token, "f".repeat(32), "folder", "Docs", "viewer", null)))
|
||||
}
|
||||
|
||||
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
|
||||
Response.success(ByteArray(0).toResponseBody(null))
|
||||
|
||||
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
|
||||
if (failShares) {
|
||||
Response.error(404, errBody("NOT_FOUND"))
|
||||
} else {
|
||||
Response.success(ApiEnvelope(data = shares))
|
||||
}
|
||||
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = links))
|
||||
|
||||
private fun errBody(code: String) =
|
||||
"{\"error\":{\"code\":\"$code\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType())
|
||||
}
|
||||
}
|
||||
+14
@@ -20,6 +20,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
@@ -52,6 +53,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fous data-layer de la fusion de dossiers : le re-parentage repositionne
|
||||
@@ -378,4 +380,16 @@ private class FolderMergeApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+14
@@ -26,6 +26,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
@@ -54,6 +55,7 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowContentResolver
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fous outbox du déplacement local : tant qu'un `move_resource` est en
|
||||
@@ -467,4 +469,16 @@ private class MoveProtectionApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+14
@@ -18,6 +18,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
@@ -46,6 +47,7 @@ import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import java.io.ByteArrayInputStream
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Pipeline OCR local : l'upload multipart ciblé envoie les octets du flux SAF
|
||||
@@ -385,4 +387,16 @@ private class OcrApiServiceFake : ApiService {
|
||||
body.writeTo(buffer)
|
||||
return buffer.readUtf8()
|
||||
}
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+14
@@ -28,6 +28,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
@@ -44,6 +45,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fou refresh serveur vs reparent local (miroir dossiers du
|
||||
@@ -234,4 +236,16 @@ private class RefreshVsMoveApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
|
||||
+14
@@ -19,6 +19,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
@@ -45,6 +46,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Contrat de l'hydratation du snapshot `GET /sync/permissions` :
|
||||
@@ -488,4 +490,16 @@ private class FakeApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+14
@@ -40,6 +40,7 @@ import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncFailedDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
@@ -54,6 +55,7 @@ import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -448,5 +450,17 @@ class OutboxSyncWorkerTest {
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
|
||||
override suspend fun listShares(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.kazier.mobile.ui.share
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Parsing des liens de partage (lot 2) : token brut, deep-link
|
||||
* `kazier://share/…`, URL API `…/shares/links/…`.
|
||||
*/
|
||||
class ShareLinkParserTest {
|
||||
|
||||
private val token = "aabbccddeeff11223344556677889900"
|
||||
|
||||
@Test
|
||||
fun `extractToken_accepte_le_32_hex_brut`() {
|
||||
assertEquals(token, ShareLinkParser.extractToken(token))
|
||||
assertEquals(token, ShareLinkParser.extractToken(" $token\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extractToken_normalise_la_casse`() {
|
||||
assertEquals(token, ShareLinkParser.extractToken(token.uppercase()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extractToken_extrait_du_deep_link`() {
|
||||
assertEquals(token, ShareLinkParser.extractToken("kazier://share/$token"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extractToken_extrait_de_l_url_api`() {
|
||||
assertEquals(
|
||||
token,
|
||||
ShareLinkParser.extractToken("http://10.0.2.2:8080/api/v1/shares/links/$token"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extractToken_rejette_l_illisible`() {
|
||||
assertNull(ShareLinkParser.extractToken(""))
|
||||
assertNull(ShareLinkParser.extractToken(" "))
|
||||
assertNull(ShareLinkParser.extractToken("not-a-token"))
|
||||
assertNull(ShareLinkParser.extractToken("kazier://share/zzz"))
|
||||
assertNull(ShareLinkParser.extractToken("kazier://share/${token}00"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `shareUrl_produit_le_deep_link`() {
|
||||
assertEquals("kazier://share/$token", ShareLinkParser.shareUrl(token))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user