minor doc update
[bbdb-csv-import] / bbdb-csv-import.el
1 ;;; bbdb-csv-import.el --- import csv to bbdb version 3+
2
3 ;; Copyright (C) 2014 by Ian Kelling
4
5 ;; Maintainer: Ian Kelling <ian@iankelling.org>
6 ;; Author: Ian Kelling <ian@iankelling.org>
7 ;; Created: 1 Apr 2014
8 ;; Version: 1.1
9 ;; Package-Requires: ((pcsv "1.3.3") (dash "2.5.0") (bbdb "20140412.1949"))
10 ;; Keywords: csv, util, bbdb
11 ;; Homepage: https://gitlab.com/iankelling/bbdb-csv-import
12
13 ;; This program is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; Importer of csv (comma separated value) text into Emacs’s bbdb database,
29 ;; version 3+. Works out of the box with csv exported from Thunderbird, Gmail,
30 ;; Linkedin, Outlook.com/hotmail, and probably others.
31 ;; Easily extensible to handle new formats.
32
33 ;;; Installation:
34 ;;
35 ;; If you installed this file with a package manager, just
36 ;;
37 ;; (require 'bbdb-csv-import)
38 ;;
39 ;; Else, note the min versions of dependencies above in "Package-Requires:",
40 ;; and load this file. The exact minimum bbdb version is unknown, something 3+.
41 ;;
42 ;;; Basic Usage:
43 ;;
44 ;; Back up bbdb by copying `bbdb-file' in case things go wrong.
45 ;;
46 ;; Simply M-x `bbdb-csv-import-buffer' or `bbdb-csv-import-file'.
47 ;; When called interactively, they prompt for file or buffer arguments.
48 ;;
49 ;; Then view your bbdb records: M-x bbdb .* RET
50 ;; If the import looks good save the bbdb database: C-x s (bbdb-save)
51
52 ;;; Advanced usage / notes:
53 ;;
54 ;; Tested to work with thunderbird, gmail, linkedin,
55 ;; outlook.com/hotmail.com. For those programs, if it's exporter has an option
56 ;; of what kind of csv format, choose it's own native format if available, if
57 ;; not, choose an outlook compatible format. If you're exporting from some other
58 ;; program and its csv exporter claims outlook compatibility, there is a good
59 ;; chance it will work out of the box. If it doesn't, you can try to fix it as
60 ;; described below, or the maintainer will be happy to help, just anonymize your
61 ;; csv data using the M-x bbdb-csv-anonymize-current-buffer (make sure csv
62 ;; buffer is the current one) and attach it to an email.
63 ;;
64 ;; Duplicate contacts (according to email address) are skipped if
65 ;; bbdb-allow-duplicates is nil (default). Any duplicates found are echoed at
66 ;; the end of the import.
67
68 ;;; Custom mapping of csv fields
69 ;;
70 ;; If a field is handled wrong or you want to extend the program to handle a new
71 ;; kind of csv format, you need to setup a custom field mapping variable. Use
72 ;; the existing tables as an example. By default, we use a combination of most
73 ;; predefined mappings, and look for all of their fields, but it is probably
74 ;; best to avoid that kind of table when setting up your own as it is an
75 ;; unnecessary complexity in that case. If you have a problem with data from a
76 ;; supported export program, start by testing its specific mapping table instead
77 ;; of the combined one. Here is a handy template to set each of the predefined
78 ;; mapping tables if you would rather avoid the configure interface:
79 ;;
80 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-combined)
81 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-thunderbird)
82 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail)
83 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail-typed-email)
84 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-linkedin)
85 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-web)
86 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-typed-email)
87 ;;
88 ;; The doc string for `bbdb-create-internal' may also be useful when creating a
89 ;; mapping table. Please send any new tables to the maintainer listed in this
90 ;; file. The maintainer should be able to help with any issues and may create a
91 ;; new mapping table given sample data.
92
93 ;;; Misc tips/troubleshooting:
94 ;;
95 ;; - ASynK looks promising for syncing bbdb/google/outlook.
96 ;; - The git repo contains a test folder with exactly tested version info and working
97 ;; test data. Software, and especially online services are prone to changing how they
98 ;; export. Please send feedback if you run into problems.
99 ;; - bbdb doesn't work if you delete the bbdb database file in
100 ;; the middle of an emacs session. If you want to empty the current bbdb database,
101 ;; do M-x bbdb then .* then C-u * d on the beginning of a record.
102 ;; - After changing a mapping table variable, don't forget to re-execute
103 ;; (setq bbdb-csv-import-mapping-table ...) so that it propagates.
104
105 ;;; Bugs, patches, discussion, feedback
106 ;;
107 ;; Patches and bugs are very welcome via https://gitlab.com/iankelling/bbdb-csv-import
108 ;;
109 ;; Questions, feedback, etc are very welcome via email to Ian Kelling
110 ;; <ian@iankelling.org>. I will add any useful questions, answers, etc. to this
111 ;; file. The scope/userbase of this project doesn't justify a mailing list, but if
112 ;; it ever did I would start a mailman or discourse to act as a mailing list
113 ;; and forum.
114
115
116 ;;; Code:
117 (require 'pcsv)
118 (require 'dash)
119 (require 'bbdb-com)
120 (eval-when-compile (require 'cl))
121
122
123 (defconst bbdb-csv-import-thunderbird
124 '((:namelist "First Name" "Last Name")
125 (:name "Display Name")
126 (:aka "Nickname")
127 (:mail "Primary Email" "Secondary Email")
128 (:phone "Work Phone" "Home Phone" "Fax Number" "Pager Number" "Mobile Number")
129 (:address
130 (("home address"
131 (("Home Address" "Home Address 2")
132 "Home City" "Home State"
133 "Home ZipCode" "Home Country"))
134 ("work address"
135 (("Work Address" "Work Address 2")
136 "Work City" "Work State"
137 "Work ZipCode" "Work Country"))))
138 (:organization "Organization")
139 (:xfields "Web Page 1" "Web Page 2" "Birth Year" "Birth Month"
140 "Birth Day" "Department" "Custom 1" "Custom 2" "Custom 3"
141 "Custom 4" "Notes" "Job Title"))
142 "Thunderbird csv format")
143
144 (defconst bbdb-csv-import-linkedin
145 '((:namelist "First Name" "Middle Name" "Last Name")
146 (:affix "Suffix")
147 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
148 (:phone
149 "Assistant's Phone" "Business Fax" "Business Phone"
150 "Business Phone 2" "Callback" "Car Phone"
151 "Company Main Phone" "Home Fax" "Home Phone"
152 "Home Phone 2" "ISDN" "Mobile Phone"
153 "Other Fax" "Other Phone" "Pager"
154 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
155 (:address
156 (("business address"
157 (("Business Street" "Business Street 2" "Business Street 3")
158 "Business City" "Business State"
159 "Business Postal Code" "Business Country"))
160 ("home address"
161 (("Home Street" "Home Street 2" "Home Street 3")
162 "Home City" "Home State"
163 "Home Postal Code" "Home Country"))
164 ("other address"
165 (("Other Street" "Other Street 2" "Other Street 3")
166 "Other City" "Other State"
167 "Other Postal Code" "Other Country"))))
168 (:organization "Company")
169 (:xfields
170 "Department" "Job Title" "Assistant's Name"
171 "Birthday" "Manager's Name" "Notes" "Other Address PO Box"
172 "Spouse" "Web Page" "Personal Web Page"))
173 "Linkedin export in the Outlook csv format.")
174
175
176 (defconst bbdb-csv-import-gmail
177 '((:namelist "Given Name" "Family Name")
178 (:name "Name")
179 (:affix "Name Prefix" "Name Suffix")
180 (:aka "Nickname")
181 (:mail (repeat "E-mail 1 - Value"))
182 (:phone (repeat ("Phone 1 - Type" "Phone 1 - Value")))
183 (:address
184 (repeat (("Address 1 - Type")
185 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
186 "Address 1 - City" "Address 1 - Region"
187 "Address 1 - Postal Code" "Address 1 - Country"))))
188 (:organization (repeat "Organization 1 - Name"))
189 (:xfields
190 "Additional Name" "Yomi Name" "Given Name Yomi"
191 "Additional Name Yomi" "Family Name Yomi"
192 "Initials" "Short Name" "Maiden Name" "Birthday"
193 "Gender" "Location" "Billing Information"
194 "Directory Server" "Mileage" "Occupation"
195 "Hobby" "Sensitivity" "Priority"
196 "Subject" "Notes" "Group Membership"
197 ;; Gmail wouldn't let me add more than 1 organization in its web interface,
198 ;; but no harm in looking for multiple since the field name implies the
199 ;; possibility.
200 (repeat
201 "Organization 1 - Type" "Organization 1 - Yomi Name"
202 "Organization 1 - Title" "Organization 1 - Department"
203 "Organization 1 - Symbol" "Organization 1 - Location"
204 "Organization 1 - Job Description")
205 (repeat ("Relation 1 - Type" "Relation 1 - Value"))
206 (repeat ("Website 1 - Type" "Website 1 - Value"))
207 (repeat ("Event 1 - Type" "Event 1 - Value"))
208 (repeat ("Custom Field 1 - Type" "Custom Field 1 - Value"))))
209 "Gmail csv export format. Note some fields don't map perfectly,
210 feel free to modify them as you wish. \"PO Box\" and \"Extended
211 Address\" are added as additional address street lines if they
212 exist. Some special name fields are made custom instead of put in
213 name, which gets a single string. We map Gmail's \"Name Prefix\"
214 and \"Name Suffix\" to bbdb's affix (a list of strings). We lose
215 the prefix/suffix label, but those are usually obvious.")
216
217
218 (defconst bbdb-csv-import-gmail-typed-email
219 (append (car (last bbdb-csv-import-gmail)) '((repeat "E-mail 1 - Type")))
220 "Like the first Gmail mapping, but use custom fields to store
221 Gmail's email labels. This is separate because I assume most
222 people don't use those labels and using the default labels
223 would create useless custom fields.")
224
225 (defconst bbdb-csv-import-outlook-web
226 '((:namelist "First Name" "Middle Name" "Last Name")
227 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
228 (:affix "Suffix")
229 (:phone
230 "Assistant's Phone" "Business Fax" "Business Phone"
231 "Business Phone 2" "Callback" "Car Phone"
232 "Company Main Phone" "Home Fax" "Home Phone"
233 "Home Phone 2" "ISDN" "Mobile Phone"
234 "Other Fax" "Other Phone" "Pager"
235 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
236 (:address
237 (("business address"
238 (("Business Street")
239 "Business City" "Business State"
240 "Business Postal Code" "Business Country"))
241 ("home address"
242 (("Home Street")
243 "Home City" "Home State"
244 "Home Postal Code" "Home Country"))
245 ("other address"
246 (("Other Street")
247 "Other City" "Other State"
248 "Other Postal Code" "Other Country"))))
249 (:organization "Company")
250 (:xfields
251 "Anniversary" "Family Name Yomi" "Given Name Yomi"
252 "Department" "Job Title" "Birthday" "Manager's Name" "Notes"
253 "Spouse" "Web Page"))
254 "Hotmail.com, outlook.com, live.com, etc.
255 Based on 'Export for outlook.com and other services',
256 not the export for Outlook 2010 and 2013.")
257
258 (defconst bbdb-csv-import-outlook-typed-email
259 (append (car (last bbdb-csv-import-outlook-web)) '((repeat "E-mail 1 - Type")))
260 "Like bbdb-csv-import-gmail-typed-email, but for outlook-web.
261 Adds email labels as custom fields.")
262
263
264 (defun bbdb-csv-import-flatten1 (list)
265 "Flatten LIST by 1 level."
266 (--reduce-from (if (consp it)
267 (-concat acc it)
268 (-snoc acc it))
269 nil list))
270
271
272 (defun bbdb-csv-import-merge-map (root)
273 "Combine two root mappings for making a combined mapping."
274 (bbdb-csv-import-flatten1
275 (list root
276 (-distinct
277 (append
278 (cdr (assoc root bbdb-csv-import-thunderbird))
279 (cdr (assoc root bbdb-csv-import-linkedin))
280 (cdr (assoc root bbdb-csv-import-gmail))
281 (cdr (assoc root bbdb-csv-import-outlook-web)))))))
282
283
284 (defconst bbdb-csv-import-combined
285 (list
286 ;; manually combined for proper ordering
287 '(:namelist "First Name" "Given Name" "Middle Name" "Last Name" "Family Name")
288 (bbdb-csv-import-merge-map :name)
289 (bbdb-csv-import-merge-map :affix)
290 (bbdb-csv-import-merge-map :aka)
291 (bbdb-csv-import-merge-map :mail)
292 (bbdb-csv-import-merge-map :phone)
293 ;; manually combined the addresses. Because it was easier.
294 '(:address
295 (repeat (("Address 1 - Type")
296 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
297 "Address 1 - City" "Address 1 - Region"
298 "Address 1 - Postal Code" "Address 1 - Country")))
299 (("business address"
300 (("Business Street" "Business Street 2" "Business Street 3")
301 "Business City" "Business State"
302 "Business Postal Code" "Business Country"))
303 ("home address"
304 (("Home Street" "Home Street 2" "Home Street 3"
305 "Home Address" "Home Address 2")
306 "Home City" "Home State"
307 "Home Postal Code" "Home ZipCode" "Home Country"))
308 ("work address"
309 (("Work Address" "Work Address 2")
310 "Work City" "Work State"
311 "Work ZipCode" "Work Country"))
312 ("other address"
313 (("Other Street" "Other Street 2" "Other Street 3")
314 "Other City" "Other State"
315 "Other Postal Code" "Other Country"))))
316 (bbdb-csv-import-merge-map :organization)
317 (bbdb-csv-import-merge-map :xfields)))
318
319 (defcustom bbdb-csv-import-mapping-table bbdb-csv-import-combined
320 "The table which maps bbdb fields to csv fields. The default should work for most cases.
321 See the commentary section of this file for more details."
322 :group 'bbdb-csv-import
323 :type 'symbol)
324
325
326 (defun bbdb-csv-import-expand-repeats (csv-fields list)
327 "Return new list where elements from LIST in form (repeat elem1 ...)
328 become ((elem1 ...) [(elem2 ...)] ...) for as many repeating
329 numbered fields exist in the csv fields. elem can be a string or
330 a tree (a list with lists inside it)"
331 (cl-flet ((replace-num (num string)
332 ;; in STRING, replace all groups of numbers with NUM
333 (replace-regexp-in-string "[0-9]+"
334 (number-to-string num)
335 string)))
336 (--reduce-from
337 (if (not (and (consp it) (eq (car it) 'repeat)))
338 (cons it acc)
339 (setq it (cdr it))
340 (let* ((i 1)
341 (first-field (car (-flatten it))))
342 (setq acc (cons it acc))
343 ;; use first-field to test if there is another repetition.
344 (while (member
345 (replace-num (setq i (1+ i)) first-field)
346 csv-fields)
347 (cl-labels ((fun (cell)
348 (if (consp cell)
349 (mapcar #'fun cell)
350 (replace-num i cell))))
351 (setq acc (cons (fun it) acc))))
352 acc))
353 nil list)))
354
355 (defun bbdb-csv-import-map-bbdb (csv-fields root)
356 "ROOT is a root element from bbdb-csv-import-mapping-table. Get
357 the csv-fields for root in the mapping format, including variably
358 repeated ones. Flatten by one because repeated fields are put in
359 sub-lists, but after expanding them, that extra depth is no
360 longer useful. Small trade off: address mappings without 'repeat need
361 to be grouped in a list because they contain sublists that we
362 don't want flattened."
363 (bbdb-csv-import-flatten1
364 (bbdb-csv-import-expand-repeats
365 csv-fields
366 (cdr (assoc root bbdb-csv-import-mapping-table)))))
367
368 ;;;###autoload
369 (defun bbdb-csv-import-file (filename)
370 "Parse and import csv file FILENAME to bbdb.
371 The file will be saved to disk with blank lines and aberrant characters removed."
372 (interactive "fCSV file containg contact data: ")
373 (bbdb-csv-import-buffer (find-file-noselect filename)))
374
375 ;;;###autoload
376 (defun bbdb-csv-import-buffer (&optional buffer-or-name)
377 "Parse and import csv buffer to bbdb. Interactively, it prompts for a buffer.
378 The buffer will be saved to disk with blank lines and aberrant characters removed.
379 BUFFER-OR-NAME is a buffer or name of a buffer, or the current buffer if nil."
380 (interactive "bBuffer containing CSV contact data: ")
381 (when (null bbdb-csv-import-mapping-table)
382 (error "error: `bbdb-csv-import-mapping-table' is nil. Please set it and rerun."))
383 (let* ((csv-buffer (get-buffer (or buffer-or-name (current-buffer))))
384 (csv-data (save-excursion
385 (set-buffer csv-buffer)
386 ;; deal with blank lines and ^M from linkedin
387 (flush-lines "^\\s-*$")
388 (goto-char (point-min))
389 ;; remove ^M aka ret characters
390 (while (re-search-forward (char-to-string 13) nil t)
391 (replace-match ""))
392 (basic-save-buffer)
393 (pcsv-parse-file buffer-file-name)))
394 (csv-fields (car csv-data))
395 (csv-data (cdr csv-data))
396 (allow-dupes bbdb-allow-duplicates)
397 csv-record rd assoc-plus map-bbdb dupes)
398 ;; convenient function names
399 (fset 'rd 'bbdb-csv-import-rd)
400 (fset 'assoc-plus 'bbdb-csv-import-assoc-plus)
401 (fset 'map-bbdb (-partial 'bbdb-csv-import-map-bbdb csv-fields))
402 ;; we handle duplicates ourselves
403 (setq bbdb-allow-duplicates t)
404 ;; loop over the csv records
405 (while (setq csv-record (map 'list 'cons csv-fields (pop csv-data)))
406 (cl-flet*
407 ((ca (key list) (cdr (assoc key list))) ;; utility function
408 (rd-assoc (root)
409 ;; given ROOT, return a list of data, ignoring empty fields
410 (rd (lambda (elem) (assoc-plus elem csv-record)) (map-bbdb root)))
411 (assoc-expand (e)
412 ;; E = data-field-name | (field-name-field data-field)
413 ;; get data from the csv-record and return (field-name data) or nil.
414 (let ((data-name (if (consp e) (ca (car e) csv-record) e))
415 (data (assoc-plus (if (consp e) (cadr e) e) csv-record)))
416 (if data (list data-name data)))))
417 ;; set the arguments to bbdb-create-internal, then call it, the end.
418 (let ((name (let ((name (rd-assoc :namelist)))
419 ;; prioritize any combination of first middle last over :name
420 (if (>= (length name) 2)
421 (mapconcat 'identity name " ")
422 (car (rd-assoc :name)))))
423 (affix (rd-assoc :affix))
424 (aka (rd-assoc :aka))
425 (organization (rd-assoc :organization))
426 (mail (rd-assoc :mail))
427 (phone (rd 'vconcat (rd #'assoc-expand (map-bbdb :phone))))
428 (address (rd (lambda (e)
429
430 (let ((al (rd (lambda (elem) ;; al = address lines
431 (assoc-plus elem csv-record))
432 (caadr e)))
433 ;; to use bbdb-csv-import-combined, we can't mapcar
434 (address-data (--reduce-from (if (member it csv-fields)
435 (cons (ca it csv-record) acc)
436 acc)
437 nil (cdadr e)))
438 (elem-name (car e)))
439 (setq al (nreverse al))
440 (setq address-data (nreverse address-data))
441 ;; make it a list of at least 2 elements
442 (setq al (append al
443 (-repeat (- 2 (length al)) "")))
444 (when (consp elem-name)
445 (setq elem-name (ca (car elem-name) csv-record)))
446
447 ;; determine if non-nil and put together the minimum set
448 (when (or (not (--all? (zerop (length it)) address-data))
449 (not (--all? (zerop (length it)) al)))
450 (when (> 2 (length al))
451 (setcdr (max 2 (nthcdr (--find-last-index (not (null it))
452 al)
453 al)) nil))
454 (vconcat (list elem-name) (list al) address-data))))
455 (map-bbdb :address)))
456 (xfields (rd (lambda (list)
457 (let ((e (car list)))
458 (while (string-match "-" e)
459 (setq e (replace-match "" nil nil e)))
460 (while (string-match " +" e)
461 (setq e (replace-match "-" nil nil e)))
462 (setq e (make-symbol (downcase e)))
463 (cons e (cadr list)))) ;; change from (a b) to (a . b)
464 (rd #'assoc-expand (map-bbdb :xfields)))))
465 ;; we copy and subvert bbdb's duplicate detection instead of catching
466 ;; errors so that we don't interfere with other errors, and can print
467 ;; them nicely at the end.
468 (let (found-dupe)
469 (dolist (elt mail)
470 (when (bbdb-gethash elt '(mail))
471 (push elt dupes)
472 (setq found-dupe t)))
473 (when (or allow-dupes (not found-dupe))
474 (bbdb-create-internal name affix aka organization mail phone address xfields t))))))
475 (when dupes (if allow-dupes
476 (message "Warning, contacts with duplicate email addresses were imported:\n%s" dupes)
477 (message "Skipped contacts with duplicate email addresses:\n%s" dupes)))
478 (setq bbdb-allow-duplicates allow-dupes)))
479
480 (defun bbdb-csv-import-rd (func list)
481 "like mapcar but don't build nil results into the resulting list"
482 (--reduce-from (let ((funcreturn (funcall func it)))
483 (if funcreturn
484 (cons funcreturn acc)
485 acc))
486 nil list))
487
488 (defun bbdb-csv-import-assoc-plus (key list)
489 "Like (cdr assoc ...) but turn an empty string result to nil."
490 (let ((result (cdr (assoc key list))))
491 (when (not (string= "" result))
492 result)))
493
494 (defun bbdb-csv-anonymize-current-buffer ()
495 (interactive)
496 "Anonymize the current buffer which contains csv data.
497 The first line should contain header names."
498 (goto-line 2)
499 (while (re-search-forward "\\w")
500 (delete-char -1)
501 (insert (number-to-string (random 9)))))
502
503
504 (provide 'bbdb-csv-import)
505
506 ;;; bbdb-csv-import.el ends here