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