package registry import ( "bytes" "encoding/gob" "fmt" "git.capotej.com/capotej/communique/config" "git.capotej.com/capotej/communique/models" "git.capotej.com/capotej/communique/views" ) type Handler struct { handlerCfg config.Handler } // TODO rename to controller and controller.go type Registry struct { cfg config.Config persister *models.Persister handlerMap map[string]Handler } func NewRegistry(cfg config.Config, persister *models.Persister) *Registry { reg := Registry{cfg: cfg, persister: persister} reg.handlerMap = make(map[string]Handler) for _, v := range cfg.Handlers { reg.handlerMap[fqn(v.Name, cfg.Domain)] = Handler{handlerCfg: v} } return ® } func (r *Registry) Profile(name string) (map[string]interface{}, error) { handler := r.findByName(name) if handler == nil { return nil, nil } return views.RenderProfile(handler.handlerCfg.Name, r.cfg.Domain) } func (r *Registry) Outbox(name string) (map[string]interface{}, error) { handler := r.findByName(name) if handler == nil { return nil, nil } aso := models.NewOutboxItem(handler.handlerCfg) totalItems, err := r.persister.Count(aso) if err != nil { return nil, err } return views.RenderOutbox(handler.handlerCfg.Name, r.cfg.Domain, totalItems) } func (r *Registry) OutboxCollection(name string) (map[string]interface{}, error) { handler := r.findByName(name) if handler == nil { return nil, nil } aso := models.NewOutboxItem(handler.handlerCfg) page, err := r.persister.Collect(aso) if err != nil { return nil, err } var outboxItems []models.OutboxItem for _, v := range page { buf := bytes.NewBuffer(v) dec := gob.NewDecoder(buf) var outboxItem models.OutboxItem err = dec.Decode(&outboxItem) if err != nil { return nil, err } outboxItems = append(outboxItems, outboxItem) } return views.RenderOutboxCollection(handler.handlerCfg.Name, r.cfg.Domain, outboxItems) } func (r *Registry) Activity(name, id string) (map[string]interface{}, error) { handler := r.findByName(name) if handler == nil { return nil, nil } lookup := models.NewOutboxItem(handler.handlerCfg) lookup.Id = []byte(id) result, err := r.persister.Find(lookup) if err != nil { return nil, err } buf := bytes.NewBuffer(result) dec := gob.NewDecoder(buf) var outboxItem models.OutboxItem err = dec.Decode(&outboxItem) if err != nil { return nil, err } return views.RenderActivity(handler.handlerCfg.Name, r.cfg.Domain, outboxItem) } func (r *Registry) WebfingerResource(fqn string) (*views.WebfingerResource, error) { handler := r.findByFQN(fqn) if handler == nil { handler = r.findByFQN("acct:" + fqn) } if handler == nil { return nil, nil } return views.RenderWebfingerResource(handler.handlerCfg.Name, r.cfg.Domain) } func fqn(name, domain string) string { return fmt.Sprintf("acct:%s@%s", name, domain) } func (r *Registry) findByFQN(fqn string) *Handler { handler, ok := r.handlerMap[fqn] if !ok { return nil } return &handler } func (r *Registry) findByName(name string) *Handler { return r.findByFQN(fqn(name, r.cfg.Domain)) }