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