public
Description: Nokia NBU to vCard
Clone URL: git://github.com/halorgium/nbu2vcard.git
halorgium (author)
Sat Apr 19 18:47:40 -0700 2008
commit  45ca99fb4fbdf37b12aa5893ae46a46b35b1fc3a
tree    b0b45bff26bed1137cb455eb79795a330f93a5e3
nbu2vcard / convert.rb
100755 84 lines (69 sloc) 1.692 kb
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
#!/usr/bin/env ruby
 
require 'logger'
require 'fileutils'
LOGGER = Logger.new($stderr)
 
class NokiaFile
  FIRST_BITS = /[\240\[\]{};\w>\306:\\\210\234`\316\201?\220^\215"\307\267<\202]/
  SECOND_BITS = /[\021]/
 
  def initialize(filename)
    @filename = filename
  end
  attr_reader :filename
 
  def content
    @content ||= File.read(filename)
  rescue Errno::ENOENT
    abort "data file not found"
  end
 
  def parts
    LOGGER.info "content size: #{content.size}" unless @parts
    @parts ||= content.split(/#{FIRST_BITS}#{SECOND_BITS}/)
  end
 
  def vcards
    @vcards ||= begin
      LOGGER.info "parts size: #{parts.size}" unless @vcards
      parts.map do |part|
        VCard.new(part)
      end
    end
  end
 
  def vcards_with_more_than_one
    vcards.select do |vcard|
      vcard.vcard_count > 1
    end
  end
 
  def write
    FileUtils.mkdir(data_dir)
    vcards.each_with_index do |vcard,i|
      vcard.write("#{data_dir}/#{i}.vcf")
    end
  end
 
  def data_dir
    @data_dir ||= File.expand_path(File.dirname(__FILE__)) + "/output/#{Time.now.to_i}"
  end
end
 
class VCard
  def initialize(part)
    @part = part
  end
  attr_reader :part
 
  def vcard_count
    part.scan("BEGIN:VCARD").size
  end
 
  def write(filename)
    File.open(filename, "w") do |f|
      f.write part
    end
  end
end
 
require 'pp'
 
filename = ARGV.first || abort("provide a .nbu data file to parse")
nf = NokiaFile.new(filename)
bad = nf.vcards_with_more_than_one
if bad.any?
  LOGGER.error "there are #{bad.size} vcards with more than one inside :("
  LOGGER.error "here is the first"
  pp bad.first.part.split(/\n/)
else
  LOGGER.info "writing vcards to #{nf.data_dir}"
  nf.write
end