~tsileo/blobstash

ref: d62b4924ec016bd250d26f05ac5570f60374e0f2 blobstash/pkg/filetree/lua/lua.go -rw-r--r-- 9.7 KiB View raw
d62b4924Thomas Sileo filetree/lua: add new upload_file Lua function 2 months ago
                                                                                
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package lua // import "a4.io/blobstash/pkg/filetree/lua"

import (
	"context"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	humanize "github.com/dustin/go-humanize"
	"github.com/yuin/gopher-lua"

	"a4.io/blobsfile"
	"a4.io/blobstash/pkg/apps/luautil"
	"a4.io/blobstash/pkg/filetree"
	rnode "a4.io/blobstash/pkg/filetree/filetreeutil/node"
	"a4.io/blobstash/pkg/filetree/imginfo"
	"a4.io/blobstash/pkg/filetree/reader/filereader"
	"a4.io/blobstash/pkg/filetree/vidinfo"
	"a4.io/blobstash/pkg/filetree/writer"
	"a4.io/blobstash/pkg/stash/store"
)

func buildFSInfo(L *lua.LState, name, ref, tgzURL string) *lua.LTable {
	tbl := L.CreateTable(0, 2)
	tbl.RawSetString("name", lua.LString(name))
	tbl.RawSetString("ref", lua.LString(ref))
	tbl.RawSetString("tgz_url", lua.LString(tgzURL))
	return tbl
}

func convertNode(L *lua.LState, ft *filetree.FileTree, bs store.BlobStore, node *filetree.Node) *lua.LTable {
	tbl := L.CreateTable(0, 32)
	dlURL, embedURL, err := ft.GetSemiPrivateLink(node)
	if err != nil {
		panic(err)
	}
	tbl.RawSetString("url", lua.LString(embedURL))
	tbl.RawSetString("dl_url", lua.LString(dlURL))
	if vidinfo.IsVideo(node.Name) {
		if node.Info != nil && node.Info.Video != nil {
			tbl.RawSetString("video_width", lua.LNumber(node.Info.Video.Width))
			tbl.RawSetString("video_height", lua.LNumber(node.Info.Video.Height))
			tbl.RawSetString("video_codec", lua.LString(node.Info.Video.Codec))
			t := node.Info.Video.Duration
			tbl.RawSetString("video_duration", lua.LString(fmt.Sprintf("%02d:%02d:%02d", (t/3600), (t/60)%60, t%60)))
		}
		webmURL, webmPosterURL, err := ft.GetWebmLink(node)
		if err != nil {
			panic(err)
		}
		tbl.RawSetString("is_video", lua.LTrue)
		tbl.RawSetString("webm_poster_url", lua.LString(webmPosterURL))
		tbl.RawSetString("webm_url", lua.LString(webmURL))
	} else {
		tbl.RawSetString("is_video", lua.LFalse)
		tbl.RawSetString("webm_poster_url", lua.LString(""))
		tbl.RawSetString("webm_url", lua.LString(""))
	}
	if imginfo.IsImage(node.Name) {
		tbl.RawSetString("is_image", lua.LTrue)
		if node.Info != nil && node.Info.Image != nil {
			tbl.RawSetString("image_width", lua.LNumber(node.Info.Image.Width))
			tbl.RawSetString("image_height", lua.LNumber(node.Info.Image.Height))
			// TODO(tsileo): export EXIF
		}
	} else {
		tbl.RawSetString("is_image", lua.LFalse)
	}
	if node.FileType == "text" {
		// FIXME(tsileo): check only the firsr blob, cache the result in a LRU and uses it for Node.FileType
		f := filereader.NewFile(context.TODO(), bs, node.Meta, nil)
		defer f.Close()
		contents, err := ioutil.ReadAll(f)
		if err != nil {
			panic(err)
		}
		tbl.RawSetString("contents", lua.LString(contents))
	} else {
		tbl.RawSetString("contents", lua.LString(""))
	}
	tbl.RawSetString("hash", lua.LString(node.Hash))
	tbl.RawSetString("name", lua.LString(node.Name))
	tbl.RawSetString("type", lua.LString(node.Type))
	tbl.RawSetString("mtime", lua.LString(node.ModTime))
	tbl.RawSetString("mtime_short", lua.LString(strings.Split(node.ModTime, "T")[0]))
	tbl.RawSetString("citme", lua.LString(node.ChangeTime))
	tbl.RawSetString("mode", lua.LString(os.FileMode(node.Mode).String()))
	tbl.RawSetString("size", lua.LNumber(node.Size))
	tbl.RawSetString("size_human", lua.LString(humanize.Bytes(uint64(node.Size))))
	childrenTbl := L.CreateTable(len(node.Children), 0)
	for _, child := range node.Children {
		childrenTbl.Append(convertNode(L, ft, bs, child))
	}
	tbl.RawSetString("children", childrenTbl)
	if node.Type == rnode.Dir {
		tgzURL, err := ft.GetTgzLink(node)
		if err != nil {
			panic(err)
		}

		tbl.RawSetString("tgz_url", lua.LString(tgzURL))
		tbl.RawSetString("children_count", lua.LNumber(node.ChildrenCount))
	} else {
		tbl.RawSetString("file_type", lua.LString(node.FileType))
	}
	return tbl
}

func setupFileTree(ft *filetree.FileTree, bs store.BlobStore, kv store.KvStore) func(*lua.LState) int {
	return func(L *lua.LState) int {
		// register functions to the table
		mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
			"create_fs": func(L *lua.LState) int {
				node, err := ft.CreateFS(context.TODO(), L.ToString(1), filetree.FSKeyFmt)
				if err != nil {
					panic(err)
				}
				L.Push(convertNode(L, ft, bs, node))
				return 1
			},
			"iter_fs": func(L *lua.LState) int {
				it, err := ft.IterFS(context.TODO(), "")
				if err != nil {
					panic(err)
				}
				tbl := L.CreateTable(len(it), 0)
				for _, kv := range it {
					tgzURL, err := ft.GetTgzLink(&filetree.Node{Hash: kv.Ref})
					if err != nil {
						panic(err)
					}
					tbl.Append(buildFSInfo(L, kv.Name, kv.Ref, tgzURL))
				}
				L.Push(tbl)
				return 1
			},
			"fs_versions": func(L *lua.LState) int {
				versions, err := ft.LuaFSVersions(L.ToString(1))
				if err != nil {
					panic(err)
				}

				tbl := L.CreateTable(len(versions), 0)
				for _, v := range versions {
					snap := L.CreateTable(0, 4)
					snap.RawSetString("ref", lua.LString(v.Ref))
					snap.RawSetString("hostname", lua.LString(v.Hostname))
					snap.RawSetString("message", lua.LString(v.Message))
					snap.RawSetString("created_at", lua.LString(time.Unix(0, v.CreatedAt).Format(time.RFC3339)))
					tbl.Append(snap)
				}
				L.Push(tbl)
				return 1
			},
			"fs_by_name": func(L *lua.LState) int {
				fs, err := ft.FS(context.TODO(), L.ToString(1), filetree.FSKeyFmt, false, 0)
				if err != nil {
					panic(err)
				}
				node, _, _, err := fs.Path(context.TODO(), "/", 1, false, 0)
				if err != nil {
					if err == blobsfile.ErrBlobNotFound {
						L.Push(lua.LNil)
						return 1
					}

					panic(err)
				}
				L.Push(convertNode(L, ft, bs, node))
				return 1

			},
			"fs_by_name_at": func(L *lua.LState) int {
				fs, err := ft.FS(context.TODO(), L.ToString(1), filetree.FSKeyFmt, false, 0)
				if err != nil {
					panic(err)
				}
				node, _, _, err := fs.Path(context.TODO(), L.ToString(2), 1, false, 0)
				if err != nil {
					if err == blobsfile.ErrBlobNotFound {
						L.Push(lua.LNil)
						return 1
					}

					panic(err)
				}
				L.Push(convertNode(L, ft, bs, node))
				return 1

			},
			"fs": func(L *lua.LState) int {
				fs := filetree.NewFS(L.ToString(1), ft)
				node, _, _, err := fs.Path(context.TODO(), "/", 1, false, 0)
				if err != nil {
					panic(err)
				}
				L.Push(convertNode(L, ft, bs, node))
				return 1
			},
			"node": func(L *lua.LState) int {
				node, err := ft.NodeWithChildren(context.TODO(), L.ToString(2))
				if err != nil {
					panic(err)
				}
				path, err := ft.BruteforcePath(context.TODO(), L.ToString(1), L.ToString(2))
				if err != nil {
					panic(err)
				}
				spath := ""
				pathTable := L.CreateTable(len(path), 0)
				for _, nodeInfo := range path {
					if nodeInfo.Name != "_root" {
						spath = spath + "/" + nodeInfo.Name
					}
					pathTable.Append(buildFSInfo(L, nodeInfo.Name, nodeInfo.Ref, ""))
				}
				if node.Name != "_root" {
					spath = spath + "/" + node.Name
				}
				L.Push(convertNode(L, ft, bs, node))
				L.Push(pathTable)
				L.Push(lua.LString(spath))
				return 3
			},
			"put_file": func(L *lua.LState) int {
				uploader := writer.NewUploader(filetree.NewBlobStoreCompat(bs, context.TODO()))
				name := L.ToString(1)
				newName := L.ToString(2)
				extraMeta := L.ToBool(3)
				var ref string
				if newName != "" {
					// Upload the given file with a new name and without meta data (mtime/ctime/mode)
					node, err := uploader.PutFileRename(name, newName, extraMeta)
					if err != nil {
						panic(err)
					}
					ref = node.Hash
				} else {
					node, err := uploader.PutFile(name)
					if err != nil {
						panic(err)
					}
					ref = node.Hash
				}
				L.Push(lua.LString(ref))
				return 1
			},
			"mkdir": func(L *lua.LState) int {
				ctx := context.TODO()
				fs, err := ft.FS(ctx, L.ToString(1), filetree.FSKeyFmt, false, 0)
				if err != nil {
					panic(err)
				}
				node, err := fs.Mkdir(ctx, filetree.FSKeyFmt, L.ToString(2), L.ToString(3))
				if err != nil {
					panic(err)
				}
				L.Push(lua.LString(node.Hash))
				return 1
			},
			"upload_file": func(L *lua.LState) int {
				uploader := writer.NewUploader(filetree.NewBlobStoreCompat(bs, context.TODO()))
				name := L.ToString(1)
				contents := L.ToString(2)
				node, err := uploader.PutReader(name, strings.NewReader(contents), nil)
				if err != nil {
					panic(err)
				}

				L.Push(lua.LString(node.Hash))
				return 1
			},
			"put_file_at": func(L *lua.LState) int {
				uploader := writer.NewUploader(filetree.NewBlobStoreCompat(bs, context.TODO()))
				snap := toSnap(luautil.TableToMap(L.ToTable(1)))
				name := L.ToString(2)
				contents := L.ToString(3)
				var ref string
				node, err := uploader.PutReader(name, strings.NewReader(contents), nil)
				if err != nil {
					panic(err)
				}

				ref = node.Hash
				ctx := context.TODO()

				fs, err := ft.FS(ctx, L.ToString(4), filetree.FSKeyFmt, false, 0)
				if err != nil {
					panic(err)
				}

				t := time.Now().Unix()
				parentNode, _, _, err := fs.Path(ctx, L.ToString(5), 1, true, t)
				if err != nil {
					panic(err)
				}
				if parentNode.Type != rnode.Dir {
					panic("only dir can be patched")
				}

				newParent, _, err := ft.AddChild(ctx, snap, parentNode, node, filetree.FSKeyFmt, t)
				if err != nil {
					panic(err)
				}

				fmt.Printf("newParent=%+v\nnew file ref=%s\n", newParent, ref)
				L.Push(lua.LString(newParent.Hash))
				L.Push(lua.LString(ref))
				return 2
			},
		})
		// returns the module
		L.Push(mod)
		return 1
	}
}

func toSnap(dat map[string]interface{}) *filetree.Snapshot {
	snap := &filetree.Snapshot{}
	if iua, ok := dat["user_agent"]; ok {
		snap.UserAgent = iua.(string)
	}
	if imessage, ok := dat["message"]; ok {
		snap.Message = imessage.(string)
	}
	return snap
}

// Setup loads the filetree Lua module
func Setup(L *lua.LState, ft *filetree.FileTree, bs store.BlobStore, kv store.KvStore) {
	L.PreloadModule("filetree", setupFileTree(ft, bs, kv))
}