All files / src/services/api/routers FileRouter.tsx

81.48% Statements 22/27
75% Branches 12/16
85.71% Functions 6/7
84.61% Lines 22/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113                                                                                        2209x           2209x 3x 3x 3x             3x 3x           2209x 3x     3x 3x             2209x       3x           3x 3x             2209x 57x     57x 57x 57x         2209x 3x      
import { Dictionary } from "@/types/ext";
import { dispositionFilename } from "@/util/download";
import { AxiosRequestConfig } from "axios";
import { APIRouter } from "../ApiRouter";
 
/** How far svc-core got reading a document's text: an upload answers
 *  `reading`, and a chat can attach it once `ready`. */
export type UploadStatus = "reading" | "ready" | "failed";
 
/** A document in the workspace's library (svc-core `app/services/uploads.py`). */
export interface UploadedFileRef {
  id: string;
  name: string;
  mime_type: string | null;
  created_at: string;
  /** Who uploaded it — the actor on its first edit-history version; null
   *  when that account is gone. */
  uploaded_by?: { id: string; name?: string | null; email?: string | null } | null;
  /** Whether the caller may delete it: its uploader (a writer of Knowledge)
   *  or an editor in a shared workspace, always in Personal. */
  can_delete?: boolean;
  /** Absent from older responses, whose documents were all read. */
  status?: UploadStatus;
  /** Why no text could be read, when `failed`. */
  error?: string | null;
  /** The original's size; absent for one uploaded before originals were kept. */
  size_bytes?: number | null;
  /** Whether `fetchContent` can return the file as uploaded. */
  has_original?: boolean;
}
 
/** A document's file as uploaded, and the name to save it under. */
export interface UploadedFileContent {
  blob: Blob;
  filename: string;
}
 
export class FileRouter extends APIRouter {
  constructor(
    host: string,
    token: string | null = null,
    default_config: AxiosRequestConfig | null = null,
    headers: Dictionary<string> = {},
  ) {
    super("files", host, token, default_config, headers);
  }
 
  /** Upload into the workspace's library. Rejects with the API's refusal
   *  (a reader of Knowledge may not add to a shared library). It answers
   *  before the text is read: `uploadAndRead` waits for that. */
  uploadFile = async (file: File): Promise<UploadedFileRef | null> => {
    const formData = new FormData();
    formData.append("file", file);
    const res = await this.api.post<UploadedFileRef>(
      super.endpoint("upload"),
      formData,
      {
        withCredentials: true,
      },
    );
    Eif (super.validRes(res)) {
      return res.data;
    }
    return null;
  };
 
  /** One document: how far reading its text has got. */
  getFile = async (fileId: string): Promise<UploadedFileRef | null> => {
    const res = await this.api.get<UploadedFileRef>(super.endpoint(fileId), {
      withCredentials: true,
    });
    Eif (super.validRes(res)) {
      return res.data;
    }
    return null;
  };
 
  /** The file as uploaded (svc-core keeps it since migration 109). Null
   *  when there is none: deleted, or uploaded before originals were kept. */
  fetchContent = async (
    fileId: string,
    fallbackName = "document",
  ): Promise<UploadedFileContent | null> => {
    const res = await this.api
      .get(super.endpoint(`${fileId}/content`), {
        responseType: "blob",
        withCredentials: true,
      })
      .catch(() => null);
    Iif (res?.status !== 200) return null;
    return {
      blob: res.data as Blob,
      filename:
        dispositionFilename(res.headers?.["content-disposition"]) ?? fallbackName,
    };
  };
 
  listFiles = async (): Promise<UploadedFileRef[]> => {
    const res = await this.api.get(super.endpoint(""), {
      withCredentials: true,
    });
    Eif (super.validRes(res)) {
      const data = res.data as { files: UploadedFileRef[] };
      return data.files ?? [];
    }
    return [];
  };
 
  deleteFile = async (fileId: string): Promise<void> => {
    await this.api.delete(super.endpoint(fileId), { withCredentials: true });
  };
}