From 00d7836d8a3d0101bd282e3acce58d65ed0220fe Mon Sep 17 00:00:00 2001 From: bptato Date: Thu, 8 Jun 2023 08:03:16 +0200 Subject: Remove JSObject again, add File API constructor --- src/types/blob.nim | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) (limited to 'src/types') diff --git a/src/types/blob.nim b/src/types/blob.nim index 677fb037..4a5627c3 100644 --- a/src/types/blob.nim +++ b/src/types/blob.nim @@ -1,3 +1,5 @@ +import options + import js/javascript import types/mime import utils/twtstr @@ -37,17 +39,47 @@ proc newWebFile*(path: string, webkitRelativePath = ""): WebFile = isfile: true, path: path, file: file, + ctype: guessContentType(path), webkitRelativePath: webkitRelativePath ) +proc newWebFile(ctx: JSContext, fileBits: seq[string], fileName: string, + options = none(JSValue)): WebFile {.jsctor.} = + let file = WebFile( + isfile: false, + path: fileName, + deallocFun: dealloc + ) + var len = 0 + for blobPart in fileBits: + len += blobPart.len + file.buffer = alloc(len) + var buf = cast[ptr UncheckedArray[uint8]](file.buffer) + var i = 0 + for blobPart in fileBits: + if blobPart.len > 0: + copyMem(addr buf[i], unsafeAddr blobPart[0], blobPart.len) + i += blobPart.len + file.size = uint64(len) + if options.isSome: + block ctype: + let t = fromJS[string](ctx, JS_GetPropertyStr(ctx, options.get, "type")) + if t.isNone: + break ctype + for c in t.get: + if c notin char(0x20)..char(0x7E): + break ctype + file.ctype &= c.tolower() + #TODO lastmodified + return file + #TODO File, Blob constructors func size*(this: WebFile): uint64 {.jsfget.} = #TODO use stat instead - return uint64(this.file.getFileSize()) - -func ctype*(this: WebFile): string {.jsfget: "type".} = - return guessContentType(this.path) + if this.isfile: + return uint64(this.file.getFileSize()) + return this.size func name*(this: WebFile): string {.jsfget.} = if this.path.len > 0 and this.path[^1] != '/': @@ -57,5 +89,5 @@ func name*(this: WebFile): string {.jsfget.} = #TODO lastModified proc addBlobModule*(ctx: JSContext) = - ctx.registerType(Blob) - ctx.registerType(WebFile, name = "File") + let blobCID = ctx.registerType(Blob) + ctx.registerType(WebFile, parent = blobCID, name = "File") -- cgit 1.4.1-2-gfad0