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