/
plist.js
303 lines (281 loc) · 8.8 KB
/
plist.js
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
;(function (exports, sax, xmlbuilder) {
// Checks if running in a non-browser environment
var inNode = typeof window === 'undefined' ? true : false;
function Parser() {
sax.SAXParser.call(this, false, { lowercasetags: true, trim: false });
}
var inherits = null;
if (inNode) {
var fs = require('fs');
inherits = require('util').inherits; // use node provided function
} else { //use in browser
if ("create" in Object) {
inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
var klass = function() {};
inherits = function(ctor, superCtor) {
klass.prototype = superCtor.prototype;
ctor.prototype = new klass;
ctor.prototype['constructor'] = ctor;
}
}
}
inherits(Parser, sax.SAXParser); // inherit from sax (browser-style or node-style)
Parser.prototype.getInteger = function (string) {
this.value = parseInt(string, 10);
}
Parser.prototype.getReal = function (string) {
this.value = parseFloat(string);
}
Parser.prototype.getString = function (string) {
this.value += string;
}
Parser.prototype.getData = function(string) {
// todo: parse base64 encoded data
this.value += string;
}
Parser.prototype.getDate = function (string) {
this.value = new Date(string);
}
Parser.prototype.addToDict = function (value) {
this.dict[this.key] = value;
}
Parser.prototype.addToArray = function (value) {
this.array.push(value);
}
Parser.prototype.onopentag = function (tag) {
switch (tag.name) {
case 'dict':
this.stack.push(this.context);
this.context = {
value: function() {
return this.dict;
},
dict: {},
setKey: function(key) {
this.key = key;
},
setValue: function(value) {
this.dict[this.key] = value;
}
}
break;
case 'plist':
case 'array':
this.stack.push(this.context);
this.context = {
value: function() {
return this.array;
},
array: [],
setKey: function(key) {
console.log('unexpected <key> element in array');
},
setValue: function(value) {
this.array.push(value);
}
}
break;
case 'key':
this.ontext = function (text) {
this.context.setKey(text);
}
break;
case 'integer':
this.ontext = this.getInteger;
break;
case 'real':
this.ontext = this.getReal;
break;
case 'string':
this.value = '';
this.ontext = this.getString;
this.oncdata = this.getString;
break;
case 'data':
this.value = '';
this.ontext = this.getData;
this.oncdata = this.getData;
break;
case 'true':
this.value = true;
break;
case 'false':
this.value = false;
break;
case 'date':
this.ontext = this.getDate;
break;
default:
console.log('ignored tag', tag.name);
break;
}
}
Parser.prototype.onclosetag = function (tag) {
var value;
switch (tag) {
case 'dict':
case 'array':
case 'plist':
var value = this.context.value();
this.context = this.stack.pop();
this.context.setValue(value);
break;
case 'true':
case 'false':
case 'string':
case 'integer':
case 'real':
case 'date':
case 'data':
this.context.setValue(this.value);
break;
case 'key':
break;
default:
console.log('closing', tag, 'tag ignored');
}
this.oncdata = this.ontext = this.checkWhitespace;
}
Parser.prototype.checkWhitespace = function (data) {
if (!data.match(/^[ \t\r\n]*$/)) {
console.log('unexpected non-whitespace data', data);
}
}
Parser.prototype.oncomment = function (comment) {
}
Parser.prototype.onerror = function (error) {
console.log('sax parser error:', error);
throw error;
}
if (inNode) Parser.prototype.parseFile = function (xmlfile, callback) { // browsers aren't capable of opening files, instead use AJAX
var parser = this;
parser.stack = [ ];
parser.context = {
callback: callback,
value: function() {},
setKey: function(key) {},
setValue: function(value) {
callback(null, value);
},
}
var rs = fs.createReadStream(xmlfile, {
encoding: 'utf8'
});
rs.on('data', function(data) { parser.write(data); });
rs.on('end', function() { parser.close(); });
}
Parser.prototype.parseString = function (xml, callback) {
var parser = this;
parser.stack = [ ];
parser.context = {
callback: callback,
value: function() {},
setKey: function(key) {},
setValue: function(value) {
this.callback(null, value);
},
};
parser.write(xml);
parser.close();
}
exports.Parser = Parser;
exports.parseString = function (xml, callback) {
var parser = new Parser();
parser.parseString(xml, callback);
}
if (inNode) exports.parseFile = function (filename, callback) { // Do not expose no created method
var parser = new Parser();
parser.parseFile(filename, callback);
}
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
// instanceof is horribly unreliable so we use these hackish but safer checks
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
function isBoolean(obj) {
return (obj === true || obj === false || toString.call(obj) == '[object Boolean]');
}
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
exports.build = function(obj) {
var XMLHDR = { 'version': '1.0','encoding': 'UTF-8'}
, XMLDTD = { 'ext': 'PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"'}
, doc = xmlbuilder.create()
, child = doc.begin('plist', XMLHDR, XMLDTD).att('version', '1.0');
walk_obj(obj, child);
return child.end({pretty: true });
}
function walk_obj(next, next_child) {
var tag_type, i, prop;
if(isArray(next)) {
next_child = next_child.ele('array');
for(i=0 ;i < next.length;i++) {
walk_obj(next[i], next_child);
}
}
else if(isObject(next)) {
next_child = next_child.ele('dict');
for(prop in next) {
if(next.hasOwnProperty(prop)) {
next_child.ele('key').txt(prop);
walk_obj(next[prop], next_child);
}
}
}
else if(isNumber(next)) {
// detect if this is an integer or real
tag_type =(next % 1 === 0) ? 'integer' : 'real';
next_child.ele(tag_type).txt(next.toString());
}
else if(isDate(next)) {
next_child.ele('date').raw(ISODateString(new Date(next)));
}
else if(isBoolean(next)) {
val = next ? "true" : "false";
next_child.ele(val);
}
else if(isString(next)) {
//if (str!=obj || str.indexOf("\n")>=0) str = "<![CDATA["+str+"]]>";
var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");
//var base64Matcher = new RegExp("^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$");
if (base64Matcher.test(next.replace(/\s/g,'')) && (next.length>125)) {
next_child.ele('data').raw(next);
} else {
next_child.ele('string').raw(next);
}
}
};
})(typeof exports === 'undefined' ? plist = {} : exports, typeof window === "undefined" ? require('sax') : sax, typeof window === "undefined" ? require('xmlbuilder') : xmlbuilder)
//the above line checks for exports (defined in node) and uses it, or creates a global variable and exports to that.
//also, if in node, require sax node-style, in browser the developer must use a <script> tag to import sax
// TODO: Implement detection of 'sax' in the Browser environment