view pkg/controllers/imports.go @ 991:a301d240905f

Decoupled import job creation and job execution with a factory function. This is needed for persistence purposes.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 22 Oct 2018 10:45:17 +0200
parents 3c9ea8ab856a
children 75e65599ea52
line wrap: on
line source

package controllers

import (
	"bufio"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"gemma.intevation.de/gemma/pkg/auth"
	"gemma.intevation.de/gemma/pkg/config"
	"gemma.intevation.de/gemma/pkg/imports"
)

const (
	maxSoundingResultSize = 25 * 1024 * 1024
	soundingResultName    = "soundingresult"
)

func downloadSoundingResult(req *http.Request) (string, error) {

	f, _, err := req.FormFile(soundingResultName)
	if err != nil {
		return "", err
	}
	defer f.Close()

	dir, err := ioutil.TempDir(config.TmpDir(), soundingResultName)
	if err != nil {
		return "", err
	}

	o, err := os.Create(filepath.Join(dir, "sr.zip"))
	if err != nil {
		os.RemoveAll(dir)
		return "", err
	}

	out := bufio.NewWriter(o)

	if _, err = io.Copy(out, io.LimitReader(f, maxSoundingResultSize)); err != nil {
		o.Close()
		os.RemoveAll(dir)
		return "", err
	}

	if err = out.Flush(); err != nil {
		o.Close()
		os.RemoveAll(dir)
		return "", err
	}

	return dir, nil
}

func importSoundingResult(rw http.ResponseWriter, req *http.Request) {

	dir, err := downloadSoundingResult(req)
	if err != nil {
		log.Printf("error: %v\n", err)
		http.Error(rw, "error: "+err.Error(), http.StatusInternalServerError)
		return
	}

	session, _ := auth.GetSession(req)

	jobID := imports.AddJob(imports.SRJobKind, session.User, dir)
	log.Printf("Added job %d\n", jobID)

	result := struct {
		ID int64 `json:"id"`
	}{
		ID: jobID,
	}
	SendJSON(rw, http.StatusCreated, &result)
}