-
Notifications
You must be signed in to change notification settings - Fork 68
/
parse.go
93 lines (82 loc) · 2.44 KB
/
parse.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
// beeper-imessage - A Matrix-iMessage puppeting bridge.
// Copyright (C) 2023 Beeper, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package nskeyedarchive
import (
"fmt"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"howett.net/plist"
)
type NSKeyedArchiveRoot struct {
Root plist.UID `plist:"root"`
}
type NSKeyedArchivePayload struct {
Archiver string `plist:"$archiver"`
Objects []any `plist:"$objects"`
Top NSKeyedArchiveRoot `plist:"$top"`
Version int `plist:"$version"`
}
func (p *NSKeyedArchivePayload) Parse(objIdx int) (any, error) {
switch obj := p.Objects[objIdx].(type) {
case string:
if obj == "$null" {
return nil, nil
} else {
return obj, nil
}
case map[string]any:
var err error
keys := maps.Keys(obj)
if slices.Contains(keys, "NS.keys") && slices.Contains(keys, "NS.objects") {
// This is a serialized dictionary.
deserialized := map[string]any{}
values := obj["NS.objects"].([]any)
for i, k := range obj["NS.keys"].([]any) {
parsedKey, err := p.Parse(int(k.(plist.UID)))
if err != nil {
return nil, err
}
deserialized[parsedKey.(string)], err = p.Parse(int(values[i].(plist.UID)))
}
return deserialized, nil
}
for k, v := range obj {
if k == "$class" {
delete(obj, k)
continue
}
switch val := v.(type) {
case plist.UID:
if obj[k], err = p.Parse(int(val)); err != nil {
return nil, err
}
}
}
return obj, nil
default:
return p.Objects[objIdx], nil
}
}
func Parse(data []byte) (any, error) {
var payload NSKeyedArchivePayload
if _, err := plist.Unmarshal(data, &payload); err != nil {
return nil, err
}
if payload.Archiver != "NSKeyedArchiver" {
return nil, fmt.Errorf("invalid archiver: %s", payload.Archiver)
}
return payload.Parse(int(payload.Top.Root))
}