This repository has been archived by the owner on Feb 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fairos.go
629 lines (561 loc) · 14.8 KB
/
fairos.go
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package fairos
//go:generate gomobile bind -androidapi 21 -o fairos.aar -target=android github.com/fairdatasociety/fairos
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"github.com/dustin/go-humanize"
"github.com/fairdatasociety/fairOS-dfs/pkg/collection"
"github.com/fairdatasociety/fairOS-dfs/pkg/contracts"
"github.com/fairdatasociety/fairOS-dfs/pkg/dfs"
"github.com/fairdatasociety/fairOS-dfs/pkg/logging"
"github.com/fairdatasociety/fairOS-dfs/pkg/utils"
"github.com/sirupsen/logrus"
_ "golang.org/x/mobile/bind"
)
var (
api *dfs.API
savedPassword string
savedUsername string
sessionId string
)
// IsConnected checks if dfs.API is already initialised or password is saved or not
func IsConnected() bool {
if api == nil {
return false
}
if savedPassword == "" {
return false
}
return true
}
// Connect with a bee and initialise dfs.API
func Connect(beeEndpoint, postageBlockId, network, rpc string, logLevel int) error {
logger := logging.New(os.Stdout, logrus.Level(logLevel))
var err error
var ensConfig *contracts.Config
switch network {
case "play":
ensConfig = contracts.PlayConfig()
case "testnet":
ensConfig = contracts.TestnetConfig()
case "mainnet":
return fmt.Errorf("not supported yet")
default:
return fmt.Errorf("unknown network")
}
ensConfig.ProviderBackend = rpc
api, err = dfs.NewDfsAPI(
beeEndpoint,
postageBlockId,
ensConfig,
logger,
)
return err
}
func LoginUser(username, password string) (string, error) {
ui, nameHash, publicKey, err := api.LoginUserV2(username, password, "")
if err != nil {
return "", err
}
sessionId = ui.GetSessionId()
savedPassword = password
savedUsername = username
data := map[string]string{}
data["namehash"] = nameHash
data["publicKey"] = publicKey
resp, _ := json.Marshal(data)
return string(resp), nil
}
func IsUserPresent(username string) bool {
return api.IsUserNameAvailableV2(username)
}
func IsUserLoggedIn() bool {
return api.IsUserLoggedIn(savedUsername)
}
func LogoutUser() error {
return api.LogoutUser(sessionId)
}
func DeleteUser() error {
return api.DeleteUserV2(savedPassword, sessionId)
}
func StatUser() (string, error) {
stat, err := api.GetUserStat(sessionId)
if err != nil {
return "", err
}
resp, _ := json.Marshal(stat)
return string(resp), nil
}
func NewPod(podName string) (string, error) {
_, err := api.CreatePod(podName, sessionId)
if err != nil {
return "", err
}
return "pod created successfully", nil
}
func PodOpen(podName string) (string, error) {
_, err := api.OpenPod(podName, sessionId)
if err != nil {
return "", err
}
return "pod created successfully", nil
}
func PodClose(podName string) error {
return api.ClosePod(podName, sessionId)
}
func PodDelete(podName string) error {
return api.DeletePod(podName, sessionId)
}
func PodSync(podName string) error {
return api.SyncPod(podName, sessionId)
}
func PodList() (string, error) {
ownPods, sharedPods, err := api.ListPods(sessionId)
if err != nil {
return "", err
}
if ownPods == nil {
ownPods = []string{}
}
if sharedPods == nil {
sharedPods = []string{}
}
data := map[string]interface{}{}
data["pods"] = ownPods
data["sharedPods"] = sharedPods
resp, _ := json.Marshal(data)
return string(resp), nil
}
func PodStat(podName string) (string, error) {
stat, err := api.PodStat(podName, sessionId)
if err != nil {
return "", err
}
resp, _ := json.Marshal(stat)
return string(resp), nil
}
func IsPodPresent(podName string) bool {
return api.IsPodExist(podName, sessionId)
}
func PodShare(podName string) (string, error) {
reference, err := api.PodShare(podName, "", sessionId)
if err != nil {
return "", err
}
data := map[string]string{}
data["pod_sharing_reference"] = reference
resp, _ := json.Marshal(data)
return string(resp), nil
}
func PodReceive(podSharingReference string) (string, error) {
ref, err := utils.ParseHexReference(podSharingReference)
if err != nil {
return "", err
}
pi, err := api.PodReceive(sessionId, "", ref)
if err != nil {
return "", err
}
return fmt.Sprintf("public pod \"%s\", added as shared pod", pi.GetPodName()), nil
}
func PodReceiveInfo(podSharingReference string) (string, error) {
ref, err := utils.ParseHexReference(podSharingReference)
if err != nil {
return "", err
}
shareInfo, err := api.PodReceiveInfo(sessionId, ref)
if err != nil {
return "", err
}
resp, _ := json.Marshal(shareInfo)
return string(resp), nil
}
func DirPresent(podName, dirPath string) (string, error) {
present, err := api.IsDirPresent(podName, dirPath, sessionId)
if err != nil {
return "", err
}
data := map[string]bool{}
data["present"] = present
resp, _ := json.Marshal(data)
return string(resp), nil
}
func DirMake(podName, dirPath string) (string, error) {
err := api.Mkdir(podName, dirPath, sessionId)
if err != nil {
return "", err
}
return string("directory created successfully"), nil
}
func DirRemove(podName, dirPath string) (string, error) {
err := api.RmDir(podName, dirPath, sessionId)
if err != nil {
return "", err
}
return string("directory removed successfully"), nil
}
func DirList(podName, dirPath string) (string, error) {
dirs, files, err := api.ListDir(podName, dirPath, sessionId)
if err != nil {
return "", err
}
fileList := []string{}
dirList := []string{}
for _, v := range files {
fileList = append(fileList, v.Name)
}
for _, v := range dirs {
dirList = append(dirList, v.Name)
}
data := map[string]interface{}{}
data["files"] = fileList
data["dirs"] = dirList
resp, _ := json.Marshal(data)
return string(resp), nil
}
func DirStat(podName, dirPath string) (string, error) {
stat, err := api.DirectoryStat(podName, dirPath, sessionId)
if err != nil {
return "", err
}
resp, _ := json.Marshal(stat)
return string(resp), nil
}
func FileShare(podName, dirPath, destinationUser string) (string, error) {
ref, err := api.ShareFile(podName, dirPath, destinationUser, sessionId)
if err != nil {
return "", err
}
data := map[string]string{}
data["file_sharing_reference"] = ref
resp, _ := json.Marshal(data)
return string(resp), err
}
func FileReceive(podName, directory, fileSharingReference string) (string, error) {
ref, err := utils.ParseSharingReference(fileSharingReference)
if err != nil {
return "", err
}
filePath, err := api.ReceiveFile(podName, sessionId, ref, directory)
if err != nil {
return "", err
}
data := map[string]string{}
data["file_name"] = filePath
resp, _ := json.Marshal(data)
return string(resp), err
}
func FileReceiveInfo(podName, fileSharingReference string) (string, error) {
ref, err := utils.ParseSharingReference(fileSharingReference)
if err != nil {
return "", err
}
receiveInfo, err := api.ReceiveInfo(sessionId, ref)
if err != nil {
return "", err
}
resp, _ := json.Marshal(receiveInfo)
return string(resp), err
}
func FileDelete(podName, filePath string) error {
return api.DeleteFile(podName, filePath, sessionId)
}
func FileStat(podName, filePath string) (string, error) {
stat, err := api.FileStat(podName, filePath, sessionId)
if err != nil {
return "", err
}
resp, _ := json.Marshal(stat)
return string(resp), err
}
func FileUpload(podName, filePath, dirPath, compression, blockSize string, overwrite bool) error {
fileInfo, err := os.Lstat(filePath)
if err != nil {
return err
}
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
bs, err := humanize.ParseBytes(blockSize)
if err != nil {
return err
}
return api.UploadFile(podName, fileInfo.Name(), sessionId, fileInfo.Size(), f, dirPath, compression, uint32(bs), overwrite)
}
func BlobUpload(data []byte, podName, fileName, dirPath, compression string, size, blockSize int64, overwrite bool) error {
r := bytes.NewReader(data)
return api.UploadFile(podName, fileName, sessionId, size, r, dirPath, compression, uint32(blockSize), overwrite)
}
func FileDownload(podName, filePath string) ([]byte, error) {
r, _, err := api.DownloadFile(podName, filePath, sessionId)
if err != nil {
return nil, err
}
defer r.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(r)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func KVNewStore(podName, tableName, indexType string) (string, error) {
if indexType == "" {
indexType = "string"
}
var idxType collection.IndexType
switch indexType {
case "string":
idxType = collection.StringIndex
case "number":
idxType = collection.NumberIndex
case "bytes":
default:
return "", fmt.Errorf("invalid indexType. only string and number are allowed")
}
err := api.KVCreate(sessionId, podName, tableName, idxType)
if err != nil {
return "", err
}
return "kv store created", nil
}
func KVList(podName string) (string, error) {
collections, err := api.KVList(sessionId, podName)
if err != nil {
return "", err
}
resp, _ := json.Marshal(collections)
return string(resp), err
}
func KVOpen(podName, tableName string) error {
return api.KVOpen(sessionId, podName, tableName)
}
func KVDelete(podName, tableName string) error {
return api.KVDelete(sessionId, podName, tableName)
}
func KVCount(podName, tableName string) (string, error) {
count, err := api.KVCount(sessionId, podName, tableName)
if err != nil {
return "", err
}
resp, _ := json.Marshal(count)
return string(resp), err
}
func KVEntryPut(podName, tableName, key string, value []byte) error {
return api.KVPut(sessionId, podName, tableName, key, value)
}
func KVEntryGet(podName, tableName, key string) ([]byte, error) {
_, data, err := api.KVGet(sessionId, podName, tableName, key)
if err != nil {
return nil, err
}
return data, nil
}
func KVEntryDelete(podName, tableName, key string) error {
_, err := api.KVDel(sessionId, podName, tableName, key)
return err
}
func KVLoadCSV(podName, tableName, filePath, memory string) (string, error) {
_, err := os.Lstat(filePath)
if err != nil {
return "", err
}
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
mem := true
if memory == "" {
mem = false
}
reader := bufio.NewReader(f)
readHeader := false
rowCount := 0
successCount := 0
failureCount := 0
var batch *collection.Batch
for {
// read one row from csv (assuming
record, err := reader.ReadString('\n')
if err == io.EOF {
break
}
rowCount++
if err != nil {
failureCount++
continue
}
record = strings.TrimSuffix(record, "\n")
record = strings.TrimSuffix(record, "\r")
if !readHeader {
columns := strings.Split(record, ",")
batch, err = api.KVBatch(sessionId, podName, tableName, columns)
if err != nil {
return "", err
}
err = batch.Put(collection.CSVHeaderKey, []byte(record), false, mem)
if err != nil {
failureCount++
readHeader = true
continue
}
readHeader = true
successCount++
continue
}
key := strings.Split(record, ",")[0]
err = batch.Put(key, []byte(record), false, mem)
if err != nil {
failureCount++
continue
}
successCount++
}
_, err = batch.Write("")
if err != nil {
return "", err
}
return fmt.Sprintf("csv file loaded in to kv table (%s) with total:%d, success: %d, failure: %d rows", tableName, rowCount, successCount, failureCount), nil
}
func KVSeek(podName, tableName, start, end string, limit int64) error {
_, err := api.KVSeek(sessionId, podName, tableName, start, end, limit)
return err
}
func KVSeekNext(podName, tableName string) (string, error) {
_, key, data, err := api.KVGetNext(sessionId, podName, tableName)
if err != nil {
return "", err
}
d := map[string]interface{}{}
d["key"] = key
d["value"] = data
resp, _ := json.Marshal(data)
return string(resp), nil
}
func DocNewStore(podName, tableName, simpleIndexes string, mutable bool) error {
indexes := make(map[string]collection.IndexType)
if simpleIndexes != "" {
idxs := strings.Split(simpleIndexes, ",")
for _, idx := range idxs {
nt := strings.Split(idx, "=")
if len(nt) != 2 {
return fmt.Errorf("invalid argument")
}
switch nt[1] {
case "string":
indexes[nt[0]] = collection.StringIndex
case "number":
indexes[nt[0]] = collection.NumberIndex
case "map":
indexes[nt[0]] = collection.MapIndex
case "list":
indexes[nt[0]] = collection.ListIndex
case "bytes":
default:
return fmt.Errorf("invalid indexType")
}
}
}
return api.DocCreate(sessionId, podName, tableName, indexes, mutable)
}
func DocList(podName string) (string, error) {
collections, err := api.DocList(sessionId, podName)
if err != nil {
return "", err
}
resp, _ := json.Marshal(collections)
return string(resp), err
}
func DocOpen(podName, tableName string) error {
return api.DocOpen(sessionId, podName, tableName)
}
func DocCount(podName, tableName, expression string) (string, error) {
count, err := api.DocCount(sessionId, podName, tableName, expression)
if err != nil {
return "", err
}
resp, _ := json.Marshal(count)
return string(resp), err
}
func DocDelete(podName, tableName string) error {
return api.DocDelete(sessionId, podName, tableName)
}
func DocFind(podName, tableName, expression string, limit int) (string, error) {
count, err := api.DocFind(sessionId, podName, tableName, expression, limit)
if err != nil {
return "", err
}
resp, _ := json.Marshal(count)
return string(resp), err
}
func DocEntryPut(podName, tableName, value string) error {
return api.DocPut(sessionId, podName, tableName, []byte(value))
}
type DocGetResponse struct {
Doc []byte `json:"doc"`
}
func DocEntryGet(podName, tableName, id string) (string, error) {
data, err := api.DocGet(sessionId, podName, tableName, id)
if err != nil {
return "", err
}
var getResponse DocGetResponse
getResponse.Doc = data
resp, _ := json.Marshal(getResponse)
return string(resp), err
}
func DocEntryDelete(podName, tableName, id string) error {
return api.DocDel(sessionId, podName, tableName, id)
}
func DocLoadJson(podName, tableName, filePath string) (string, error) {
_, err := os.Lstat(filePath)
if err != nil {
return "", err
}
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
reader := bufio.NewReader(f)
rowCount := 0
successCount := 0
failureCount := 0
docBatch, err := api.DocBatch(sessionId, podName, tableName)
for {
// read one row from csv (assuming
record, err := reader.ReadString('\n')
if err == io.EOF {
break
}
rowCount++
if err != nil {
failureCount++
continue
}
record = strings.TrimSuffix(record, "\n")
record = strings.TrimSuffix(record, "\r")
err = api.DocBatchPut(sessionId, podName, []byte(record), docBatch)
if err != nil {
failureCount++
continue
}
successCount++
}
err = api.DocBatchWrite(sessionId, podName, docBatch)
if err != nil {
return "", err
}
return fmt.Sprintf("json file loaded in to document db (%s) with total:%d, success: %d, failure: %d rows", tableName, rowCount, successCount, failureCount), nil
}
func DocIndexJson(podName, tableName, filePath string) error {
return api.DocIndexJson(sessionId, podName, tableName, filePath)
}