/
plugin_common.go
95 lines (77 loc) · 2.28 KB
/
plugin_common.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
package interactor
import (
"context"
"errors"
"github.com/reearth/reearth/server/internal/usecase/gateway"
"github.com/reearth/reearth/server/internal/usecase/interfaces"
"github.com/reearth/reearth/server/internal/usecase/repo"
"github.com/reearth/reearth/server/pkg/id"
"github.com/reearth/reearth/server/pkg/plugin"
"github.com/reearth/reearth/server/pkg/plugin/pluginpack"
"github.com/reearth/reearthx/log"
"github.com/reearth/reearthx/rerror"
)
type pluginCommon struct {
pluginRepo repo.Plugin
propertySchemaRepo repo.PropertySchema
file gateway.File
pluginRegistry gateway.PluginRegistry
}
func (i *pluginCommon) SavePluginPack(ctx context.Context, p *pluginpack.Package) error {
read := false
id := p.Manifest.Plugin.ID()
for {
f, err := p.Files.Next()
if err != nil {
log.Errorfc(ctx, "failed to read a plugin file (%s): %s", id, err)
return interfaces.ErrInvalidPluginPackage
}
if f == nil {
break
}
read = true
if err := i.file.UploadPluginFile(ctx, p.Manifest.Plugin.ID(), f); err != nil {
return rerror.ErrInternalByWithContext(ctx, err)
}
}
if !read {
log.Errorfc(ctx, "no plugin files (%s)", id)
return interfaces.ErrInvalidPluginPackage
}
// save plugin and property schemas
if ps := p.Manifest.PropertySchemas(); len(ps) > 0 {
if err := i.propertySchemaRepo.SaveAll(ctx, ps); err != nil {
return err
}
}
if err := i.pluginRepo.Save(ctx, p.Manifest.Plugin); err != nil {
return err
}
return nil
}
func (i *pluginCommon) GetOrDownloadPlugin(ctx context.Context, pid id.PluginID) (*plugin.Plugin, error) {
if pid.IsNil() || pid.Equal(id.OfficialPluginID) {
return nil, rerror.ErrNotFound
}
if plugin, err := i.pluginRepo.FindByID(ctx, pid); err != nil && !errors.Is(err, rerror.ErrNotFound) {
return nil, err
} else if plugin != nil {
if plugin.ID().Scene() == nil {
if err := i.pluginRegistry.NotifyDownload(ctx, plugin.ID()); err != nil {
return nil, err
}
}
return plugin, nil
}
if !pid.Scene().IsNil() || i.pluginRegistry == nil {
return nil, rerror.ErrNotFound
}
pack, err := i.pluginRegistry.FetchPluginPackage(ctx, pid)
if err != nil {
return nil, err
}
if err := i.SavePluginPack(ctx, pack); err != nil {
return nil, err
}
return pack.Manifest.Plugin, nil
}