added outlook web mapping
[bbdb-csv-import] / bbdb3-csv-import.el
1 ;;; bbdb3-csv-import.el --- import csv to bbdb version 3+ -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 by Ian Kelling
4
5 ;; Author: Ian Kelling <ian@iankelling.org>
6 ;; Created: 1 Apr 2014
7 ;; Version: 1.0
8 ;; Keywords: csv, util, bbdb
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Importer of csv (comma separated value) text into Emacs’s bbdb database,
26 ;; version 3+. Programs such as Thunderbird, Gmail, Linkedin, and Outlook allow
27 ;; for exporting contact data as csv files. See ASynK for syncing bbdb/google/outlook.
28
29 ;;; Installation:
30 ;;
31 ;; dependencies: pcsv.el, dash.el, bbdb
32 ;; These are available via marmalade/melpa or the internet
33 ;;
34 ;; Add to init file or execute manually as this may be a one time usage:
35 ;; (load-file FILENAME-OF-THIS-FILE)
36 ;; or
37 ;; (add-to-list 'load-path DIRECTORY-CONTAINING-THIS-FILE)
38 ;; (require 'bbdb3-csv-import)
39
40 ;;; Usage:
41 ;;
42 ;; Backup or rename any existing ~/.bbdb and ~/.emacs.d/bbdb while testing that
43 ;; the import works correctly.
44 ;;
45 ;; Assign a mapping table. Predefined ones listed here:
46 ;; (setq bbdb3-csv-import-mapping-table bbdb3-csv-import-thunderbird)
47 ;; (setq bbdb3-csv-import-mapping-table bbdb3-csv-import-gmail)
48 ;; (setq bbdb3-csv-import-mapping-table bbdb3-csv-import-linkedin)
49 ;;
50 ;; Simply call `bbdb3-csv-import-buffer' or
51 ;; `bbdb3-csv-import-file'. Interactively they prompt for file/buffer. Use
52 ;; non-interactively for no prompts.
53 ;;
54 ;; If you need to define your own mapping table, it should not be too hard. Use
55 ;; the existing tables as an example, and perhaps the test data within this
56 ;; project. Please send any new mapping tables to the maintainer listed in this
57 ;; file. The maintainer should be able to help with any issues and may create a
58 ;; new mapping table given sample data.
59 ;;
60 ;; Tips for testing:
61 ;; - bbdb doesn't work if you delete the bbdb database file in
62 ;; the middle of an emacs session. If you want to empty the current bbdb database,
63 ;; do M-x bbdb then .* then C-u * d on the beginning of a record.
64 ;; - After changing a mapping table, don't forget to re-execute
65 ;; (setq bbdb3-csv-import-mapping-table ...) so that it propagates.
66 ;;
67
68 (require 'pcsv)
69 (require 'dash)
70 (require 'bbdb-com)
71 (eval-when-compile (require 'cl))
72
73 (defconst bbdb3-csv-import-thunderbird
74 '(("firstname" "First Name")
75 ("lastname" "Last Name")
76 ("name" "Display Name")
77 ("aka" "Nickname")
78 ("mail" "Primary Email" "Secondary Email")
79 ("phone" "Work Phone" "Home Phone" "Fax Number" "Pager Number" "Mobile Number")
80 ("address"
81 (("home address"
82 (("Home Address" "Home Address 2")
83 "Home City" "Home State"
84 "Home ZipCode" "Home Country"))
85 ("work address"
86 (("Work Address" "Work Address 2")
87 "Work City" "Work State"
88 "Work ZipCode" "Work Country"))))
89 ("organization" "Organization")
90 ("xfields" "Web Page 1" "Web Page 2" "Birth Year" "Birth Month"
91 "Birth Day" "Department" "Custom 1" "Custom 2" "Custom 3"
92 "Custom 4" "Notes" "Job Title"))
93 "Thunderbird csv format")
94
95 (defconst bbdb3-csv-import-linkedin
96 '(("firstname" "First Name")
97 ("lastname" "Last Name")
98 ("middlename" "Middle Name")
99 ("mail" "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
100 ("phone"
101 "Assistant's Phone" "Business Fax" "Business Phone"
102 "Business Phone 2" "Callback" "Car Phone"
103 "Company Main Phone" "Home Fax" "Home Phone"
104 "Home Phone 2" "ISDN" "Mobile Phone"
105 "Other Fax" "Other Phone" "Pager"
106 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
107 ("address"
108 (("business address"
109 (("Business Street" "Business Street 2" "Business Street 3")
110 "Business City" "Business State"
111 "Business Postal Code" "Business Country"))
112 ("home address"
113 (("Home Street" "Home Street 2" "Home Street 3")
114 "Home City" "Home State"
115 "Home Postal Code" "Home Country"))
116 ("other address"
117 (("Other Street" "Other Street 2" "Other Street 3")
118 "Other City" "Other State"
119 "Other Postal Code" "Other Country"))))
120 ("organization" "Company")
121 ("xfields"
122 "Suffix" "Department" "Job Title" "Assistant's Name"
123 "Birthday" "Manager's Name" "Notes" "Other Address PO Box"
124 "Spouse" "Web Page" "Personal Web Page"))
125 "Linkedin export in the Outlook csv format.")
126
127
128 ;; note. PO Box and Extended Address are added as additional address street lines if they exist.
129 ;; If you don't like this, just delete them from this fiel.
130 ;; If you want some other special handling, it will need to be coded.
131 (defconst bbdb3-csv-import-gmail
132 '(("firstname" "Given Name")
133 ("lastname" "Family Name")
134 ("name" "Name")
135 ("mail" (repeat "E-mail 1 - Value"))
136 ("phone" (repeat ("Phone 1 - Type" "Phone 1 - Value")))
137 ("address"
138 (repeat (("Address 1 - Type")
139 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
140 "Address 1 - City" "Address 1 - Region"
141 "Address 1 - Postal Code" "Address 1 - Country"))))
142 ("organization" (repeat "Organization 1 - Name"))
143 ("xfields"
144 "Additional Name" "Yomi Name" "Given Name Yomi"
145 "Additional Name Yomi" "Family Name Yomi" "Name Prefix"
146 "Name Suffix" "Initials" "Nickname"
147 "Short Name" "Maiden Name" "Birthday"
148 "Gender" "Location" "Billing Information"
149 "Directory Server" "Mileage" "Occupation"
150 "Hobby" "Sensitivity" "Priority"
151 "Subject" "Notes" "Group Membership"
152 ;; Gmail wouldn't let me add more than 1 organization, but no harm in
153 ;; looking for multiple since the field name implies the possibility.
154 (repeat
155 "Organization 1 - Type" "Organization 1 - Yomi Name"
156 "Organization 1 - Title" "Organization 1 - Department"
157 "Organization 1 - Symbol" "Organization 1 - Location"
158 "Organization 1 - Job Description")
159 (repeat ("Relation 1 - Type" "Relation 1 - Value"))
160 (repeat ("Website 1 - Type" "Website 1 - Value"))
161 (repeat ("Event 1 - Type" "Event 1 - Value"))
162 (repeat ("Custom Field 1 - Type" "Custom Field 1 - Value"))))
163 "Gmail csv export format")
164
165
166 (defconst bbdb3-csv-import-gmail-typed-email
167 (append (car (last bbdb3-csv-import-gmail)) '((repeat "E-mail 1 - Type")))
168 "Like the first Gmail mapping, but use custom fields to store
169 Gmail's email labels. This is separate because I assume most
170 people don't use those labels and using the default labels
171 would create useless custom fields.")
172
173 (defconst bbdb3-csv-import-outlook-web-typed-email
174 (append (car (last bbdb3-csv-import-outlook-web)) '((repeat "E-mail 1 - Type")))
175 "Like the previous var, but for outlook-web.
176 Adds email labels as custom fields.")
177
178
179 (defconst bbdb3-csv-import-outlook-web
180 '(("firstname" "First Name")
181 ("lastname" "Last Name")
182 ("middlename" "Middle Name")
183 ("mail" "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
184 ("phone"
185 "Assistant's Phone" "Business Fax" "Business Phone"
186 "Business Phone 2" "Callback" "Car Phone"
187 "Company Main Phone" "Home Fax" "Home Phone"
188 "Home Phone 2" "ISDN" "Mobile Phone"
189 "Other Fax" "Other Phone" "Pager"
190 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
191 ("address"
192 (("business address"
193 (("Business Street")
194 "Business City" "Business State"
195 "Business Postal Code" "Business Country"))
196 ("home address"
197 (("Home Street")
198 "Home City" "Home State"
199 "Home Postal Code" "Home Country"))
200 ("other address"
201 (("Other Street")
202 "Other City" "Other State"
203 "Other Postal Code" "Other Country"))))
204 ("organization" "Company")
205 ("xfields"
206 "Anniversary" "Family Name Yomi" "Given Name Yomi"
207 "Suffix" "Department" "Job Title" "Birthday" "Manager's Name" "Notes"
208 "Spouse" "Web Page"))
209 "Hotmail.com, outlook.com, live.com, etc.
210 Based on 'Export for outlook.com and other services',
211 not the export for Outlook 2010 and 2013.")
212
213
214
215 (defvar bbdb3-csv-import-mapping-table nil
216 "The table which maps bbdb3 fields to csv fields.
217 Use the default as an example to map non-thunderbird data.
218 Name used is firstname + lastname or name.
219 After the car, all names should map to whatever csv
220 field names are used in the first row of csv data.
221 Many fields are optional. If you aren't sure if one is,
222 best to just try it. The doc string for `bbdb-create-internal'
223 may be useful for determining which fields are required.")
224
225 ;;;###autoload
226 (defun bbdb3-csv-import-file (filename)
227 "Parse and import csv file FILENAME to bbdb3."
228 (interactive "fCSV file containg contact data: ")
229 (bbdb3-csv-import-buffer (find-file-noselect filename)))
230
231
232 ;;;###autoload
233 (defun bbdb3-csv-import-buffer (&optional buffer-or-name)
234 "Parse and import csv BUFFER-OR-NAME to bbdb3.
235 Argument is a buffer or name of a buffer.
236 Defaults to current buffer."
237 (interactive "bBuffer containing CSV contact data: ")
238 (when (null bbdb3-csv-import-mapping-table)
239 (error "error: `bbdb3-csv-import-mapping-table' is nil. Please set it and rerun."))
240 (let* ((csv-fields (pcsv-parse-buffer (get-buffer (or buffer-or-name (current-buffer)))))
241 (csv-contents (cdr csv-fields))
242 (csv-fields (car csv-fields))
243 (initial-duplicate-value bbdb-allow-duplicates)
244 csv-record rd assoc-plus flatten1)
245 ;; convenient function names
246 (fset 'rd 'bbdb3-csv-import-rd)
247 (fset 'assoc-plus 'bbdb3-csv-import-assoc-plus)
248 (fset 'flatten1 'bbdb3-csv-import-flatten1)
249 ;; Easier to allow duplicates and handle them post import vs failing as
250 ;; soon as we find one.
251 (setq bbdb-allow-duplicates t)
252 ;; loop over the csv records
253 (while (setq csv-record (map 'list 'cons csv-fields (pop csv-contents)))
254 (cl-flet*
255 ((rd-assoc (list)
256 ;; given LIST of fields, return a list of data, ignoring empty fields
257 (rd (lambda (elem) (assoc-plus elem csv-record)) list))
258 (mapcar-assoc (list)
259 ;; given LIST of fields,return a list of data with nil in place of an empty field
260 (mapcar (lambda (elem) (cdr (assoc elem csv-record))) list))
261 (assoc-expand (e)
262 ;; E = data-field-name | (field-name-field data-field)
263 ;; get data from the csv-record and return
264 ;; (field-name data) or nil.
265 (let ((data-name (if (consp e) (cdr (assoc (car e) csv-record)) e))
266 (data (assoc-plus (if (consp e) (cadr e) e) csv-record)))
267 (if data (list data-name data))))
268 (replace-num (num string)
269 ;; in STRING, replace all groups of numbers with NUM
270 (replace-regexp-in-string "[0-9]+" (number-to-string num) string))
271 (expand-repeats (list)
272 ;; return new list where elements from LIST in form
273 ;; (repeat elem1 ...) become ((elem1 ...) [(elem2 ...)] ...)
274 ;; For as many repeating numbered fields exist in the csv fields.
275 ;; elem can be a string or a tree (a list with possibly lists inside it)
276 (-reduce-from (lambda (acc arg)
277 (if (not (and (consp arg) (eq (car arg) 'repeat)))
278 (cons arg acc)
279 (setq arg (cdr arg))
280 (let* ((i 1)
281 (first-field (car (flatten arg))))
282 (setq acc (cons arg acc))
283 ;; use first-field to test if there is another repetition.
284 (while (member (replace-num (setq i (1+ i)) first-field) csv-fields)
285 (cl-labels ((fun (cell)
286 (if (consp cell)
287 (mapcar #'fun cell)
288 (replace-num i cell))))
289 (setq acc (cons (fun arg) acc))))
290 acc))) nil list))
291
292 (map-bbdb3 (root-mapping)
293 ;; ROOT-MAPPING = a root element from bbdb3-csv-import-mapping-table.
294 ;;
295 ;; Get the actual csv-fields, including variably repeated ones flattened
296 ;; by one because potentially repeated fields are put in sub-lists so they
297 ;; can be as one thing, but after they are, that extra depth is no longer
298 ;; useful. This makes for a little quirk: address mappings without 'repeat
299 ;; need to be grouped in a list because they contain sublists that we
300 ;; don't want flattened. I've decided that is a better trade off than more
301 ;; complex code.
302 (flatten1 (expand-repeats (cdr (assoc bbdb-arg bbdb3-csv-import-mapping-table)))))
303 (map-assoc (field)
304 ;; For mappings with just 1 simple csv-field, get it's data
305 (assoc-plus (car (map-bbdb3 field)) csv-record)))
306
307
308 (let ((name (let ((first (map-assoc "firstname"))
309 (middle (map-assoc "middlename"))
310 (last (map-assoc "lastname"))
311 (name (map-assoc "name")))
312 ;; prioritize any combination of first middle last over just "name"
313 (if (or (and first last) (and first middle) (and middle last))
314 ;; purely historical note.
315 ;; using (cons first last) as argument works the same as (concat first " " last)
316 (concat (or first middle) " " (or middle last) (when (and first middle) (concat " " last) ))
317 (or name first middle last ""))))
318 (phone (rd 'vconcat (rd #'assoc-expand (map-bbdb3 "phone"))))
319 (mail (rd-assoc (map-bbdb3 "mail")))
320 (xfields (rd (lambda (list)
321 (let ((e (car list)))
322 (while (string-match "-" e)
323 (setq e (replace-match "" nil nil e)))
324 (while (string-match " +" e)
325 (setq e (replace-match "-" nil nil e)))
326 (setq e (make-symbol (downcase e)))
327 (cons e (cadr list)))) ;; change from (a b) to (a . b)
328 (rd #'assoc-expand (map-bbdb3 "xfields"))))
329 (address (rd (lambda (mapping-elem)
330 (let ((address-lines (mapcar-assoc (caadr mapping-elem)))
331 (address-data (mapcar-assoc (cdadr mapping-elem)))
332 (elem-name (car mapping-elem)))
333
334 (when (consp elem-name)
335 (setq elem-name (cdr (assoc (car elem-name) csv-record))))
336
337 ;; determine if non-nil and put together the minimum set
338 (when (or (not (-all? '(lambda (arg) (zerop (length arg))) address-data))
339 (not (-all? '(lambda (arg) (zerop (length arg))) address-lines)))
340 (when (> 2 (length address-lines))
341 (setcdr (max 2 (nthcdr (-find-last-index (lambda (mapping-elem) (not (null mapping-elem)))
342 address-lines)
343 address-lines)) nil))
344 (vconcat (list elem-name) (list address-lines) address-data))))
345 (map-bbdb3 "address")))
346 (organization (rd-assoc (map-bbdb3 "organization")))
347 (affix (map-assoc "affix"))
348 (aka (rd-assoc (map-bbdb3 "aka"))))
349 (bbdb-create-internal name affix aka organization mail phone address xfields t))))
350 (setq bbdb-allow-duplicates initial-duplicate-value)))
351
352
353 (defun bbdb3-csv-import-flatten1 (list)
354 "flatten LIST by 1 level."
355 (-reduce-from (lambda (acc elem)
356 (if (consp elem)
357 (-concat acc elem)
358 (-snoc acc elem)))
359 nil list))
360
361 ;;;###autoload
362 (defun bbdb3-csv-import-rd (func list)
363 "like mapcar but don't build nil results into the resulting list"
364 (-reduce-from (lambda (acc elem)
365 (let ((funcreturn (funcall func elem)))
366 (if funcreturn
367 (cons funcreturn acc)
368 acc)))
369 nil list))
370
371 ;;;###autoload
372 (defun bbdb3-csv-import-assoc-plus (key list)
373 "Like `assoc' but turn an empty string result to nil."
374 (let ((result (cdr (assoc key list))))
375 (when (not (string= "" result))
376 result)))
377
378
379
380 (provide 'bbdb3-csv-import)
381
382 ;;; bbdb3-csv-import.el ends here