github.com/code-to-go/safepool.lib@v0.0.0-20221205180519-ee25e63c226e/api/library/library.go (about) 1 package library 2 3 import ( 4 "bytes" 5 "strings" 6 "time" 7 8 "github.com/code-to-go/safepool.lib/core" 9 pool "github.com/code-to-go/safepool.lib/pool" 10 "github.com/code-to-go/safepool.lib/security" 11 "github.com/code-to-go/safepool.lib/transport" 12 "github.com/wailsapp/mimetype" 13 ) 14 15 type State int 16 17 const ( 18 StateSync State = iota 19 StateIn 20 StateOut 21 StateAlt 22 ) 23 24 // Document includes information about a file stored on the library. Most information refers on the synchronized state with the exchange 25 type Document struct { 26 Id uint64 `json:"id"` 27 Name string `json:"name"` 28 Size uint64 `json:"size"` 29 ModTime time.Time `json:"modTime"` 30 Author security.Identity `json:"author"` 31 ContentType string `json:"contentType"` 32 Hash []byte `json:"hash"` 33 34 // LocalPath is the location on the local storage where the document 35 LocalPath string `json:"localPath"` 36 // TmpPath is the location for temporary readonly documents 37 TmpPath string `json:"tmpPath"` 38 // HasChanges is true when the location on the local storage is different than the last available on the exchange 39 HasChanged bool `json:"hasChanged"` 40 } 41 42 type Library struct { 43 Pool *pool.Pool 44 } 45 46 func Get(p *pool.Pool) Library { 47 return Library{ 48 Pool: p, 49 } 50 } 51 52 func (l *Library) List(beforeId uint64, limit int) ([]Document, error) { 53 l.sync() 54 return sqlGetDocuments(l.Pool.Name, beforeId, limit) 55 } 56 57 func (l *Library) Download(id uint64, localPath string) error { 58 return nil 59 } 60 61 func (l *Library) Upload(id uint64) error { 62 return nil 63 } 64 65 func (l *Library) sync() { 66 l.Pool.Sync() 67 68 } 69 70 func (l *Library) TimeOffset(p *pool.Pool) time.Time { 71 return sqlGetOffset(p.Name) 72 } 73 74 func (l *Library) Accept(p *pool.Pool, head pool.Head) bool { 75 name := head.Name 76 if !strings.HasPrefix(name, "/library/") { 77 return false 78 } 79 80 var buf bytes.Buffer 81 err := p.Get(head.Id, &transport.Range{From: 0, To: 1024}, &buf) 82 if core.IsErr(err, "cannot get file to detect content type: %v") { 83 return false 84 } 85 86 contentType := mimetype.Detect(buf.Bytes()).String() 87 d := Document{ 88 Id: head.Id, 89 Name: head.Name, 90 ModTime: head.ModTime, 91 Size: uint64(head.Size), 92 Author: head.Author, 93 ContentType: contentType, 94 Hash: head.Hash, 95 } 96 97 return !core.IsErr(sqlSetDocument(p.Name, d), "cannot save document to db: %v") 98 }