EgnyteWebHookHandler/main/main.go

193 lines
7.0 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"path/filepath"
"regexp"
"strings"
2023-12-04 15:03:40 -07:00
"time"
"github.com/gorilla/mux"
)
func MPE_IsProject(input map[string]json.RawMessage) (projectnumber string, project_name string) {
// this will attempt to extract a project number from the "targetpath" element. If it's able to determine a folder contains a project number, we'll return it.
var path_data map[string]json.RawMessage
project_regex, _ := regexp.Compile(`(^[0-9]{1,3})`) // regex to match against
err := json.Unmarshal((input["data"]), &path_data)
if err != nil {
log.Fatal(err)
fmt.Println("oops")
return
}
path := string(path_data["targetPath"])
split_path, _ := filepath.Split(path)
split_path = filepath.Clean(split_path)
separated_path := strings.Split(split_path, "/") //turn this into an array (slice?) to parse
var sb strings.Builder
// iterate through the path_data map. We want to find all strings that start with a number.
for _, value := range separated_path {
matched := project_regex.MatchString(value)
// matched, err := regexp.MatchString(`(^[0-9]{1,3})`, value)
// if err != nil {
// log.Fatal(err)
// fmt.Println("oops")
// return "RegexError", "RegExError"
// }
if matched {
// if we match the Regex above, write values to SB. This will give us a string like "73|10 Office Of Somone|153 HelpMe|002 Phase 2"
sb.WriteString(value + "|")
}
} // end of loop
// now to assemble project number and project name from the resulting values...
project_text := sb.String()
project_slice := strings.Split(project_text, "|")
// first value should be a digit, if not this can't be a project
isProject, _ := regexp.MatchString(`(^[0-9])`, project_slice[0])
if isProject {
project_regex, _ := regexp.Compile(`(^[0-9]{1,3})`) // regex to match against
regex_tidy_string, _ := regexp.Compile(`[-_]+|^\s`) //regex to tidy up folder paths
client_section := regex_tidy_string.ReplaceAllString(project_slice[1], "") // remove fancy chars from Client Name
project_section := regex_tidy_string.ReplaceAllString(project_regex.ReplaceAllString(project_slice[2], ""), " ") // remove leading-digits
project_section_digits := strings.Split(regex_tidy_string.ReplaceAllString(project_slice[2], " "), " ") //split on space for MOST file folders...
sb.Reset() // reset string builder so I can use it again!
sb.WriteString(project_slice[0]) // 73
sb.WriteString(strings.Split(client_section, " ")[0] + "-") // 7310 -- Client Name
sb.WriteString(project_section_digits[0]) // 7310-10
// do we have a third section of the project number?
project_third := strings.Split(project_slice[3], " ")[0]
project_third_match, _ := regexp.MatchString(`(^[0-9]{1,3})`, project_third)
if project_third_match {
// if we have a third section, then add another section to the project number, and append to the project name
third_project_name := project_regex.ReplaceAllString(project_slice[3], "") // 7310-10-153
project_name = project_section + "-" + regex_tidy_string.ReplaceAllString(third_project_name, "") // remove project digits from beginning of string and append
project_third = regex_tidy_string.ReplaceAllString(project_third, " ")
sb.WriteString("-" + project_third)
} else {
project_name = project_section // remove project digits from beginning of string
}
projectnumber = sb.String() // I should now have a project number!
} else {
return "NotAProject", "NoPath"
}
return
}
func MPE_ValidateForward(in map[string]json.RawMessage) bool {
// decode targetPath data. Will return TRUE if the last section of the path contains "External Share" or "ExternalShare". This would indicate that we SHOULD forward this request onward.
var path_data map[string]json.RawMessage
err := json.Unmarshal((in["data"]), &path_data)
if err != nil {
log.Fatal(err)
fmt.Println("oops")
return false
}
path := string(path_data["targetPath"])
split_path, last := filepath.Split(path)
split_path = filepath.Clean(split_path)
matched, err := regexp.MatchString(`ExternalShare|External Share`, last)
return matched
}
func readDataStream(resp http.ResponseWriter, request *http.Request) {
// reqBody, _ := io.ReadAll(request.Body)
body_string, _ := io.ReadAll(request.Body)
fmt.Println(string(body_string)) // debug code to show JASON data coming in
var request_body map[string]json.RawMessage
err := json.Unmarshal(body_string, &request_body)
if err != nil {
log.Fatal(err)
fmt.Println("oops")
return
}
var MPE_ShouldFoward = MPE_ValidateForward(request_body)
var MPE_ProjectNumber, MPE_ProjectName = MPE_IsProject(request_body)
// TODO: Fix - json: cannot unmarshal array into Go value of type map[string]json.RawMessage error.
// TODO: Collect EventID, JSON Content, and return values into data object to be logged to screen. Validate data visually for a bit against "live" webhook data.
fmt.Println(MPE_ShouldFoward, MPE_ProjectNumber, MPE_ProjectName)
// TODO: Once Data validation / Struct is built, pass data off to next Webhook URL for processing.
}
2023-12-04 15:03:40 -07:00
func HealthCheck(resp http.ResponseWriter, request *http.Request) {
var t = time.Now().String()
var MessageText = t + ": Health Check from " + request.RemoteAddr
// reqBody, _ := io.ReadAll(request.Body)
2023-12-04 15:03:40 -07:00
fmt.Println(http.StatusOK, MessageText)
resp.WriteHeader(http.StatusOK)
resp.Write([]byte(MessageText))
}
2023-12-12 13:29:55 -07:00
func CatchError(resp http.ResponseWriter, request *http.Request) {
var LogText = "got bad request from " + request.RemoteAddr + ". Method: " + request.Method
fmt.Println(http.StatusBadRequest, LogText)
var MessageText = "Invalid Request, please read the docs..."
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte(MessageText))
}
func handleRequests() {
// Start new Mux router
mainrouter := mux.NewRouter().StrictSlash(true)
mainrouter.HandleFunc("/", readDataStream).Methods("POST")
2023-12-04 15:03:40 -07:00
mainrouter.HandleFunc("/healthcheck", HealthCheck).Methods("GET")
2023-12-12 13:29:55 -07:00
mainrouter.HandleFunc("/", CatchError)
log.Fatal(http.ListenAndServe(":10000", mainrouter))
}
func main() {
2023-12-12 13:29:55 -07:00
var t = time.Now().String()
fmt.Println("MPE x Egnyte x PowerApps - Mux Router starting: " + t)
handleRequests()
}
type send_data struct {
EventID string `json:"eventId"`
Domain string `json:"domain"`
Timestamp int64 `json:"timestamp"`
User struct {
ID int `json:"id"`
ClientIDHash string `json:"clientIdHash"`
DisplayName string `json:"displayName"`
Username string `json:"username"`
Email string `json:"email"`
ImpersonatedBy interface{} `json:"impersonatedBy"`
} `json:"user"`
ActionSource string `json:"actionSource"`
WebhookID string `json:"webhookId"`
EventType string `json:"eventType"`
Data struct {
SourcePath string `json:"sourcePath"`
TargetPath string `json:"targetPath"`
} `json:"data"`
}