-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn900contacts
executable file
·473 lines (412 loc) · 12.9 KB
/
n900contacts
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/python
# -*- coding: utf-8 -*-
# n900contacts Copyright (C) 2011, 2012, 2013 Stuart Pook (http://www.pook.it/)
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# run on a machine that has python-vobject. This machine must be able to run a command on the Nokia N900 using "ssh n900"
# with no options just look for a contact as given in the arguments
# show all the fred's in the contact list on the N900
# n900_contacts fred
# print a short list of important contacts formatted using groff
# n900_contacts -p | lp
# print a longer list of important and medium contacts
# n900_contacts -P | lp
# An important contact is a contact with gender male or female. A medium contact is a contact with an undefined gender.
# The printed output is formated for A4 paper.
from __future__ import print_function
from __future__ import with_statement # This isn't required in Python 2.6
import sys;
import os;
import re;
import unicodedata;
import locale
import tempfile
import vobject
import subprocess
import optparse
import errno
import time
import stat
class MyError(Exception):
pass
def format_number(number, options):
if number.find('p') >= 0:
p = re.compile('^.*p')
number = p.sub('', number)
if number.startswith('00'):
number = '+' + number[2:]
if number.startswith('0'):
number = options.home_prefix + number[1:]
if not options.international and number.startswith(options.home_prefix):
number = '0' + number[len(options.home_prefix):]
if options.dots:
p = re.compile(r'(\d\d)')
number = p.sub(r'\1.', number)
number = number[0:-1]
return number
def insert(set, value):
n = len(set)
set.add(value)
return n != len(set)
def format_contact(contact, troff, min_pager, options):
if troff:
or_mark = r" \(or "
else:
or_mark = " | "
if troff:
nbsp = r'\ '
else:
nbsp = ' '
try:
nv = contact.n.value
except AttributeError:
return ''
name = ''
for k in (nv.prefix, nv.given, nv.family, nv.suffix, nv.additional):
if k != '' and name != '':
name = name + " "
name = name + k
if troff:
out = r'\fB' + name + r'\fP'
else:
out = name + ','
pager = 0
for g in contact.contents.get('x-gender', []):
if g.value == 'female' or g.value == "male":
pager = 2
else:
pager = 1
numbers = set()
for number in contact.contents.get('tel', []):
tag = ''
for type in number.params['TYPE']:
if type == 'CELL':
tag += 'm'
elif type == 'HOME':
tag += 'h'
elif type == 'FAX':
tag += options.fax_tag
elif type == 'WORK':
tag += 'w'
elif type == 'PAGER':
break
else:
formated_number = format_number(number.value, options)
if insert(numbers, formated_number):
out += ' '
if tag:
out += tag + nbsp
out += formated_number
if pager < min_pager:
return ''
for number in contact.contents.get('x-sip', []):
formated_number = format_number(number.value.partition('@')[0], options)
if insert(numbers, formated_number):
out += ' s' + nbsp + formated_number
for address in contact.contents.get('adr', []):
tag = ''
try:
for type in address.params['TYPE']:
if type == 'HOME':
tag += 'h'
elif type == 'WORK':
tag += 'w'
except KeyError:
pass
v = address.value
for v in (v.box, v.extended, v.street, v.code, v.city, v.region, v.country):
if len(v) > 0:
if len(tag):
out += ' ' + tag + nbsp
tag = ''
else:
out += ', '
for vv in v:
out += vv
if 'note' in contact.contents:
done1 = False
for note in contact.contents['note']:
if len(note.value):
if done1:
out += or_mark
else:
out += ' ('
done1 = True
out += note.value
if done1:
out += ')'
for email in contact.contents.get('email', []):
if troff:
out += ' ' + email.value.replace('@', '\\:@').replace('.', '\\:.')
else:
out += ' ' + email.value
return out
def strip_accents(uc):
if uc == '':
return ''
c = unicodedata.normalize('NFD', uc)
d = ""
for i in c:
if unicodedata.combining(i) == 0:
d += i
return d
def eclose(evolution, errors, cmd):
if evolution.wait() != 0:
errors.seek(0)
sys.stderr.writelines(errors)
raise MyError("%s failed (%d)" % (cmd[0], evolution.returncode))
def matcher(unicode, expressions, what):
# print "matching", what, "=", `unicode`
for e in expressions:
if e.search(strip_accents(unicode)):
return True
return False
def match(contact, expressions):
# print(contact)
for k in ("org", ):
for l in contact.contents.get(k, []):
for m in l.value:
if matcher(m, expressions, k):
return True
for k in ("n",):
for l in contact.contents.get(k, []):
# print "n 1= ", dir(l)
# print "n a= ", l.prettyPrint()
# print "n 2= ", `l.value`
# print "n 3= ", dir(l.value)
# print "n 3 given = ", `l.value.given`
# print "n5=", strip_accents(l.value.given)
# print "n6=", strip_accents(l.value.family)
if matcher(l.value.suffix, expressions, k + " suffix"):
return True
if matcher(l.value.additional, expressions, k + " additional"):
return True
if matcher(l.value.prefix, expressions, k + " prefix"):
return True
if matcher(l.value.given, expressions, k + " given"):
return True
if matcher(l.value.family, expressions, k + " family"):
return True
for k in ("fn", 'tel'):
for l in contact.contents.get(k, []):
if matcher(l.value, expressions, k):
return True
for number in contact.contents.get('x-sip', []):
if matcher(number.value.partition('@')[0], expressions, "x-sip"):
return True
return False
def show_contacts(vcal, args, options):
expressions = []
for a in args:
expressions.append(re.compile(strip_accents(a.decode('utf-8')), re.IGNORECASE))
for contact in vobject.readComponents(vcal):
if (match(contact, expressions)):
# print dir(contact), contact.n.value.__doc__, `contact.n.value.given`, dir(contact.n.value)
print(format_contact(contact, False, 0, options).encode('utf-8'))
# express: for e in expressions:
# for k in ("fn", "n", "org"):
# if k in contact.contents:
# for k in contact.contents:
# print k, "is", contact.contents[k]
# if e.search(strip_accents(contact.contents[k])):
# print dir(contact)
# for z in contact.getChildren():
# print z
# print format_contact(contact, False, 0).encode('utf-8')
# break express
# eclose(evolution, errors)
def get_cache_file(options):
# ugly hack for http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=569273
get_contacts= ["ssh", "-xn", options.host,
"t=`mktemp /tmp/cXXXXXX` && run-standalone.sh osso-addressbook-backup -e $t && sed -e 's/\\\\,/,/g' $t && rm $t"]
if options.cache:
mode = 0o666
try:
old = open(options.cache, "r")
except IOError as e:
if e.errno != errno.ENOENT:
raise e
if options.verbose:
print("no cache " + options.cache, file=sys.stderr)
else:
stat_buf = os.fstat(old.fileno())
if stat_buf.st_mtime > time.time() - options.cache_lifetime:
if options.verbose:
print("reusing cache " + options.cache, file=sys.stderr)
return old
mode = stat.S_IMODE(stat_buf.st_mode)
old.close()
if options.verbose:
print("cache too old %s (new mode %#o)" % (options.cache, mode), file=sys.stderr)
tmp = options.cache + ".tmp"
agenda = os.fdopen(os.open(tmp, os.O_RDWR | os.O_CREAT | os.O_TRUNC, mode))
else:
agenda = tempfile.TemporaryFile()
errors = tempfile.TemporaryFile()
evolution = subprocess.Popen(get_contacts, bufsize=-1, stdout=agenda, stderr=errors, close_fds=True)
if evolution.wait() != 0:
if options.cache:
os.remove(tmp)
errors.seek(0)
sys.stderr.writelines(errors)
raise MyError("%s failed (%d)" % (get_contacts[0], evolution.returncode))
agenda.seek(0)
if options.cache:
os.rename(tmp, options.cache)
return agenda
def format_contacts(cache, options, args):
full = options.full_postscript or options.full
if options.groff:
output = sys.stdout
else:
output = tempfile.TemporaryFile()
mess = """.\\"
.af minutes 00
.kern
.fam HN
.nh
.na
.nr topmargin 1.5c
.po 0.7c
.ll 19.8c
.pl 29.7c
.sp \\n[topmargin]u
"""
output.write(mess)
if full:
sz = 11
if options.text_size:
sz = options.text_size
output.write('.ps %f\n' % sz)
mess = """.\\"
.vs \\n[.s]+0.9
.de NP
'bp
'sp \\n[topmargin]u
..
.wh -0.8c NP
"""
else:
sz = 7.9
if options.text_size:
sz = options.text_size
output.write('.ps %f\n' % sz)
mess = """.\\"
.vs \\n[.s]+0.4
.ll 15c
.de NP
' bp
' sp \\n[topmargin]u
' po +4.4c
..
.wh 7.2c NP
"""
output.write(mess)
if options.utf8:
output.write('.ll 26c\n')
output.write('.po 0\n')
output.write('.wh 7.2c\n')
output.write(r'\n[hours]:\n[minutes] \n[dy]/\n[mo]/\n[year]' + '\n')
if full:
output.write('.sp 0.3\n')
contacts = []
for contact in vobject.readComponents(cache):
line = format_contact(contact, True, full and 1 or 2, options)
if line:
contacts.append(line)
cache.close()
contacts.sort(locale.strcoll)
for line in contacts:
euro = u'\u20ac'
line = line.replace(euro, r'\[eu]')
output.write(line.encode('iso8859-1'))
output.write('\n')
if full:
output.write('.br\n')
output.write('\n')
if options.groff:
return
output.flush()
output.seek(0)
postscript = tempfile.TemporaryFile()
child = os.fork()
if child == 0:
os.dup2(output.fileno(), 0)
if options.print_list:
os.dup2(postscript.fileno(), 1)
cmd = ["groff"]
if options.utf8:
cmd.extend(["-T", "utf8"])
else:
cmd.extend(["-P", "-pA4"])
os.execvp(cmd[0], cmd)
pid, status = os.waitpid(child, 0)
if status:
raise MyError('groff failed: %d' % status)
if not options.print_list:
return
printer = "lp"
turn_over = not "Duplex=Duplex" in subprocess.Popen(["lpoptions"], stdout=subprocess.PIPE).communicate()[0]
postscript.seek(0)
child = os.fork()
if child == 0:
os.dup2(postscript.fileno(), 0)
if turn_over:
os.execlp(printer, printer, "-P1")
else:
os.execlp(printer, printer)
pid, status = os.waitpid(child, 0)
if status:
raise MyError('%s failed (%d)' % (printer, status))
if turn_over:
print("turn the paper over and hit return ", end="")
sys.stdin.readline()
postscript.seek(0)
child = os.fork()
if child == 0:
os.dup2(postscript.fileno(), 0)
os.execlp(printer, printer, "-P2")
pid, status = os.waitpid(child, 0)
if status:
raise MyError('%s failed (%d)' % (printer, status))
def main():
parser = optparse.OptionParser("%prog [options] pattern ...")
parser.add_option("-C", "--cache_lifetime", metavar="seconds", type='float', default=120, help="cache life time [%default]")
parser.add_option("-n", "--oldcache", action="store_const", const=0, dest='cache_lifetime',
help="consider cache is too old")
parser.add_option("-v", "--verbose", action="store_true", help="verbose")
parser.add_option("-g", "--groff", action="store_true", help="produce groff output")
parser.add_option("-p", "--short_postscript", action="store_true", help="produce PostScript list")
parser.add_option("-P", "--full_postscript", action="store_true", help="produce full PostScript list")
parser.add_option("-i", "--international", action="store_true", help="use internation format for all numbers")
parser.add_option("-f", "--full", action="store_true", help="produce full list")
parser.add_option("-d", "--dots", action="store_true", help="add dots to numbers")
parser.add_option("-u", "--utf8", action="store_true", help="produce a full UTF-8 list")
parser.add_option("--stdin", action="store_true", help="read stdin")
parser.add_option("--dump", action="store_true", help="dump the raw contact list")
parser.add_option("--print", dest="print_list", action="store_true", help="print")
parser.add_option("--text_size", type='float', metavar="points", help="text size")
parser.add_option("--host", default="n900", help="host to contact [%default]")
parser.add_option("--fax_tag", default="f", help="tag for fax numbers [%default]")
parser.add_option("--home_prefix", default="+33", help="home prefix [%default]")
parser.add_option("--cache", metavar="file_for_cache", help="file to cache contacts [%default]")
(options, args) = parser.parse_args()
#locale.setlocale(locale.LC_COLLATE, 'fr_FR.iso885915@euro')
locale.setlocale(locale.LC_ALL, '')
locale.setlocale(locale.LC_COLLATE, 'fr_FR.UTF-8')
with get_cache_file(options) as cache:
if options.dump:
for line in cache:
print(line, end="")
elif not options.short_postscript and not options.full_postscript and not options.utf8 and not options.groff:
show_contacts(cache, args, options)
else:
format_contacts(cache, options, args)
if __name__ == "__main__":
main()