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.

83 lines
1.7 KiB

  1. package files
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "strconv"
  6. "time"
  7. "git.aiterp.net/rpdata/api/internal/store"
  8. "git.aiterp.net/rpdata/api/models"
  9. "github.com/globalsign/mgo"
  10. )
  11. var collection *mgo.Collection
  12. func find(query interface{}) (models.File, error) {
  13. file := models.File{}
  14. err := collection.Find(query).One(&file)
  15. if err != nil {
  16. return models.File{}, err
  17. }
  18. return file, nil
  19. }
  20. func list(query interface{}) ([]models.File, error) {
  21. list := make([]models.File, 0, 32)
  22. err := collection.Find(query).Sort("-time").All(&list)
  23. if err != nil {
  24. return nil, err
  25. }
  26. return list, nil
  27. }
  28. // makeID makes a random file ID that's 32 characters long
  29. func makeID() string {
  30. result := "F" + strconv.FormatInt(time.Now().UnixNano(), 36)
  31. offset := 0
  32. data := make([]byte, 32)
  33. rand.Read(data)
  34. for len(result) < 32 {
  35. result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36)
  36. offset += 8
  37. if offset >= 32 {
  38. rand.Read(data)
  39. offset = 0
  40. }
  41. }
  42. return result[:32]
  43. }
  44. func init() {
  45. store.HandleInit(func(db *mgo.Database) {
  46. collection = db.C("file.headers")
  47. collection.EnsureIndexKey("author")
  48. collection.EnsureIndexKey("public")
  49. collection.EnsureIndexKey("kind", "name", "author")
  50. collection.EnsureIndexKey("author", "public")
  51. collection.EnsureIndexKey("kind")
  52. })
  53. }
  54. var allowdMimeTypes = map[string]bool{
  55. "": false,
  56. "image/jpeg": true,
  57. "image/png": true,
  58. "image/gif": true,
  59. "image/tiff": true,
  60. "image/tga": true,
  61. "text/plain": true,
  62. "application/json": true,
  63. "application/pdf": false,
  64. "binary/octet-stream": false,
  65. "video/mp4": false,
  66. "audio/mp3": false,
  67. }