This repository has been archived by the owner on Dec 12, 2018. It is now read-only.
forked from der-antikeks/go-webdav
-
Notifications
You must be signed in to change notification settings - Fork 14
/
lock.go
119 lines (100 loc) · 2.39 KB
/
lock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package webdav
import (
"errors"
"fmt"
"strings"
"time"
)
type Lock struct {
uri string
creator string
owner string
depth int
timeout TimeOut
typ string
scope string
token string
Modified time.Time
}
func NewLock(uri, creator, owner string) *Lock {
return &Lock{
uri,
creator,
owner,
0,
0,
"write",
"exclusive",
generateToken(),
time.Now(),
}
}
// parse a lock from a http request
func ParseLockString(body string) (*Lock, error) {
node, err := NodeFromXmlString(body)
if err != nil {
return nil, err
}
if node == nil {
return nil, errors.New("no found node")
}
lock := new(Lock)
if node.Name.Local != "lockinfo" {
node = node.FirstChildren("lockinfo")
}
if node == nil {
return nil, errors.New("not lockinfo element")
}
lock.scope = node.FirstChildren("lockscope").Children[0].Name.Local
lock.typ = node.FirstChildren("locktype").Children[0].Name.Local
lock.owner = node.FirstChildren("owner").Children[0].Value
return lock, nil
}
func (lock *Lock) Refresh() {
lock.Modified = time.Now()
}
func (lock *Lock) IsValid() bool {
return time.Duration(lock.timeout) > time.Now().Sub(lock.Modified)
}
func (lock *Lock) GetTimeout() TimeOut {
return lock.timeout
}
func (lock *Lock) SetTimeout(timeout time.Duration) {
lock.timeout = TimeOut(timeout)
lock.Modified = time.Now()
}
func (lock *Lock) asXML(namespace string, discover bool) string {
//owner_str = lock.owner
//owner_str = "".join([node.toxml() for node in self.owner[0].childNodes])
base := fmt.Sprintf(`<%[1]s:activelock>
<%[1]s:locktype><%[1]s:%[2]s/></%[1]s:locktype>
<%[1]s:lockscope><%[1]s:%[3]s/></%[1]s:lockscope>
<%[1]s:depth>%[4]d</%[1]s:depth>
<%[1]s:owner>%[5]s</%[1]s:owner>
<%[1]s:timeout>%[6]s</%[1]s:timeout>
<%[1]s:locktoken>
<%[1]s:href>opaquelocktoken:%[7]s</%[1]s:href>
</%[1]s:locktoken>
<%[1]s:lockroot>
<%[1]s:href>%[8]s</%[1]s:href>
</%[1]s:lockroot>
</%[1]s:activelock>
`, strings.Trim(namespace, ":"),
lock.typ,
lock.scope,
lock.depth,
lock.owner,
lock.GetTimeout(),
lock.token,
lock.uri,
)
if discover {
return base
}
return fmt.Sprintf(`<?xml version="1.0" encoding="utf-8" ?>
<D:prop xmlns:d="DAV:">
<D:lockdiscovery>
%s
</D:lockdiscovery>
</D:prop>`, base)
}