-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathorg-onenote.el
339 lines (268 loc) · 11.7 KB
/
org-onenote.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
;;; org-onenote.el --- export org-mode document to onenote.
;; Copyright (C) 2017 Frei Zhang
;; Author: Frei Zhang <[email protected]>
;; Maintainer: Frei Zhang <[email protected]>
;; Homepage: https://github.com/ifree/org-onenote
;; Created: 15th Aug 2017
;; Version: 0.1.0
;; Keywords: tools, docs, org-mode, onenote
;; Package-Requires: ((oauth2 "0.11") (request "0.2.0") (org "8.2.10"))
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file LICENSE. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;;; Summary
;; this package provides org-mode buffer to onenote exporting, images and code
;; highlighting are supported.
;;; Usage
;; before post your document to onenote, you need grant access to org-onenote for
;; accessing your onenote by invoke `org-onenote-start-authenticate`.
;; to specify which section your org document will post to, you need add custom org
;; keyword "ONENOTE-SECTION" to it. eg.
;; #+ONENOTE-SECTION: Frei's Notebook/Tech Notes/Common
;; org-onenote will look up section id from `org-onenote-section-map` by your
;; specified section, which can be generate by `onenote-insert-section-map-at-pt`
;; eg.
;; (setq org-onenote-section-map '(("Frei's Notebook/Programming Language/C++"
;; . "THE-ID")))
;; to post your document by invoke `org-onenote-submit-page`, server side note id
;; will be recorded after a successful post. You can delete it by invoke
;; `org-onenote-delete-page`
;;; TODO: patch
;;; Code:
(require 'oauth2)
(require 'request)
(require 'mailcap) ;for mime type detection
(require 'org-element) ;org element api
(require 'ox) ;org export api
(defvar org-onenote-auth-url "https://login.live.com/oauth20_authorize.srf")
(defvar org-onenote-auth-implicit-grant-url "https://login.live.com/oauth20_desktop.srf")
;;; https://blogs.msdn.microsoft.com/onenotedev/2014/03/28/authenticating-with-the-org-onenote-apis/
(defvar org-onenote-auth-scope "wl.offline_access offline_access office.onenote_create office.onenote_update_by_app office.onenote_update office.onenote")
(defvar org-onenote-token-refresh-url "https://login.live.com/oauth20_token.srf")
(defvar org-onenote-token-refresh-type "application/x-www-form-urlencoded" )
;;; www prefix is required, otherwise will cause 301.
(defvar org-onenote-api-host "https://www.onenote.com/api");"https://private-anon-2d7c3b9948-onenote.apiary-proxy.com"
;;; resource paths
(defvar org-onenote-api-path-notebooks "/v1.0/me/notes/notebooks")
(defvar org-onenote-api-path-sections "/v1.0/me/notes/sections")
(defvar org-onenote-api-path-section-groups "/v1.0/me/notes/sectiongroups")
(defvar org-onenote-api-path-pages "/v1.0/me/notes/pages")
(defvar org-onenote-api-path-pages-post "/v1.0/me/notes/sections/%s/pages")
(defvar org-onenote-api-path-pages-delete "/v1.0/me/notes/pages/%s/")
(defvar org-onenote--stored-token nil)
;; get image width&height
(defvar org-onenote-get-img-dimenton-func (lambda (file)
(when (executable-find "identify")
(shell-command-to-string (concat "identify -format \"width='%w' height='%h'\" " file)))))
;;; org stuff
(defconst org-onenote--keyword-section-name "ONENOTE-SECTION")
(defconst org-onenote--keyword-page-id "ONENOTE-PAGE-ID")
(defconst org-onenote--data-image-block-name "ONENOTE-ORG-IMG")
;;; custom variables
(defgroup org-onenote nil
"Export org-mode buffers to onenote."
:group 'applications
:group 'org
:prefix "org-onenote-")
(defcustom org-onenote-client-id "d6c99b4d-fda1-48f0-9e0f-22103e544413"
"Oneonte app client id, you can register yours on onenote dev site.")
(defcustom org-onenote-token-file
(concat user-emacs-directory "org-onenote-oauth2.plstore")
"Plstore to store onenote oauth2 token, also be used for token expiration detection based on file modification time. Will dynamic bind oauth2-token-file...")
(defcustom org-onenote-token-expire-time 4500
"Default oauth2 refresh token expiration time.")
(defcustom org-onenote-section-map nil
"Onenote section name-id mapping. Can be generated by call `onenote-build-section-map-from-response` or `onenote-insert-section-map-at-pt` to build."
:type '(alist :value-type (group string)))
(defcustom org-onenote-html-template
"<!DOCTYPE html>
<html>
<head>
<title>%s</title>
<meta name=\"created\" content=\"%s\"/>
</head>
<body>
<div data-id=\"main_content\">%s<div>
</body>
</html>"
"Html template.")
;;;###autoload
(defun org-onenote-start-authenticate ()
"Start OAuth2 authenticate."
(interactive)
(let ((oauth2-token-file org-onenote-token-file))
(setq org-onenote--stored-token
(oauth2-auth-and-store org-onenote-auth-url org-onenote-token-refresh-url org-onenote-auth-scope org-onenote-client-id nil org-onenote-auth-implicit-grant-url))))
(defun org-onenote-get-auth-token ()
"Get raw auth token."
(oauth2-token-access-token org-onenote--stored-token))
(defun org-onenote-may-refresh-token ()
"Refresh token based on token store modification time."
(let ((token-modify-time (nth 5(file-attributes org-onenote-token-file)))
(now (current-time)))
(when (time-less-p (time-add token-modify-time org-onenote-token-expire-time) now)
(setq org-onenote--stored-token (oauth2-refresh-access org-onenote--stored-token)))))
(defun org-onenote-api-call (path &rest args)
"Call onenote API.
Argument PATH is the REST API path.
Optional argument ARGS are request arguments for request.el."
(org-onenote-may-refresh-token)
(let ((headers (plist-get args :headers))
(bearer-header (oauth2-authz-bearer-header (org-onenote-get-auth-token)))) ;insert auth token
(plist-put args :headers (push bearer-header headers ))
(plist-put args :parser (or (plist-get args :parser) 'json-read))
(apply #'request (concat org-onenote-api-host path) args)))
(defun org-onenote-build-section-map-from-response (response)
"Build section map from RESPONSE.
Construct `(Notebook/[SectionGroup]/Section . Section-id)` like assoc list for section id lookup."
(let ((data (assoc-default 'value response)))
(mapcar
(lambda (itm)
(let ((id (assoc-default 'id itm))
(pname (assoc-default 'name (assoc-default 'parentNotebook itm)))
(gname (assoc-default 'name (assoc-default 'parentSectionGroup itm)))
(name (assoc-default 'name itm)))
`(,(concat pname "/" (when gname (concat gname "/")) name) . ,id)))
data)))
;;;###autoload
(defun org-onenote-insert-section-map-at-pt ()
"Insert section map at current point. You may use it as your config."
(interactive)
(org-onenote-api-call org-onenote-api-path-sections
:success
(cl-function
(lambda
(&key data &allow-other-keys)
(prin1
(org-onenote-build-section-map-from-response data)
(current-buffer))))))
(defun org-onenote-get-section-id (name)
"Get section id from `org-onenote-section-map` by NAME."
(assoc-default name org-onenote-section-map))
;;; org stuff
(defun org-onenote-process-image ()
"Processing image tag."
(let ((re "<img\s*src=\"\\([^\"]+\\)\"")
(start-index 0)
ret '())
(save-excursion
(goto-char (point-min))
(while (re-search-forward re nil t)
(let ((src (match-string-no-properties 1))
(block-name (format "%s%d" org-onenote--data-image-block-name start-index)))
(save-match-data
(when (string-match "file:\\([^]]*\\)" src)
(setq src (substring src 5))))
(when (file-exists-p src)
(setq src (expand-file-name src))
(replace-match (format "<img src=\"name:%s\" %s" block-name (funcall org-onenote-get-img-dimenton-func src)))
(setq ret (push `(,block-name . (,block-name :file ,src :mime-type ,(mailcap-extension-to-mime (file-name-extension src)))) ret))
(setq start-index (1+ start-index))))))
ret))
(defun org-onenote-html-get-request-data ()
"Export ‘org-mode’ BUFFER to post data."
(let ((org-export-show-temporary-export-buffer nil)
(title (substring-no-properties
(or (car (plist-get
(org-export-get-environment)
:title))
(file-name-nondirectory
(file-name-sans-extension
(buffer-file-name))))))
(time (format-time-string "%Y-%m-%dT%T"))
ret)
(save-excursion
(org-html-export-as-html nil nil t t '(:html-doctype "xhtml5"))
(with-current-buffer "*Org HTML Export*"
(setq ret (org-onenote-process-image))
(setq ret
(push `("Presentation" . ("Presentation"
:data ,(format
org-onenote-html-template
title
time
(buffer-substring-no-properties
(point-min)
(point-max)))
:mime-type "application/xhtml+xml"))
ret))
(kill-buffer)))
ret))
(defun org-onenote-get-keyword-val (key &optional buffer)
"Get value from #+keyword tag identify by KEY in BUFFER."
(with-current-buffer (or buffer (current-buffer))
(let ((props (org-element-parse-buffer 'greater-element t)))
(org-element-map props 'keyword
(lambda (item)
(when (equal (org-element-property :key item)
key)
(org-element-property :value item)))))))
(defun org-onenote-set-keyword-val (key value &optional force)
"Set keyword(identify by KEY) with given VALUE use FORCE when the BUFFER no such keyword."
(let ((re "#\\+\\([^\:]+\\)\\:\s*\\(.*\\)$")
found)
(save-excursion
(goto-char (point-min))
(while (re-search-forward re nil t)
(when (string= (match-string 1) key)
(setq found t)
(replace-match (concat "#+\\1: " value))
(goto-char (match-end 2))))
(when (and (not found) force)
(insert (format "\n#+%s: %s" key value))))))
(defun org-onenote-submit-done-callback (data)
"Handle response DATA."
(let ((id (assoc-default 'id data)))
(if id
(org-onenote-set-keyword-val
org-onenote--keyword-page-id
id t)
(message "invalid response"))))
;;;###autoload
(defun org-onenote-submit-page ()
"Submit it."
(interactive)
;; if-let?
(let* ((section-name (org-onenote-get-keyword-val org-onenote--keyword-section-name))
(section-id (org-onenote-get-section-id (car section-name))))
(when section-id
(let* ((files (org-onenote-html-get-request-data)))
(org-onenote-api-call
(format org-onenote-api-path-pages-post section-id)
:type "POST"
:success (cl-function (lambda (&key data &allow-other-keys)
(message "post success!")
(org-onenote-submit-done-callback data)))
:error (cl-function (lambda (&key data &allow-other-keys)
(message "error!")
(print data)))
:files files)))))
;;;###autoload
(defun org-onenote-delete-page (&optional id)
"Delete page from server by optional ID, default current page."
(interactive)
(let ((page-id (or id (car (org-onenote-get-keyword-val org-onenote--keyword-page-id)))))
(when page-id
(org-onenote-api-call
(format org-onenote-api-path-pages-delete page-id)
:type "DELETE"
:success (cl-function (lambda (&key data &allow-other-keys)
(message "delete success!")
(org-onenote-set-keyword-val org-onenote--keyword-page-id nil)
))
:error (cl-function (lambda (&key data &allow-other-keys)
(message "error!")
(print data)))))))
(provide 'org-onenote)
;;; org-onenote.el ends here