Skip to content
Snippets Groups Projects
groups.go 2.16 KiB
//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  tank is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with tank. If not, see <http://www.gnu.org/licenses/>.
//

package store

import (
	"errors"

	"github.com/coreos/bbolt"
)

func getGroupsBucket(tx *bolt.Tx) (groups *bolt.Bucket, err error) {
	groups = tx.Bucket([]byte(groupsBn))
	if groups == nil {
		err = errors.New("invalid store: groups bucket not found")
	}
	return
}

func getGroupBucket(tx *bolt.Tx, name string) (group *bolt.Bucket, err error) {
	var groups *bolt.Bucket
	groups, err = getGroupsBucket(tx)
	if err != nil {
		return
	}
	group = groups.Bucket([]byte(name))
	return
}

func newGroup(groups *bolt.Bucket, name string) (group *bolt.Bucket, err error) {
	if group, err = groups.CreateBucket([]byte(name)); err != nil {
		return
	}

	for _, bn := range groupBuckets {
		if _, err = group.CreateBucket([]byte(bn)); err != nil {
			return
		}
	}
	return
}

func (st *Store) createGroup(name string) (err error) {
	err = st.db.Update(func(tx *bolt.Tx) error {
		gb, err := getGroupsBucket(tx)
		if err != nil {
			return err
		}
		_, err = newGroup(gb, name)
		return err
	})
	return
}

func listGroups(tx *bolt.Tx) ([]string, error) {
	gb, err := getGroupsBucket(tx)
	if err != nil {
		return nil, err
	}

	var groups []string
	err = gb.ForEach(func(k, v []byte) error {
		groups = append(groups, string(k))
		return nil
	})
	return groups, err
}

func (st *Store) ListGroups() (groups []string, err error) {
	err = st.db.View(func(tx *bolt.Tx) error {
		groups, err = listGroups(tx)
		return err
	})
	return
}