GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
5.1 KiB

  1. package file
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "errors"
  7. "io"
  8. "strconv"
  9. "time"
  10. "git.aiterp.net/rpdata/api/internal/store"
  11. "github.com/globalsign/mgo"
  12. "github.com/globalsign/mgo/bson"
  13. )
  14. var fileCollection *mgo.Collection
  15. // A File is a record of a file stored in the Space.
  16. type File struct {
  17. ID string `bson:"_id" json:"id"`
  18. Time time.Time `bson:"time" json:"time"`
  19. Kind string `bson:"kind" json:"kind"`
  20. Public bool `bson:"public" json:"public"`
  21. Name string `bson:"name" json:"name"`
  22. MimeType string `bson:"mimeType" json:"mimeType"`
  23. Size int64 `bson:"size" json:"size"`
  24. Author string `bson:"author" json:"author"`
  25. URL string `bson:"url,omitempty" json:"url,omitempty"`
  26. }
  27. // Edit edits the file, changing up to both the two mutable properties
  28. func (file *File) Edit(name *string, public *bool) error {
  29. changes := bson.M{}
  30. changedFile := *file
  31. if name != nil && *name != file.Name {
  32. changes["name"] = *name
  33. changedFile.Name = *name
  34. }
  35. if public != nil && *public != file.Public {
  36. changes["public"] = *public
  37. changedFile.Public = *public
  38. }
  39. if len(changes) == 0 {
  40. return nil
  41. }
  42. err := fileCollection.UpdateId(file.ID, bson.M{"$set": changes})
  43. if err != nil {
  44. return err
  45. }
  46. *file = changedFile
  47. return nil
  48. }
  49. // Delete removes the file information from the database, and deletes the file.
  50. func (file *File) Delete() error {
  51. err := fileCollection.RemoveId(file.ID)
  52. if err != nil {
  53. return err
  54. }
  55. if file.Kind == "upload" {
  56. err = store.RemoveFile("files", file.ID)
  57. if err != nil {
  58. return err
  59. }
  60. }
  61. file.URL = ""
  62. return nil
  63. }
  64. // Insert manually inserts file information into the database. This should never, ever be API accessible
  65. func Insert(name, kind, mimeType, author string, time time.Time, size int64, url string) (File, error) {
  66. file := File{
  67. ID: makeFileID(),
  68. Kind: kind,
  69. Time: time,
  70. Public: false,
  71. Author: author,
  72. Name: name,
  73. MimeType: mimeType,
  74. Size: size,
  75. URL: url,
  76. }
  77. err := fileCollection.Insert(file)
  78. if err != nil {
  79. return File{}, err
  80. }
  81. return file, nil
  82. }
  83. // Upload adds a file to the space.
  84. func Upload(ctx context.Context, name, mimeType, author string, size int64, input io.Reader) (File, error) {
  85. if name == "" {
  86. date := time.Now().UTC().Format("Jan 02 2006 15:04:05 MST")
  87. name = "Unnamed file (" + date + ")"
  88. }
  89. if mimeType == "" {
  90. mimeType = "binary/octet-stream"
  91. }
  92. id := makeFileID()
  93. path, err := store.UploadFile(ctx, "files", id, mimeType, input, size)
  94. if err != nil {
  95. return File{}, err
  96. }
  97. file := File{
  98. ID: id,
  99. Kind: "upload",
  100. Time: time.Now(),
  101. Public: false,
  102. Author: author,
  103. Name: name,
  104. MimeType: mimeType,
  105. Size: size,
  106. URL: store.URLFromPath(path),
  107. }
  108. err = fileCollection.Insert(file)
  109. if err != nil {
  110. return File{}, err
  111. }
  112. return file, nil
  113. }
  114. // FindID finds a file by ID
  115. func FindID(id string) (File, error) {
  116. file := File{}
  117. err := fileCollection.FindId(id).One(&file)
  118. if err != nil {
  119. return File{}, err
  120. }
  121. return file, nil
  122. }
  123. // FindName finds a file by kind, name and author
  124. func FindName(kind string, name string, author string) (File, error) {
  125. query := bson.M{"kind": kind, "name": name, "author": author}
  126. file := File{}
  127. err := fileCollection.Find(query).One(&file)
  128. if err != nil {
  129. return File{}, err
  130. }
  131. return file, nil
  132. }
  133. // List lists files according to the standard lookup. By default it's just the author's own files,
  134. // but if `public` is true it will alos include files made public by other authors. If `mimeTypes` contains
  135. // any, it will limit the results to that. If `author` is empty, it will only list public files
  136. func List(author string, public bool, mimeTypes []string) ([]File, error) {
  137. query := bson.M{}
  138. if author != "" {
  139. if public {
  140. query["$or"] = []bson.M{
  141. bson.M{"author": author},
  142. bson.M{"public": true},
  143. }
  144. } else {
  145. query["author"] = author
  146. }
  147. } else {
  148. if !public {
  149. return nil, errors.New("No author specified, and public is unset")
  150. }
  151. query["public"] = true
  152. }
  153. if len(mimeTypes) > 0 {
  154. query["mimeTypes"] = bson.M{"$in": mimeTypes}
  155. }
  156. return listFiles(query)
  157. }
  158. func listFiles(query interface{}) ([]File, error) {
  159. list := make([]File, 0, 32)
  160. err := fileCollection.Find(query).Sort("-time").All(&list)
  161. if err != nil {
  162. return nil, err
  163. }
  164. return list, nil
  165. }
  166. // makeFileID makes a random file ID that's 32 characters long
  167. func makeFileID() string {
  168. result := "F" + strconv.FormatInt(time.Now().UnixNano(), 36)
  169. offset := 0
  170. data := make([]byte, 32)
  171. rand.Read(data)
  172. for len(result) < 32 {
  173. result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36)
  174. offset += 8
  175. if offset >= 32 {
  176. rand.Read(data)
  177. offset = 0
  178. }
  179. }
  180. return result[:32]
  181. }
  182. func init() {
  183. store.HandleInit(func(db *mgo.Database) {
  184. fileCollection = db.C("file.headers")
  185. fileCollection.EnsureIndexKey("author")
  186. fileCollection.EnsureIndexKey("public")
  187. fileCollection.EnsureIndexKey("kind", "name", "author")
  188. fileCollection.EnsureIndexKey("author", "public")
  189. fileCollection.EnsureIndexKey("kind")
  190. })
  191. }