Implemented folderId query

This commit is contained in:
Andreas Schneider 2018-03-31 15:20:21 +02:00
commit 1e9293ac86
1 changed files with 125 additions and 0 deletions

View File

@ -0,0 +1,125 @@
package main
import (
"encoding/xml"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"strings"
"time"
)
type FolderId struct {
Id string `xml:",attr"`
}
type CalendarItem struct {
Subject string
UID string
Start time.Time
End time.Time
}
type EWSCalendar struct {
httpClient *http.Client
url string
username string
password string
items []CalendarItem
}
func NewEWSCalendar(url, username, password string) *EWSCalendar {
// Prepare a cookie jar so we don't have to provide basic auth credentials multiple times.
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
return &EWSCalendar{
httpClient: &http.Client{
Jar: jar,
},
url: url,
username: username,
password: password,
}
}
func (e *EWSCalendar) prepareRequest(body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(http.MethodPost, e.url, body)
req.Header.Set("Content-Type", "text/xml")
req.Header.Set("Accept", "text/xml")
return
}
func (e *EWSCalendar) getCalendarFolderID() (id string, err error) {
req, err := e.prepareRequest(strings.NewReader(folderIdRequest))
if err != nil {
return
}
// For the first request we need an authentication header
req.SetBasicAuth(e.username, e.password)
resp, err := e.httpClient.Do(req)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("unexpected status when querying folderID: %d", resp.StatusCode)
return
}
d := xml.NewDecoder(resp.Body)
defer resp.Body.Close()
for {
var t xml.Token
t, err = d.Token()
if err == io.EOF {
err = nil
return
} else if err != nil {
return
}
switch t := t.(type) {
case xml.StartElement:
if t.Name.Local == "FolderId" {
fid := FolderId{}
err = d.DecodeElement(&fid, &t)
id = fid.Id
// The first one is enough
return
}
}
}
}
func main() {
e := NewEWSCalendar("https://outlook.live.com/EWS/Exchange.asmx", "", "")
id, err := e.getCalendarFolderID()
if err != nil {
log.Println(err)
return
}
fmt.Println(id)
}
const folderIdRequest = `<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<t:RequestServerVersion Version="Exchange2013_SP1" />
</soap:Header>
<soap:Body>
<m:GetFolder>
<m:FolderShape>
<t:BaseShape>AllProperties</t:BaseShape>
</m:FolderShape>
<m:FolderIds>
<t:DistinguishedFolderId Id="calendar" />
</m:FolderIds>
</m:GetFolder>
</soap:Body>
</soap:Envelope>`