sync.go 8.61 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10
package liber

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
11
	"net/url"
ale's avatar
ale committed
12 13
	"os"
	"path/filepath"
14
	"strings"
ale's avatar
ale committed
15
	"sync"
ale's avatar
ale committed
16
	"time"
ale's avatar
ale committed
17 18 19 20 21 22 23 24 25
)

const (
	diffChunkSize     = 1000
	uploadConcurrency = 3
)

type SyncClient interface {
	DiffRequest(*diffRequest) (*diffResponse, error)
26
	SendBook(*Book, *FileStorage, []*File) error
ale's avatar
ale committed
27 28 29 30 31
}

type remoteServer struct {
	client    *http.Client
	remoteURL string
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
	username  string
	password  string
}

func extractAuth(uri string) (string, string, string) {
	parsed, err := url.Parse(uri)
	if err != nil {
		return uri, "", ""
	}
	if strings.Contains("@", parsed.Host) {
		hostParts := strings.SplitN(parsed.Host, "@", 2)
		parsed.Host = hostParts[1]
		authParts := strings.SplitN(hostParts[0], ":", 2)
		if len(authParts) == 2 {
			return parsed.String(), authParts[0], authParts[1]
		}
	}
	return uri, "", ""
ale's avatar
ale committed
50 51 52
}

func NewRemoteServer(remoteURL string) *remoteServer {
53
	remoteURL, username, password := extractAuth(remoteURL)
ale's avatar
ale committed
54 55
	return &remoteServer{
		remoteURL: remoteURL,
56 57
		username:  username,
		password:  password,
ale's avatar
ale committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
		client:    &http.Client{},
	}
}

// DiffRequest sends a diffRequest to the remote server.
func (r *remoteServer) DiffRequest(diffreq *diffRequest) (*diffResponse, error) {
	var body bytes.Buffer
	if err := json.NewEncoder(&body).Encode(diffreq); err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", r.remoteURL+"/api/sync/diff", &body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
74 75 76
	if r.username != "" {
		req.SetBasicAuth(r.username, r.password)
	}
ale's avatar
ale committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	resp, err := r.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("HTTP error: %s", resp.Status)
	}

	var diffresp diffResponse
	if err := json.NewDecoder(resp.Body).Decode(&diffresp); err != nil {
		return nil, err
	}

	return &diffresp, nil
}

ale's avatar
ale committed
94
func addFilePart(w *multipart.Writer, varname, filename, mimeFilename string) error {
ale's avatar
ale committed
95 96 97 98 99 100
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

ale's avatar
ale committed
101
	part, err := w.CreateFormFile(varname, mimeFilename)
ale's avatar
ale committed
102 103 104 105 106 107 108 109 110 111 112
	if err != nil {
		return err
	}

	if _, err := io.Copy(part, file); err != nil {
		return err
	}
	return nil
}

// SendBook uploads a book to the remote server.
113
func (r *remoteServer) SendBook(book *Book, storage *FileStorage, files []*File) error {
ale's avatar
ale committed
114 115 116 117 118
	// Create a multipart request with the JSON-encoded metadata
	// and the actual file contents as two separate mime/multipart
	// sections.
	var body bytes.Buffer
	w := multipart.NewWriter(&body)
ale's avatar
ale committed
119

ale's avatar
ale committed
120 121 122 123 124
	part, err := w.CreateFormFile("meta", "meta.json")
	if err := json.NewEncoder(part).Encode(book.Metadata); err != nil {
		return err
	}

ale's avatar
ale committed
125 126 127
	for i, f := range files {
		varname := fmt.Sprintf("book%d", i)
		filename := fmt.Sprintf("%d%s", book.Id, f.FileType)
128
		if err := addFilePart(w, varname, storage.Abs(f.Path), filename); err != nil {
ale's avatar
ale committed
129 130 131
			w.Close()
			return err
		}
ale's avatar
ale committed
132 133 134
	}

	if book.CoverPath != "" {
135
		if err := addFilePart(w, "cover", storage.Abs(book.CoverPath), "cover.jpg"); err != nil {
ale's avatar
ale committed
136 137 138 139 140 141 142 143 144 145 146 147 148
			w.Close()
			return err
		}
	}

	if err := w.Close(); err != nil {
		return err
	}

	req, err := http.NewRequest("POST", r.remoteURL+"/api/sync/upload", &body)
	if err != nil {
		return err
	}
149 150 151 152
	req.Header.Set("Content-Type", w.FormDataContentType())
	if r.username != "" {
		req.SetBasicAuth(r.username, r.password)
	}
ale's avatar
ale committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

	resp, err := r.client.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("HTTP error: %s", resp.Status)
	}

	return nil
}

type uniqueIds struct {
	Id     string
	Unique []string
}

type diffRequest struct {
	Candidates []uniqueIds
}

type diffResponse struct {
	Missing []string
}

func (db *Database) findMissing(srv SyncClient) chan string {
	missing := make(chan string, diffChunkSize)

	doRequest := func(req *diffRequest) {
		resp, err := srv.DiffRequest(req)
		if err != nil {
			log.Printf("DiffRequest(): %v", err)
		} else {
			for _, id := range resp.Missing {
				missing <- id
			}
		}
	}

	go func() {
		n := 0
		var req diffRequest
196 197 198
		iter := db.Scan(BookBucket)
		defer iter.Close()
		for iter.Next() {
ale's avatar
ale committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
			var book Book
			if err := iter.Value(&book); err != nil {
				continue
			}
			req.Candidates = append(req.Candidates, uniqueIds{
				Id:     book.Id.String(),
				Unique: book.Metadata.Uniques(),
			})
			n++
			if n%diffChunkSize == 0 {
				doRequest(&req)
				req.Candidates = nil
			}
		}
		if req.Candidates != nil {
			doRequest(&req)
		}
		close(missing)
	}()

	return missing
}

// Sync the local database with a remote one. This is a one-way
// synchronization: files missing on the remote side will be uploaded
// to it.
225
func (db *Database) Sync(storage *FileStorage, remote SyncClient) error {
ale's avatar
ale committed
226 227 228 229 230 231 232 233
	var wg sync.WaitGroup

	ch := db.findMissing(remote)

	for i := 0; i < uploadConcurrency; i++ {
		wg.Add(1)
		go func() {
			for id := range ch {
ale's avatar
ale committed
234 235 236
				bookid := ParseID(id)
				if book, err := db.GetBook(bookid); err == nil {
					if files, err := db.GetBookFiles(bookid); err == nil {
ale's avatar
ale committed
237
						log.Printf("uploading %s", book.String())
238
						if err := remote.SendBook(book, storage, files); err != nil {
ale's avatar
ale committed
239
							log.Printf("SendBook(%s): %v", id, err)
ale's avatar
ale committed
240
						}
ale's avatar
ale committed
241 242 243 244 245 246 247 248 249 250 251 252
					}
				}
			}
			wg.Done()
		}()
	}
	wg.Wait()
	return nil
}

type syncServer struct {
	db      *Database
253
	storage *RWFileStorage
ale's avatar
ale committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
}

func (l *syncServer) handleDiffRequest(w http.ResponseWriter, req *http.Request) {
	if req.Header.Get("Content-Type") != "application/json" {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	var diffreq diffRequest
	if err := json.NewDecoder(req.Body).Decode(&diffreq); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var resp diffResponse
	for _, c := range diffreq.Candidates {
ale's avatar
ale committed
270 271 272
		// Search for matches in the database by looking for
		// unique ids.
		if _, err := l.db.Find(c.Unique); err != nil {
ale's avatar
ale committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
			resp.Missing = append(resp.Missing, c.Id)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(&resp)
}

func (l *syncServer) handleSyncUpload(w http.ResponseWriter, req *http.Request) {
	mf, _, err := req.FormFile("meta")
	if err != nil {
		log.Printf("request with no 'meta' field")
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var md Metadata
	if err := json.NewDecoder(mf).Decode(&md); err != nil {
		log.Printf("error decoding metadata: %v", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Check again that we don't have this book.
ale's avatar
ale committed
297
	if _, err := l.db.Find(md.Uniques()); err == nil {
ale's avatar
ale committed
298 299 300 301 302 303 304 305 306 307 308 309
		log.Printf("attempt to upload duplicate: %#v", &md)
		http.Error(w, "Duplicate", http.StatusConflict)
		return
	}

	// Create a new Book with a local ID and path.
	bookid := NewID()
	book := &Book{
		Id:       bookid,
		Metadata: &md,
	}

ale's avatar
ale committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
	// Save the file data to our local storage.
	for i := 0; i < 10; i++ {
		// Use a temporary file, we'll know the right
		// extension to use only after having parsed the
		// file's MIME header.
		tmppath := l.storage.Path(fmt.Sprintf("%d.%d.tmp", bookid, i))
		varname := fmt.Sprintf("book%d", i)
		size, hdr, err := savePart(req, varname, l.storage, tmppath)
		if err == http.ErrMissingFile {
			break
		} else if err != nil {
			log.Printf("error saving local file: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		filetype := filepath.Ext(hdr.Filename)
		path := l.storage.Path(fmt.Sprintf("%d.%d%s", bookid, i, filetype))
		if err := l.storage.Rename(tmppath, path); err != nil {
			log.Printf("error moving local file: %v", err)
		}

		file := &File{
			Path:     path,
			FileType: filetype,
			Mtime:    time.Now(),
			Size:     size,
			Id:       bookid,
		}
		if err := l.db.PutFile(file); err != nil {
			log.Printf("error saving file to the database: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
ale's avatar
ale committed
343 344 345
	}

	// If the request contains a cover image, save that as well.
ale's avatar
ale committed
346 347
	coverPath := l.storage.Path(fmt.Sprintf("%s.cover.png", book.Id))
	if _, _, err := savePart(req, "cover", l.storage, coverPath); err == nil {
ale's avatar
ale committed
348 349 350 351 352 353 354 355 356 357 358 359 360
		book.CoverPath = coverPath
	}

	if err := l.db.PutBook(book); err != nil {
		log.Printf("error saving book to the database: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Empty 200 OK response.
	w.WriteHeader(200)
}

361
func savePart(req *http.Request, fieldname string, storage *RWFileStorage, outname string) (int64, *multipart.FileHeader, error) {
ale's avatar
ale committed
362
	f, hdr, err := req.FormFile(fieldname)
ale's avatar
ale committed
363
	if err != nil {
ale's avatar
ale committed
364
		return 0, nil, err
ale's avatar
ale committed
365 366 367 368
	}

	outf, err := storage.Create(outname)
	if err != nil {
ale's avatar
ale committed
369
		return 0, nil, err
ale's avatar
ale committed
370 371 372
	}
	defer outf.Close()

ale's avatar
ale committed
373 374 375
	n, err := io.Copy(outf, f)
	if err != nil {
		return 0, nil, err
ale's avatar
ale committed
376 377
	}

ale's avatar
ale committed
378
	return n, hdr, nil
ale's avatar
ale committed
379
}