<commit_before>// Copyright 2013 <NAME>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package rtfhandler

import (
	"fmt"
	"github.com/andreaskoch/allmark2/common/config"
	"github.com/andreaskoch/allmark2/common/index"
	"github.com/andreaskoch/allmark2/common/logger"
	"github.com/andreaskoch/allmark2/common/paths"
	"github.com/andreaskoch/allmark2/common/route"
	"github.com/andreaskoch/allmark2/common/util/fsutil"
	"github.com/andreaskoch/allmark2/model"
	"github.com/andreaskoch/allmark2/ui/web/orchestrator"
	"github.com/andreaskoch/allmark2/ui/web/server/handler/errorhandler"
	"github.com/andreaskoch/allmark2/ui/web/server/handler/handlerutil"
	"github.com/gorilla/mux"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

func New(logger logger.Logger, config *config.Config, itemIndex *index.Index, patherFactory paths.PatherFactory) *RtfHandler {

	// error
	error404Handler := errorhandler.New(logger, config, itemIndex, patherFactory)

	return &RtfHandler{
		logger:          logger,
		itemIndex:       itemIndex,
		config:          config,
		patherFactory:   patherFactory,
		error404Handler: error404Handler,
	}
}

type RtfHandler struct {
	logger          logger.Logger
	itemIndex       *index.Index
	config          *config.Config
	patherFactory   paths.PatherFactory
	error404Handler *errorhandler.ErrorHandler
}

func (handler *RtfHandler) Func() func(w http.ResponseWriter, r *http.Request) {

	return func(w http.ResponseWriter, r *http.Request) {

		// get the path from the request variables
		vars := mux.Vars(r)
		path := vars["path"]

		// strip the "rtf" or ".rtf" suffix from the path
		path = strings.TrimSuffix(path, "rtf")
		path = strings.TrimSuffix(path, ".")

		// get the request route
		requestRoute, err := route.NewFromRequest(path)
		if err != nil {
			handler.logger.Error("Unable to get route from request. Error: %s", err.Error())
			return
		}

		// make sure the request body is closed
		defer r.Body.Close()

		// check if there is a item for the request
		item, found := handler.itemIndex.IsMatch(*requestRoute)
		if !found {

			// display a 404 error page
			error404Handler := handler.error404Handler.Func()
			error404Handler(w, r)
			return
		}

		// check if the a conversion tool has been supplied
		conversionToolIsConfigured := len(handler.config.Conversion.Tool) > 0
		if !conversionToolIsConfigured {

			handler.logger.Warn("Cannot convert item %q to RTF. No conversion tool configured.", item.String())

			// display a 404 error page
			error404Handler := handler.error404Handler.Func()
			error404Handler(w, r)
			return

		}

		// prepare a path provider which includes the hostname
		hostname := handlerutil.GetHostnameFromRequest(r)
		addressPrefix := fmt.Sprintf("http://%s/", hostname)
		pathProvider := handler.patherFactory.Absolute(addressPrefix)

		// assemble the item url
		sourceUrl := pathProvider.Path(orchestrator.GetTypedItemUrl(item, "print"))

		// get a target file path
		targetFile := getTempFileName("rtf-target") + ".rtf"

		// call pandoc
		args := []string{<commit_msg>RTF Handler Bug fix: remove double forward slashes from the url<commit_after>// Copyright 2013 <NAME>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package rtfhandler

import (
	"fmt"
	"github.com/andreaskoch/allmark2/common/config"
	"github.com/andreaskoch/allmark2/common/index"
	"github.com/andreaskoch/allmark2/common/logger"
	"github.com/andreaskoch/allmark2/common/paths"
	"github.com/andreaskoch/allmark2/common/route"
	"github.com/andreaskoch/allmark2/common/util/fsutil"
	"github.com/andreaskoch/allmark2/model"
	"github.com/andreaskoch/allmark2/ui/web/orchestrator"
	"github.com/andreaskoch/allmark2/ui/web/server/handler/errorhandler"
	"github.com/andreaskoch/allmark2/ui/web/server/handler/handlerutil"
	"github.com/gorilla/mux"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

func New(logger logger.Logger, config *config.Config, itemIndex *index.Index, patherFactory paths.PatherFactory) *RtfHandler {

	// error
	error404Handler := errorhandler.New(logger, config, itemIndex, patherFactory)

	return &RtfHandler{
		logger:          logger,
		itemIndex:       itemIndex,
		config:          config,
		patherFactory:   patherFactory,
		error404Handler: error404Handler,
	}
}

type RtfHandler struct {
	logger          logger.Logger
	itemIndex       *index.Index
	config          *config.Config
	patherFactory   paths.PatherFactory
	error404Handler *errorhandler.ErrorHandler
}

func (handler *RtfHandler) Func() func(w http.ResponseWriter, r *http.Request) {

	return func(w http.ResponseWriter, r *http.Request) {

		// get the path from the request variables
		vars := mux.Vars(r)
		path := vars["path"]

		// strip the "rtf" or ".rtf" suffix from the path
		path = strings.TrimSuffix(path, "rtf")
		path = strings.TrimSuffix(path, ".")

		// get the request route
		requestRoute, err := route.NewFromRequest(path)
		if err != nil {
			handler.logger.Error("Unable to get route from request. Error: %s", err.Error())
			return
		}

		// make sure the request body is closed
		defer r.Body.Close()

		// check if there is a item for the request
		item, found := handler.itemIndex.IsMatch(*requestRoute)
		if !found {

			// display a 404 error page
			error404Handler := handler.error404Handler.Func()
			error404Handler(w, r)
			return
		}

		// check if the a conversion tool has been supplied
		conversionToolIsConfigured := len(handler.config.Conversion.Tool) > 0
		if !conversionToolIsConfigured {

			handler.logger.Warn("Cannot convert item %q to RTF. No conversion tool configured.", item.String())

			// display a 404 error page
			error404Handler := handler.error404Handler.Func()
			error404Handler(w, r)
			return

		}

		// prepare a path provider which includes the hostname
		hostname := handlerutil.GetHostnameFromRequest(r)
		addressPrefix := fmt.Sprintf("http://%s", hostname)
		pathProvider := handler.patherFactory.Absolute(addressPrefix)

		// assemble the item url
		sourceUrl := pathProvider.Path(orchestrator.GetTypedItemUrl(item, "print"))

		// get a target file path
		targetFile := getTempFileName("rtf-target") + ".rtf"

		// call pandoc
		args := []string{
{'fraction_non_alphanumeric': 0.11607002050149819, 'fraction_numerical': 0.0160857908847185, 'mean_word_length': 3.82648401826484, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6874559', 'n_tokens_mistral': 2272, 'n_tokens_neox': 2062, 'n_words': 505}