view pkg/controllers/uploadedimports.go @ 3302:ec6163c6687d

'Historicise' gauges on import Gauge data sets will be updated or a new version will be inserted depending on temporal validity and a timestamp marking the last update in the RIS-Index of a data set. The trigger on date_info is removed because the value is actually an attribut coming from the RIS-Index. Gauge measurements and predictions are associated to the version with matching temporal validity. Bottlenecks are always associated to the actual version of the gauge, although this might change as soon as bottlenecks are 'historicised', too.
author Tom Gottfried <tom@intevation.de>
date Thu, 16 May 2019 18:41:43 +0200
parents 5222bfe5b4af
children 34623265eac1
line wrap: on
line source

// This is Free Software under GNU Affero General Public License v >= 3.0
// without warranty, see README.md and license for details.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// License-Filename: LICENSES/AGPL-3.0.txt
//
// Copyright (C) 2018 by via donau
//   – Österreichische Wasserstraßen-Gesellschaft mbH
// Software engineering by Intevation GmbH
//
// Author(s):
//  * Sascha L. Teichmann <sascha.teichmann@intevation.de>

package controllers

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"

	"gemma.intevation.de/gemma/pkg/auth"
	"gemma.intevation.de/gemma/pkg/common"
	"gemma.intevation.de/gemma/pkg/imports"
	"gemma.intevation.de/gemma/pkg/misc"
)

const maxUploadSize = 25 * 1024 * 1024

type BadUploadParameterError string

func importWaterwayProfiles() http.HandlerFunc {
	return uploadedImport(
		imports.WPJobKind,
		"wp.csv",
		func(req *http.Request, dir string) (imports.Job, error) {
			url := req.FormValue("url")
			if url == "" {
				return nil, BadUploadParameterError("missing 'url' parameter")
			}

			featureType := req.FormValue("feature-type")
			if featureType == "" {
				return nil, BadUploadParameterError("missing 'feature-type' parameter")
			}

			sortBy := req.FormValue("sort-by")

			var precision *float64
			if p := req.FormValue("precision"); p != "" {
				v, err := strconv.ParseFloat(p, 64)
				if err != nil {
					return nil, BadUploadParameterError(
						fmt.Sprintf("Invalid 'precision' parameter: %v", err))
				}
				precision = &v
			}

			user := req.FormValue("user")
			password := req.FormValue("password")

			return &imports.WaterwayProfiles{
				Dir:         dir,
				URL:         url,
				FeatureType: featureType,
				SortBy:      sortBy,
				Precision:   precision,
				User:        user,
				Password:    password,
			}, nil
		},
	)
}

func importApprovedGaugeMeasurements() http.HandlerFunc {
	return uploadedImport(
		imports.AGMJobKind,
		"agm.csv",
		func(req *http.Request, dir string) (imports.Job, error) {
			originator := req.FormValue("originator")
			if originator == "" {
				return nil, BadUploadParameterError("missing 'originator' parameter")
			}

			return &imports.ApprovedGaugeMeasurements{
				Dir:        dir,
				Originator: originator,
			}, nil
		},
	)
}

func importUploadedBottleneck() http.HandlerFunc {
	return uploadedImport(
		imports.UBNJobKind,
		"data.xml",
		func(req *http.Request, dir string) (imports.Job, error) {

			var tolerance float64
			if t := req.FormValue("tolerance"); t != "" {
				v, err := strconv.ParseFloat(t, 64)
				if err != nil {
					return nil, BadUploadParameterError(
						fmt.Sprintf("Invalid 'tolerance' parameter: %v", err))
				}
				tolerance = v
			}

			return &imports.UploadedBottleneck{Dir: dir, Tolerance: tolerance}, nil
		},
	)
}

func importUploadedFairwayAvailability() http.HandlerFunc {
	return uploadedImport(
		imports.UFAJobKind,
		"data.xml",
		func(_ *http.Request, dir string) (imports.Job, error) {
			return &imports.UploadedFairwayAvailability{Dir: dir}, nil
		},
	)
}

func importUploadedGaugeMeasurement() http.HandlerFunc {
	return uploadedImport(
		imports.UGMJobKind,
		"data.xml",
		func(_ *http.Request, dir string) (imports.Job, error) {
			return &imports.UploadedGaugeMeasurement{Dir: dir}, nil
		},
	)
}

func (bup BadUploadParameterError) Error() string {
	return string(bup)
}

func uploadedImport(
	kind imports.JobKind,
	fname string,
	create func(*http.Request, string) (imports.Job, error),
) http.HandlerFunc {

	return func(rw http.ResponseWriter, req *http.Request) {
		dir, err := misc.StoreUploadedFile(
			req,
			string(kind),
			fname,
			maxUploadSize)
		if err != nil {
			log.Printf("error: %v\n", err)
			http.Error(rw, "error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		job, err := create(req, dir)
		if err != nil {
			if err2 := os.RemoveAll(dir); err2 != nil {
				log.Printf("warn: %v\n", err2)
			}
			if err2, ok := err.(BadUploadParameterError); ok {
				http.Error(rw, string(err2), http.StatusBadRequest)
				return
			}
			log.Printf("error: %v\n", err)
			http.Error(rw, "error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		serialized, err := common.ToJSONString(job)
		if err != nil {
			log.Printf("error: %v\n", err)
			http.Error(rw, "error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		session, _ := auth.GetSession(req)

		sendEmail := req.FormValue("send-email") != ""

		jobID, err := imports.AddJob(
			kind,
			time.Time{}, // due
			nil,         // trys
			nil,         // retry wait
			session.User,
			sendEmail,
			serialized)

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

		log.Printf("info: added import #%d to queue\n", jobID)

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