summaryrefslogtreecommitdiff
path: root/cmd/getallhocrs/main.go
blob: 696a5fcecc1e07cdd23b53a2dc69e49c36b8bc9e (plain)
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
// Copyright 2020 Nick White.
// Use of this source code is governed by the GPLv3
// license that can be found in the LICENSE file.

// getallhocrs downloads every 'best' file from a set of OCRed books
// stored on cloud infrastructure
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strings"

	"rescribe.xyz/bookpipeline"
)

const usage = `Usage: getallhocrs

Downloads every 'hocr' file.
`

type Pipeliner interface {
	Init() error
	Download(bucket string, key string, fn string) error
	ListObjects(bucket string, prefix string) ([]string, error)
	ListObjectPrefixes(bucket string) ([]string, error)
	Log(v ...interface{})
	WIPStorageId() string
}

func main() {
	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(), usage)
		flag.PrintDefaults()
	}
	flag.Parse()

	verboselog := log.New(os.Stdout, "", log.LstdFlags)

	var conn Pipeliner
	conn = &bookpipeline.AwsConn{Region: "eu-west-2", Logger: verboselog}

	err := conn.Init()
	if err != nil {
		log.Fatalln("Error setting up cloud connection:", err)
	}

	conn.Log("Getting list of all books")
	prefixes, err := conn.ListObjectPrefixes(conn.WIPStorageId())
	if err != nil {
		log.Fatalln("Failed to get list of prefixes", err)
	}

	for _, p := range prefixes {
		conn.Log("Getting list of files for book", p)
		objs, err := conn.ListObjects(conn.WIPStorageId(), p)
		if err != nil {
			log.Fatalln("Failed to get list of files", err)
		}
		err = os.MkdirAll(p, 0755)
		if err != nil {
			log.Fatalln("Failed to make directory", err)
		}
		conn.Log("Downloading hocrs from book", p)
		for _, o := range objs {
			if !strings.HasSuffix(o, ".hocr") {
				continue
			}
			// skip already downloaded items
			_, err = os.Stat(o)
			if err == nil || os.IsExist(err) {
				log.Println("  Skipping already complete download of", o)
				continue
			}
			log.Println("  Downloading", o)
			err = conn.Download(conn.WIPStorageId(), o, o)
			if err != nil {
				log.Fatalln("Failed to download file", o, err)
			}
		}
	}
}