1package server
2
3import (
4 "bytes"
5
6 "github.com/bluesky-social/indigo/carstore"
7 "github.com/haileyok/cocoon/internal/helpers"
8 "github.com/haileyok/cocoon/models"
9 "github.com/ipfs/go-cid"
10 cbor "github.com/ipfs/go-ipld-cbor"
11 "github.com/ipld/go-car"
12 "github.com/labstack/echo/v4"
13)
14
15func (s *Server) handleSyncGetRepo(e echo.Context) error {
16 ctx := e.Request().Context()
17 logger := s.logger.With("name", "handleSyncGetRepo")
18
19 did := e.QueryParam("did")
20 if did == "" {
21 return helpers.InputError(e, nil)
22 }
23
24 urepo, err := s.getRepoActorByDid(ctx, did)
25 if err != nil {
26 return err
27 }
28
29 rc, err := cid.Cast(urepo.Root)
30 if err != nil {
31 return err
32 }
33
34 hb, err := cbor.DumpObject(&car.CarHeader{
35 Roots: []cid.Cid{rc},
36 Version: 1,
37 })
38
39 buf := new(bytes.Buffer)
40
41 if _, err := carstore.LdWrite(buf, hb); err != nil {
42 logger.Error("error writing to car", "error", err)
43 return helpers.ServerError(e, nil)
44 }
45
46 var blocks []models.Block
47 if err := s.db.Raw(ctx, "SELECT * FROM blocks WHERE did = ? ORDER BY rev ASC", nil, urepo.Repo.Did).Scan(&blocks).Error; err != nil {
48 return err
49 }
50
51 for _, block := range blocks {
52 if _, err := carstore.LdWrite(buf, block.Cid, block.Value); err != nil {
53 return err
54 }
55 }
56
57 return e.Stream(200, "application/vnd.ipld.car", bytes.NewReader(buf.Bytes()))
58}