Transfer Phone Numbers from gammu to the Mac Adressbook

Tue, 31. Mar 2009

Categories: en sysadmin Tags: 6610 Addressbook gammu Nokia OS X Ruby vCard

ok, make yourself comfortable, fasten your seatbelt and stop smoking. This will be quite a journey:

  1. Get gammu and backup the phone data:
    $ gammu backup phonedata.txt -yes
  2. open phonedata.txt and save it in „MacRoman“ encoding with Unix line endings
  3. run it through this ruby script:

    #!/usr/bin/ruby -w -- 
        
    # http://www.rubycentral.com/pickaxe/
    # http://homepage.mac.com/phrogz/CSV2vCard_v2.html
        
    records = {}
    fields = {}
        
    eor = /^[ \t]*$/
    bor = /^\[([^0-9\]]+)([0-9]*)\]$/
    etype = /^Entry([0-9]+)Type\s+=\s+(\S+)$/
    etext = /^Entry([0-9]+)Text\s+=\s+"(.*)"/
        
    record_type = nil
    entry_type = nil
    tmp = nil
        
    $stdin.each do |l|
      if (eor =~ l) == 0
        records[record_type] = [] if records[record_type].nil?
        records[record_type] << tmp if tmp
    #   puts '-- EOR --'
        record_type = entry_type = tmp = nil
        next
      end
      m = bor.match l
      if m
    #   puts "#{m[1]} - #{m[2]}"
        record_type = "#{m[1]}"
        tmp = {}
        next
      end
      if 'PhonePBK' == record_type
        m = etype.match l
    #   raise "Parse Error: #{l}" if entry_type.nil? && m.nil?
        if m
    entry_type = "#{m[2]}"
        else
    m = etext.match l
    if m
      raise 'Parse Error' if entry_type.nil?
      if 'Name' == entry_type
        name = "#{m[2]}".split ' '
        tmp[entry_type = 'LastName'] = "#{name[name.length-1]}"
        fields[entry_type] = entry_type
        name[name.length-1] = nil
        name.compact!
        
        count = 0
        name.each do |tn|
    tmp[entry_type = "Name_#{count}"] = tn
    fields[entry_type] = entry_type
    count += 1
        end
      else
        fields[entry_type] = entry_type
    #         puts "#{entry_type} = #{m[2]}"
        tmp[entry_type] = "#{m[2]}"
      end
      entry_type = nil
    end
        end
      end
    end
        
    keys = fields.keys.sort
    sep = ','
    puts "\##{keys.join(sep)}"
    records['PhonePBK'].each do |item|
      tmp = ''
      keys.each do |key|
        v = item[key]
        v = '' if v.nil?
        v.gsub! "'", "''"
        tmp = "#{tmp}'#{v}'#{sep}"
      end
      puts tmp
    end
    
  4. run the result through a csv to vcard converter,

  5. remove all single quotes ' from the vcards,

  6. import the vcards into the osx addressbook.

And guess what โ€“ that really works! The script is quite a hack but does the job. I thought about rewriting it using closures prior publishing but left it as a homework to you.

[Update] Maybe iSync would have done the trick, too.