github.com/readium/readium-lcp-server@v0.0.0-20240101192032-6e95190e99f1/frontend/webrepository/webrepository.go (about)

     1  // Copyright (c) 2020 Readium Foundation
     2  // Use of this source code is governed by a BSD-style license
     3  // that can be found in the LICENSE file exposed on Github (readium) in the project repository.
     4  
     5  package webrepository
     6  
     7  import (
     8  	"errors"
     9  	"io/ioutil"
    10  	"os"
    11  	"path"
    12  
    13  	"github.com/readium/readium-lcp-server/config"
    14  )
    15  
    16  // ErrNotFound error trown when repository is not found
    17  var ErrNotFound = errors.New("Repository not found")
    18  
    19  // WebRepository interface for repository db interaction
    20  type WebRepository interface {
    21  	GetMasterFile(name string) (RepositoryFile, error)
    22  	GetMasterFiles() func() (RepositoryFile, error)
    23  }
    24  
    25  // RepositoryFile struct defines a file stored in a repository
    26  type RepositoryFile struct {
    27  	Name string `json:"name"`
    28  	Path string
    29  }
    30  
    31  // RepositoryManager contains all repository definitions
    32  type RepositoryManager struct {
    33  	MasterRepositoryPath    string
    34  	EncryptedRepositoryPath string
    35  }
    36  
    37  // GetMasterFile returns a specific repository file
    38  func (repManager RepositoryManager) GetMasterFile(name string) (RepositoryFile, error) {
    39  	var filePath = path.Join(repManager.MasterRepositoryPath, name)
    40  
    41  	if _, err := os.Stat(filePath); err == nil {
    42  		// File exists
    43  		var repFile RepositoryFile
    44  		repFile.Name = name
    45  		repFile.Path = filePath
    46  		return repFile, err
    47  	}
    48  
    49  	return RepositoryFile{}, ErrNotFound
    50  }
    51  
    52  // GetMasterFiles returns all filenames from the master repository
    53  func (repManager RepositoryManager) GetMasterFiles() func() (RepositoryFile, error) {
    54  	files, err := ioutil.ReadDir(repManager.MasterRepositoryPath)
    55  	var fileIndex int
    56  
    57  	if err != nil {
    58  		return func() (RepositoryFile, error) { return RepositoryFile{}, err }
    59  	}
    60  
    61  	return func() (RepositoryFile, error) {
    62  		var repFile RepositoryFile
    63  
    64  		for fileIndex < len(files) {
    65  			file := files[fileIndex]
    66  			repFile.Name = file.Name()
    67  			fileIndex++
    68  			return repFile, err
    69  		}
    70  
    71  		return repFile, ErrNotFound
    72  	}
    73  }
    74  
    75  // Init returns a WebPublication interface (db interaction)
    76  func Init(config config.FrontendServerInfo) (i WebRepository, err error) {
    77  	i = RepositoryManager{config.MasterRepository, config.EncryptedRepository}
    78  	return
    79  }