nccli/util/nextcloud.go
Brian Buller e865313e15 Initial Commit
Internal Link Generation
2024-05-28 16:50:11 -05:00

72 lines
1.6 KiB
Go

/*
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
*/
package util
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/spf13/viper"
)
func GetAuth() (string, error) {
username := viper.GetString("ncuser")
password, err := Decrypt(viper.GetString("ncpw"))
if err != nil {
return "", err
}
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth)), nil
}
func NormalizeLocalPath(path string) string {
root := viper.GetString("directory")
return strings.TrimPrefix(path, root)
}
func GetFilesUrl(path string) string {
return fmt.Sprintf("%sremote.php/dav/files/%s/%s", viper.GetString("ncurl"), viper.GetString("ncuser"), path)
}
func GetFileId(url string) (string, error) {
var auth string
client := &http.Client{}
data := bytes.NewBuffer([]byte(`<?xml version="1.0" encoding="UTF-8"?>
<d:propfind xmlns:d="DAV:">
<d:prop xmlns:oc="http://owncloud.org/ns">
<oc:fileid/>
</d:prop>
</d:propfind>`))
req, err := http.NewRequest("PROPFIND", url, data)
if err != nil {
return "", err
}
auth, err = GetAuth()
if err != nil {
return "", err
}
req.Header.Add("Authorization", "Basic "+auth)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var body []byte
body, err = io.ReadAll(resp.Body)
wrkArr := strings.Split(string(body), "<oc:fileid>")
if len(wrkArr) != 2 {
return "", errors.New("Couldn't find File ID")
}
wrkArr = strings.Split(wrkArr[1], "</oc:fileid>")
if len(wrkArr) != 2 {
return "", errors.New("Couldn't find File ID")
}
return wrkArr[0], nil
}