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