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 ;; Mapping table tips: For field names or sets of field names which go together,
94 ;; and are numbered, 1, 2, 3, the repeat keyword can be used to expand as many
95 ;; as are in your csv data.
96
97 ;;; Misc tips/troubleshooting:
98 ;;
99 ;; - ASynK looks promising for syncing bbdb/google/outlook.
100 ;; - The git repo contains a test folder with exactly tested version info and working
101 ;; test data. Software, and especially online services are prone to changing how they
102 ;; export. Please send feedback if you run into problems.
103 ;; - bbdb doesn't work if you delete the bbdb database file in
104 ;; the middle of an emacs session. If you want to empty the current bbdb database,
105 ;; do M-x bbdb then .* then C-u * d on the beginning of a record.
106 ;; - After changing a mapping table variable, don't forget to re-execute
107 ;; (setq bbdb-csv-import-mapping-table ...) so that it propagates.
108
109 ;;; Bugs, patches, discussion, feedback
110 ;;
111 ;; Patches and bugs are very welcome via https://gitlab.com/iankelling/bbdb-csv-import
112 ;;
113 ;; Questions, feedback, or anything is very welcome at to the bbdb-csv-import mailing list
114 ;; https://lists.iankelling.org/listinfo/bbdb-csv-import, no subscription needed to post via
115 ;; bbdb-csv-import@lists.iankelling.org
116
117
118
119 ;;; Code:
120 (require 'pcsv)
121 (require 'dash)
122 (require 'bbdb-com)
123 (eval-when-compile (require 'cl))
124
125
126 (defconst bbdb-csv-import-thunderbird
127 '((:namelist "First Name" "Last Name")
128 (:name "Display Name")
129 (:aka "Nickname")
130 (:mail "Primary Email" "Secondary Email")
131 (:phone "Work Phone" "Home Phone" "Fax Number" "Pager Number" "Mobile Number")
132 (:address
133 (("home address"
134 (("Home Address" "Home Address 2")
135 "Home City" "Home State"
136 "Home ZipCode" "Home Country"))
137 ("work address"
138 (("Work Address" "Work Address 2")
139 "Work City" "Work State"
140 "Work ZipCode" "Work Country"))))
141 (:organization "Organization")
142 (:xfields "Web Page 1" "Web Page 2" "Birth Year" "Birth Month"
143 "Birth Day" "Department" "Custom 1" "Custom 2" "Custom 3"
144 "Custom 4" "Notes" "Job Title"))
145 "Thunderbird csv format")
146
147 (defconst bbdb-csv-import-linkedin
148 '((:namelist "First Name" "Middle Name" "Last Name")
149 (:affix "Suffix")
150 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
151 (:phone
152 "Assistant's Phone" "Business Fax" "Business Phone"
153 "Business Phone 2" "Callback" "Car Phone"
154 "Company Main Phone" "Home Fax" "Home Phone"
155 "Home Phone 2" "ISDN" "Mobile Phone"
156 "Other Fax" "Other Phone" "Pager"
157 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
158 (:address
159 (("business address"
160 (("Business Street" "Business Street 2" "Business Street 3")
161 "Business City" "Business State"
162 "Business Postal Code" "Business Country"))
163 ("home address"
164 (("Home Street" "Home Street 2" "Home Street 3")
165 "Home City" "Home State"
166 "Home Postal Code" "Home Country"))
167 ("other address"
168 (("Other Street" "Other Street 2" "Other Street 3")
169 "Other City" "Other State"
170 "Other Postal Code" "Other Country"))))
171 (:organization "Company")
172 (:xfields
173 "Department" "Job Title" "Assistant's Name"
174 "Birthday" "Manager's Name" "Notes" "Other Address PO Box"
175 "Spouse" "Web Page" "Personal Web Page"))
176 "Linkedin export in the Outlook csv format.")
177
178
179 (defconst bbdb-csv-import-gmail
180 '((:namelist "Given Name" "Family Name")
181 (:name "Name")
182 (:affix "Name Prefix" "Name Suffix")
183 (:aka "Nickname")
184 (:mail (repeat "E-mail 1 - Value"))
185 (:phone (repeat ("Phone 1 - Type" "Phone 1 - Value")))
186 (:address
187 (repeat (("Address 1 - Type")
188 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
189 "Address 1 - City" "Address 1 - Region"
190 "Address 1 - Postal Code" "Address 1 - Country"))))
191 (:organization (repeat "Organization 1 - Name"))
192 (:xfields
193 "Additional Name" "Yomi Name" "Given Name Yomi"
194 "Additional Name Yomi" "Family Name Yomi"
195 "Initials" "Short Name" "Maiden Name" "Birthday"
196 "Gender" "Location" "Billing Information"
197 "Directory Server" "Mileage" "Occupation"
198 "Hobby" "Sensitivity" "Priority"
199 "Subject" "Notes" "Group Membership"
200 ;; Gmail wouldn't let me add more than 1 organization in its web interface,
201 ;; but no harm in looking for multiple since the field name implies the
202 ;; possibility.
203 (repeat
204 "Organization 1 - Type" "Organization 1 - Yomi Name"
205 "Organization 1 - Title" "Organization 1 - Department"
206 "Organization 1 - Symbol" "Organization 1 - Location"
207 "Organization 1 - Job Description")
208 (repeat ("Relation 1 - Type" "Relation 1 - Value"))
209 (repeat ("Website 1 - Type" "Website 1 - Value"))
210 (repeat ("Event 1 - Type" "Event 1 - Value"))
211 (repeat ("Custom Field 1 - Type" "Custom Field 1 - Value"))))
212 "Gmail csv export format. Note some fields don't map perfectly,
213 feel free to modify them as you wish. \"PO Box\" and \"Extended
214 Address\" are added as additional address street lines if they
215 exist. Some special name fields are made custom instead of put in
216 name, which gets a single string. We map Gmail's \"Name Prefix\"
217 and \"Name Suffix\" to bbdb's affix (a list of strings). We lose
218 the prefix/suffix label, but those are usually obvious.")
219
220
221 (defconst bbdb-csv-import-gmail-typed-email
222 (append (car (last bbdb-csv-import-gmail)) '((repeat "E-mail 1 - Type")))
223 "Like the first Gmail mapping, but use custom fields to store
224 Gmail's email labels. This is separate because I assume most
225 people don't use those labels and using the default labels
226 would create useless custom fields.")
227
228 (defconst bbdb-csv-import-outlook-web
229 '((:namelist "First Name" "Middle Name" "Last Name")
230 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
231 (:affix "Suffix")
232 (:phone
233 "Assistant's Phone" "Business Fax" "Business Phone"
234 "Business Phone 2" "Callback" "Car Phone"
235 "Company Main Phone" "Home Fax" "Home Phone"
236 "Home Phone 2" "ISDN" "Mobile Phone"
237 "Other Fax" "Other Phone" "Pager"
238 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
239 (:address
240 (("business address"
241 (("Business Street")
242 "Business City" "Business State"
243 "Business Postal Code" "Business Country"))
244 ("home address"
245 (("Home Street")
246 "Home City" "Home State"
247 "Home Postal Code" "Home Country"))
248 ("other address"
249 (("Other Street")
250 "Other City" "Other State"
251 "Other Postal Code" "Other Country"))))
252 (:organization "Company")
253 (:xfields
254 "Anniversary" "Family Name Yomi" "Given Name Yomi"
255 "Department" "Job Title" "Birthday" "Manager's Name" "Notes"
256 "Spouse" "Web Page"))
257 "Hotmail.com, outlook.com, live.com, etc.
258 Based on 'Export for outlook.com and other services',
259 not the export for Outlook 2010 and 2013.")
260
261 (defconst bbdb-csv-import-outlook-typed-email
262 (append (car (last bbdb-csv-import-outlook-web)) '((repeat "E-mail 1 - Type")))
263 "Like bbdb-csv-import-gmail-typed-email, but for outlook-web.
264 Adds email labels as custom fields.")
265
266
267 (defun bbdb-csv-import-flatten1 (list)
268 "Flatten LIST by 1 level."
269 (--reduce-from (if (consp it)
270 (-concat acc it)
271 (-snoc acc it))
272 nil list))
273
274
275 (defun bbdb-csv-import-merge-map (root)
276 "Combine two root mappings for making a combined mapping."
277 (bbdb-csv-import-flatten1
278 (list root
279 (-distinct
280 (append
281 (cdr (assoc root bbdb-csv-import-thunderbird))
282 (cdr (assoc root bbdb-csv-import-linkedin))
283 (cdr (assoc root bbdb-csv-import-gmail))
284 (cdr (assoc root bbdb-csv-import-outlook-web)))))))
285
286
287 (defconst bbdb-csv-import-combined
288 (list
289 ;; manually combined for proper ordering
290 '(:namelist "First Name" "Given Name" "Middle Name" "Last Name" "Family Name")
291 (bbdb-csv-import-merge-map :name)
292 (bbdb-csv-import-merge-map :affix)
293 (bbdb-csv-import-merge-map :aka)
294 (bbdb-csv-import-merge-map :mail)
295 (bbdb-csv-import-merge-map :phone)
296 ;; manually combined the addresses. Because it was easier.
297 '(:address
298 (repeat (("Address 1 - Type")
299 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
300 "Address 1 - City" "Address 1 - Region"
301 "Address 1 - Postal Code" "Address 1 - Country")))
302 (("business address"
303 (("Business Street" "Business Street 2" "Business Street 3")
304 "Business City" "Business State"
305 "Business Postal Code" "Business Country"))
306 ("home address"
307 (("Home Street" "Home Street 2" "Home Street 3"
308 "Home Address" "Home Address 2")
309 "Home City" "Home State"
310 "Home Postal Code" "Home ZipCode" "Home Country"))
311 ("work address"
312 (("Work Address" "Work Address 2")
313 "Work City" "Work State"
314 "Work ZipCode" "Work Country"))
315 ("other address"
316 (("Other Street" "Other Street 2" "Other Street 3")
317 "Other City" "Other State"
318 "Other Postal Code" "Other Country"))))
319 (bbdb-csv-import-merge-map :organization)
320 (bbdb-csv-import-merge-map :xfields)))
321
322 (defcustom bbdb-csv-import-mapping-table bbdb-csv-import-combined
323 "The table which maps bbdb fields to csv fields. The default should work for most cases.
324 See the commentary section of this file for more details."
325 :group 'bbdb-csv-import
326 :type 'symbol)
327
328
329 (defun bbdb-csv-import-expand-repeats (csv-fields list)
330 "Return new list where elements from LIST in form (repeat elem1
331 ...) become ((elem1 ...) [(elem2 ...)] ...) for as many fields
332 exist in the csv fields. elem can be a string or a tree (a list
333 with lists inside it). We use the first element as a template,
334 and increase its number by one, and check if it exists, and then
335 increment any other elements from the repeat list which have
336 numbers in them."
337 (cl-flet ((replace-num (num string)
338 ;; in STRING, replace all groups of numbers with NUM
339 (replace-regexp-in-string "[0-9]+"
340 (number-to-string num)
341 string)))
342 (--reduce-from
343 (if (not (and (consp it) (eq (car it) 'repeat)))
344 (cons it acc)
345 (setq it (cdr it))
346 (let* ((i 1)
347 (first-field (car (-flatten it))))
348 (setq acc (cons it acc))
349 ;; use first-field to test if there is another repetition.
350 (while (member
351 (replace-num (setq i (1+ i)) first-field)
352 csv-fields)
353 (cl-labels ((fun (cell)
354 (if (consp cell)
355 (mapcar #'fun cell)
356 (replace-num i cell))))
357 (setq acc (cons (fun it) acc))))
358 acc))
359 nil list)))
360
361 (defun bbdb-csv-import-map-bbdb (csv-fields root)
362 "ROOT is a root element from bbdb-csv-import-mapping-table. Get
363 the csv-fields for root in the mapping format, including variably
364 repeated ones. Flatten by one because repeated fields are put in
365 sub-lists, but after expanding them, that extra depth is no
366 longer useful. Small trade off: address mappings without 'repeat need
367 to be grouped in a list because they contain sublists that we
368 don't want flattened."
369 (bbdb-csv-import-flatten1
370 (bbdb-csv-import-expand-repeats
371 csv-fields
372 (cdr (assoc root bbdb-csv-import-mapping-table)))))
373
374 ;;;###autoload
375 (defun bbdb-csv-import-file (filename)
376 "Parse and import csv file FILENAME to bbdb.
377 The file will be saved to disk with blank lines and aberrant characters removed."
378 (interactive "fCSV file containg contact data: ")
379 (bbdb-csv-import-buffer (find-file-noselect filename)))
380
381 ;;;###autoload
382 (defun bbdb-csv-import-buffer (&optional buffer-or-name)
383 "Parse and import csv buffer to bbdb. Interactively, it prompts for a buffer.
384 The buffer will be saved to disk with blank lines and aberrant characters removed.
385 BUFFER-OR-NAME is a buffer or name of a buffer, or the current buffer if nil."
386 (interactive "bBuffer containing CSV contact data: ")
387 (when (null bbdb-csv-import-mapping-table)
388 (error "error: `bbdb-csv-import-mapping-table' is nil. Please set it and rerun."))
389 (let* ((csv-buffer (get-buffer (or buffer-or-name (current-buffer))))
390 (csv-data (save-excursion
391 (set-buffer csv-buffer)
392 ;; deal with blank lines and ^M from linkedin
393 (flush-lines "^\\s-*$")
394 (goto-char (point-min))
395 ;; remove ^M aka ret characters
396 (while (re-search-forward (char-to-string 13) nil t)
397 (replace-match ""))
398 (basic-save-buffer)
399 (pcsv-parse-file buffer-file-name)))
400 (csv-fields (car csv-data))
401 (csv-data (cdr csv-data))
402 (allow-dupes bbdb-allow-duplicates)
403 csv-record rd assoc-plus map-bbdb dupes)
404 ;; convenient function names
405 (fset 'rd 'bbdb-csv-import-rd)
406 (fset 'assoc-plus 'bbdb-csv-import-assoc-plus)
407 (fset 'map-bbdb (-partial 'bbdb-csv-import-map-bbdb csv-fields))
408 ;; we handle duplicates ourselves
409 (setq bbdb-allow-duplicates t)
410 ;; loop over the csv records
411 (while (setq csv-record (map 'list 'cons csv-fields (pop csv-data)))
412 (cl-flet*
413 ((ca (key list) (cdr (assoc key list))) ;; utility function
414 (rd-assoc (root)
415 ;; given ROOT, return a list of data, ignoring empty fields
416 (rd (lambda (elem) (assoc-plus elem csv-record)) (map-bbdb root)))
417 (assoc-expand (e)
418 ;; E = data-field-name | (field-name-field data-field)
419 ;; get data from the csv-record and return (field-name data) or nil.
420 (let ((data-name (if (consp e) (ca (car e) csv-record) e))
421 (data (assoc-plus (if (consp e) (cadr e) e) csv-record)))
422 (if data (list data-name data)))))
423 ;; set the arguments to bbdb-create-internal, then call it, the end.
424 (let ((name (let ((name (rd-assoc :namelist)))
425 ;; prioritize any combination of first middle last over :name
426 (if (>= (length name) 2)
427 (mapconcat 'identity name " ")
428 (car (rd-assoc :name)))))
429 (affix (rd-assoc :affix))
430 (aka (rd-assoc :aka))
431 (organization (rd-assoc :organization))
432 (mail (rd-assoc :mail))
433 (phone (rd 'vconcat (rd #'assoc-expand (map-bbdb :phone))))
434 (address (rd (lambda (e)
435
436 (let ((al (rd (lambda (elem) ;; al = address lines
437 (assoc-plus elem csv-record))
438 (caadr e)))
439 ;; to use bbdb-csv-import-combined, we can't mapcar
440 (address-data (--reduce-from (if (member it csv-fields)
441 (cons (ca it csv-record) acc)
442 acc)
443 nil (cdadr e)))
444 (elem-name (car e)))
445 (setq al (nreverse al))
446 (setq address-data (nreverse address-data))
447 ;; make it a list of at least 2 elements
448 (setq al (append al
449 (-repeat (- 2 (length al)) "")))
450 (when (consp elem-name)
451 (setq elem-name (ca (car elem-name) csv-record)))
452
453 ;; determine if non-nil and put together the minimum set
454 (when (or (not (--all? (zerop (length it)) address-data))
455 (not (--all? (zerop (length it)) al)))
456 (when (> 2 (length al))
457 (setcdr (max 2 (nthcdr (--find-last-index (not (null it))
458 al)
459 al)) nil))
460 (vconcat (list elem-name) (list al) address-data))))
461 (map-bbdb :address)))
462 (xfields (rd (lambda (list)
463 (let ((e (car list)))
464 (while (string-match "-" e)
465 (setq e (replace-match "" nil nil e)))
466 (while (string-match " +" e)
467 (setq e (replace-match "-" nil nil e)))
468 (setq e (make-symbol (downcase e)))
469 (cons e (cadr list)))) ;; change from (a b) to (a . b)
470 (rd #'assoc-expand (map-bbdb :xfields)))))
471 ;; we copy and subvert bbdb's duplicate detection instead of catching
472 ;; errors so that we don't interfere with other errors, and can print
473 ;; them nicely at the end.
474 (let (found-dupe)
475 (dolist (elt mail)
476 (when (bbdb-gethash elt '(mail))
477 (push elt dupes)
478 (setq found-dupe t)))
479 (when (or allow-dupes (not found-dupe))
480 (bbdb-create-internal name affix aka organization mail phone address xfields t))))))
481 (when dupes (if allow-dupes
482 (message "Warning, contacts with duplicate email addresses were imported:\n%s" dupes)
483 (message "Skipped contacts with duplicate email addresses:\n%s" dupes)))
484 (setq bbdb-allow-duplicates allow-dupes)))
485
486 (defun bbdb-csv-import-rd (func list)
487 "like mapcar but don't build nil results into the resulting list"
488 (--reduce-from (let ((funcreturn (funcall func it)))
489 (if funcreturn
490 (cons funcreturn acc)
491 acc))
492 nil list))
493
494 (defun bbdb-csv-import-assoc-plus (key list)
495 "Like (cdr assoc ...) but turn an empty string result to nil."
496 (let ((result (cdr (assoc key list))))
497 (when (not (string= "" result))
498 result)))
499
500 (defun bbdb-csv-anonymize-current-buffer ()
501 (interactive)
502 "Anonymize the current buffer which contains csv data.
503 The first line should contain header names."
504 (goto-line 2)
505 (while (re-search-forward "\\w")
506 (delete-char -1)
507 (insert (number-to-string (random 9)))))
508
509
510 (provide 'bbdb-csv-import)
511
512 ;;; bbdb-csv-import.el ends here