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