-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathorg-notion.el
1832 lines (1672 loc) · 60.8 KB
/
org-notion.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; org-notion.el --- Notion.so + Org-mode -*- lexical-binding: t; -*-
;; Copyright (C) 2022 ellis
;; Author: ellis <ellis@rwest.io>
;; Version: 0.1.0
;; Keywords: wp, extensions
;; Package-Requires: ((emacs "28.1"))
;; 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 of the License, 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 this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; org-notion is a simple package that integrates the beauty and
;; convenience of Notion with your Org-mode workflow.
;;
;;
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'org)
(require 'org-element)
(require 'eieio)
(require 'auth-source)
(require 'json)
(require 'url)
;;; Constants
;;
(defconst org-notion-host "api.notion.com"
"FQDN of Notion API. This is used to create an entry with
`auth-source-secrets-create'.")
(defconst org-notion-version "2021-08-16"
"Notion API Version")
(defconst org-notion-max-page-size 100
"Default count of results returned by Notion. Additional calls
will be made to collect all results using the `start_cursor'
parameter. Maximum value is 100.")
(defconst org-notion-method-types '(search current-user user
users database query-database
create-database
update-database page
page-property create-page
update-page block
block-children update-block
append-block delete-block)
"Method types available for Notion API requests, used by
`org-notion-request' class.")
(defconst org-notion-block-types '(paragraph heading_1 heading_2
heading_3 bulleted_list_item
numbered_list_item to_do
toggle child_page
child_database embed image
video file pdf bookmark
callout quote code equation
divider table_of_contents
breadcrumb column column_list
link_preview synced_block
template link_to_page table
table_row unsupported)
"Type of blocks available for Notion API, used by
`org-notion-block' class. `unsupported' refers to an unsupported
block type.")
(defconst org-notion-color-types '(default gray brown orange
yellow green blue purple pink
red gray_background
brown_background
orange_background
yellow_background
green_background
blue_background
purple_background
pink_background
red_background)
"Colors available for Notion API text objects, used by
`org-notion-rich-text' class.")
(defconst org-notion-annotation-types '(bold italic strikethrough
underline code)
"Annotations available for Notion API text objects, used by
`org-notion-rich-text' class.")
(defconst org-notion-mention-types '(user page database date link_preview)
"Mention types available for Notion API text objects, used by
`org-notion-rich-text' class.")
(defconst org-notion-property-types '(rich_text number select multi_select
date formula relation rollup
title people files checkbox
url email phone_number created_time
created_by last_edited_time last_edited_by)
"Notion default property_item types.")
(defconst org-notion-parent-types '(database page workspace block)
"Notion parent object types.")
;;; Custom
;;
(defgroup org-notion nil
"Customization group for org-notion."
:tag "Org Notion"
:group 'org)
(defcustom org-notion-use-auth-source t
"Check auth-source for Notion integration token. Falls back to
interactive prompt if token isn't found."
:type 'boolean
:group 'org-notion)
(defcustom org-notion-coding-system 'utf-8
"Use custom coding system for org-notion."
:type 'symbol
:group 'org-notion)
(defcustom org-notion-cache-enable t
"Enable org-notion object cache if value is non-nil. Note that the
default caching behavior is to write a message and retur nil when
attempting to insert a duplicate object, which occurs often in
testing and cause `should' to return unexpected results."
:type 'boolean
:group 'org-notion)
(defcustom org-notion-cache-overwrite nil
"Enable org-notion-cache overwrite on insert if value is non-nil. By
default, duplicate inserts into the cache will log a message
without modifying the current value. When this is enabled, a
message is still logged (disable with `org-notion-verbosity'),
but the current value is replaced."
:group 'org-notion
:type 'boolean)
(defcustom org-notion-completion-ignore-case t
"org-notion specific value of `completion-ignore-case'"
:group 'org-notion
:type 'boolean)
(defcustom org-notion-completion-list t
"Control the behaviour of org-notion completion functions.
If a list of symbols, specify which fields to complete.
Symbols include
id (= object uuid)
type (= sub-type of object)
parent (= object parent)
email (= user email address)
If t, completion is done for all of the above. If nil, no
completion is offered.
"
:group 'org-notion
:type '(choice (const :tag "No Completion" nil)
(const :tag "Complete all fields" t)
(repeat :tag "Field"
(choice (const id)
(const type)
(const parent)
(const email)))))
(defcustom org-notion-push-hook nil
"Hook to run after `org-notion-push'"
:type 'hook
:group 'org-notion)
(defcustom org-notion-pull-hook nil
"Hook to run after `org-notion-pull'"
:type 'hook
:group 'org-notion)
(defcustom org-notion-keymap-prefix "C-c n"
"Prefix for org-notion-mode keybinds."
:type 'string
:group 'org-notion)
;;; Vars
;;
(defvar org-notion-endpoint (format "https://%s/v1/" org-notion-host)
"URI of Notion API endpoint")
(defvar org-notion-uuid-regexp "\\<[[:xdigit:]]\\{8\\}-?[[:xdigit:]]\\{4\\}-?[[:xdigit:]]\\{4\\}-?[[:xdigit:]]\\{4\\}-?[[:xdigit:]]\\{12\\}\\>"
"A regular expression matching a UUID with or without hyphens.")
(defvar org-notion-hashtable (make-hash-table :test #'equal)
"Hashtable for `org-notion-class' instances.")
(defvar org-notion-verbosity 'debug
"Level of verbosity for `org-notion' logging.")
(defvar org-notion-current-user nil
"Current Notion user. This may be a user created via Notion API
integration.")
(defvar org-notion-dispatch-sync-sleep 0.05
"Time to sleep for between checks on
`org-notion-last-dispatch-result'. Only applies to synchronous
calls to `org-notion-dispatch' (:async nil).")
(defvar org-notion-last-dispatch-result nil
"value of last `org-notion-dispatch' call.")
(defvar org-notion-field-org-keys
'((id . "NOTION_ID")
(user . "NOTION_USER")
(email . "NOTION_EMAIL")
(cover . "NOTION_COVER")
(icon . "NOTION_ICON")
(created . "CREATED")
(updated . "UPDATED")
(parent . "NOTION_PARENT")
(archived . "NOTION_ARCHIVED")
(url . "NOTION_URL")
(link . "NOTION_LINK")
(content . "NOTION_CONTENT")
(mention-type . "NOTION_MENTION")
(expression . "NOTION_EXPRESSION")
(href . "NOTION_HREF")
(annotations . "NOTION_ANNOTATIONS")
(color . "NOTION_COLOR")
(properties . "NOTION_PROPERTIES")
(children . "NOTION_CHILDREN")
(text . "NOTION_TEXT")
(type . "NOTION_TYPE"))
"Mapping of org-notion EIEIO field names to org-element
node-property or keyword names (:key).")
(defvar org-notion-field-abbrevs (mapcar #'car org-notion-field-org-keys)
"Org-notion field short names.")
(defvar org-notion-field-names (mapcar #'cdr org-notion-field-org-keys)
"Org-notion field full names as string.")
(defvar org-notion-class-keys
'((database . org-notion-database)
(user . org-notion-user)
(page . org-notion-page)
(rich-text . org-notion-rich-text)
(inline-text . org-notion-inline-text)
(inline-mention . org-notion-inline-mention)
(inline-equation . org-notion-inline-equation)
(block . org-notion-block))
"Mapping of short names such as \"database\" to
org-notion-class type names, i.e. org-notion-database.")
(defvar org-notion-class-abbrevs
(flatten-list (mapcar #'(lambda (i) (car i)) org-notion-class-keys))
"`org-notion-class' type abbreviations.")
(defvar org-notion-classes
(flatten-list (mapcar #'(lambda (i) (cdr i)) org-notion-class-keys))
"List of `org-notion-class' symbols.")
;;; Errors
;;
(define-error 'org-notion-error "Unknown org-notion error")
(define-error 'org-notion-invalid-key "Invalid key value" 'org-notion-error)
(define-error 'org-notion-invalid-uuid "Invalid UUID" 'org-notion-error)
(define-error 'org-notion-invalid-object "Invalid object" 'org-notion-error)
(define-error 'org-notion-invalid-method "Invalid API method" 'org-notion-error)
(define-error 'org-notion-invalid-element-type "Invalid Org element type" 'org-notion-error)
(define-error 'org-notion-bad-time "Bad time spec" 'org-notion-error)
(define-error 'org-notion-invalid-page-size
(format "PAGE_SIZE must be an integer less than or equal to %s"
org-notion-max-page-size)
'org-notion-error)
;; API Responses
(define-error 'org-notion-bad-request "HTTP 400 Bad Request" 'org-notion-error)
(define-error 'org-notion-unauthorized "HTTP 401 Unauthorized" 'org-notion-error)
(define-error 'org-notion-restricted-resource "HTTP 403 Restricted Resource" 'org-notion-error)
(define-error 'org-notion-not-found "HTTP 404 Object not found" 'org-notion-error)
(define-error 'org-notion-conflict "HTTP 409 Conflict error possibly due to data collision" 'org-notion-error)
(define-error 'org-notion-rate-limited "HTTP 429 Exceeded number of requests allowed" 'org-notion-error)
(define-error 'org-notion-unexpected "HTTP 500 Internal server error occurred" 'org-notion-error)
(define-error 'org-notion-unavailable "HTTP 503 Resource is unavailable" 'org-notion-error)
(defun org-notion--http-error (status)
"Return an `org-notion-error' type based on STATUS."
(pcase status
(400 'org-notion-bad-request)
(401 'org-notion-unauthorized)
(403 'org-notion-restricted-resource)
(404 'org-notion-not-found)
(409 'org-notion-conflict)
(429 'org-notion-rate-limited)
(500 'org-notion-unexpected)
(503 'org-notion-unavailable)
(_ 'org-notion-error)))
(defun org-notion--handle-http-error (json)
"Check Notion response in JSON for an error and handle it by
signaling `org-notion-error' types."
(when (equal (cdar json) "error")
(let ((err (org-notion--http-error (alist-get 'status json)))
(msg (alist-get 'message json)))
(signal err msg))))
;;; Utils
;;
;;;###autoload
(def-edebug-elem-spec 'org-notion-place '(form))
(defmacro org-notion-log (str &rest args)
"Log a message with format STR given ARGS"
`(message ,str ,@args))
(defun org-notion-dbg (&rest s)
"Print an object."
(when (or (eq org-notion-verbosity t)
(eq org-notion-verbosity 'debug))
(princ s)))
(defun oref-or (obj slot)
"Get the value of object or class."
(cond
((class-p obj) (eieio-oref-default obj slot))
((eieio-object-p obj) (eieio-oref obj slot))))
(defun oref-and (obj &rest slots)
"Return a list of values bound to SLOTS in OBJ. Uses `oref-or' internally."
(mapcar (lambda (x) (oref-or obj x)) slots))
(defun oset-or (obj slot value)
"Set the value of object or class."
(cond
((class-p obj) (eieio-oset-default obj slot value))
((eieio-object-p obj) (eieio-oset obj slot value))))
(defun oset-and (obj &rest args)
"Set each SLOT to VALUE in OBJ. Uses `oset-or' internally."
(if (/= (logand (length args) 1) 0)
(signal 'wrong-number-of-arguments (list 'oset-and (length args)))
(while args (oset-or obj (pop args) (pop args)))))
(defun org-notion-field-assoc (sym)
"Return the cdr of `org-notion-field-names' associated with car SYM
in `org-notion-field-org-keys'."
(when-let ((res (assoc sym org-notion-field-org-keys)))
(cdr res)))
(defun org-notion-field-rassoc (str)
"Return the member of `org-notion-field-abbrevs' associated with cdr
STR in `org-notion-field-org-keys'."
(when-let ((res (rassoc str org-notion-field-org-keys)))
(car res)))
(defun org-notion-class-assoc (sym)
"Return the member of `org-notion-classes' associated with car SYM
in `org-notion-class-keys'."
(when-let ((res (rassoc str org-notion-class-keys)))
(cdr res)))
(defun org-notion-class-rassoc (str)
"Return the member of `org-notion-class-abbrevs' associated with cdr
STR in `org-notion-class-keys'."
(when-let ((res (rassoc str org-notion-class-keys)))
(car res)))
(defun org-notion--kv (key val)
(list :key key :value val))
(defun org-notion--node-prop (key val)
"Create an org-element node-property given KEY and VAL"
`(node-property ,(org-notion--kv key val)))
(defun org-notion--kw (key val)
"Create an org-element keyword given KEY and VAL."
`(keyword ,(org-notion--kv key val)))
(defun org-notion--prop (key val &optional type)
"Create an org-element TYPE given KEY and VAL.
If KEY is a non-nil symbol it is looked up in
`org-notion-field-org-keys' via `org-notion-field-assoc' and
replaced with the associated string value."
(let ((key (pcase key
((and (pred symbolp) (pred (not null))) (org-notion-field-assoc key))
((pred stringp) key)
(_ (signal 'org-notion-invalid-key key)))))
(unless (null val) (pcase type
((or 'kw 'keyword) (org-notion--kw key val))
((or 'nil 'prop 'node-prop 'node-property)
(org-notion--node-prop key val))))))
(defun org-notion--property-drawer (alist)
"Given an ALIST of (KEY . VAL) pairs. create an org-element
property-drawer."
(let ((res 'property-drawer)
(props))
(dolist (kv alist props)
(when-let ((k (car kv)) (v (cdr kv)))
(push (org-notion--prop k v 'prop) props)))
(setq res (list res nil props))
res))
(defun org-notion-parse-parent (json)
"Get the parent type and id. Return a cons cell (TYPE . ID)."
(let* ((parent (alist-get 'parent json))
(type (alist-get 'type parent))
(id (alist-get (intern type) parent)))
(cons type id)))
(defun org-notion--get-results (json)
(when (equal (alist-get 'object json) "list")
(alist-get 'results json)))
(defun org-notion-filter-results (json-array obj-typ)
"Filter JSON-ARRAY (an array of results from the Notion API),
where :object = OBJ-TYP (a string)."
(seq-filter (lambda (a) (if (equal obj-typ (cdar a)) t nil)) json-array))
(defun org-notion--get-flag (sym json)
"Return the value of SYM in alist JSON. If value is :json-false, return nil."
(let ((val (alist-get sym json)))
(cond
((eq val :json-false) nil )
('_ val))))
(defsubst org-notion-string= (str1 str2)
"Return t if strings STR1 and STR2 are equal, ignoring case."
(and (stringp str1) (stringp str2)
(eq t (compare-strings str1 0 nil str2 0 nil t))))
;; id utils
(defun org-notion-uuid-p (str)
"Return t if STR is a uuid, else nil."
(and (stringp str)
(string-match-p org-notion-uuid-regexp str)))
(defun org-notion-valid-uuid (str)
"Validate uuid STR and return it."
(if (org-notion-uuid-p str)
str
nil))
(defsubst org-notion-id= (id1 id2)
"Return t if ids ID1 and ID2 are equal."
(and (org-notion-uuid-p id1) (org-notion-uuid-p id2)
(eq t (compare-strings id1 0 nil id2 0 nil))))
;; org utils
(if (fboundp 'org-link-set-parameters)
(org-link-set-parameters "notion"
:follow 'org-notion-browse
:complete (lambda (x)
(format "notion:%s" x))))
(defun org-notion-to-org-time (iso-time-str)
"Convert ISO-TIME-STR to format \"%Y-%m-%d %T\".
Example: \"2012-01-09T08:59:15.000Z\" becomes \"2012-01-09
03:59:15\", with the current timezone being -0500."
(condition-case _
(org-format-time-string
"%Y-%m-%d %T"
(apply
'encode-time
(iso8601-parse iso-time-str)))
(signal 'org-notion-bad-time iso-time-str)))
;; TODO 2022-01-07: account for timezone
(defun org-notion-from-org-time (org-time-str)
"Convert ORG-TIME-STR back to ISO-8601 time format."
(condition-case _
(format-time-string
"%FT%T%z"
(apply 'encode-time
(parse-time-string org-time-str))
t)
(signal 'org-notion-bad-time org-time-str)))
(defun org-notion-id-at-point (&optional pom)
"Get the org-notion-id at point. Checks
headline at POM first, then buffer keywords."
(let ((id (org-notion-field-assoc 'id)))
(org-with-point-at pom
(or (thing-at-point 'uuid t)
(cdr (assoc id (org-entry-properties)))
(cadr (assoc id (org-collect-keywords (list id))))))))
;;;; Callbacks
;;
(defmacro org-notion-with-callback (&rest body)
"Evaluate BODY as a callback for `org-notion-dispatch'. Errors are
automatically handled and then `org-notion-last-dispatch-result'
is set to capture the raw sexp value of json-data which can be
further processed by BODY before being returned by
`org-notion-dispatch'."
(declare (debug t)
(indent 0))
`(lambda (_response) ;; should probably use this
(with-current-buffer (current-buffer)
;; quick hack. url.el will always return body at this position.
(search-forward "\n\n")
(let ((json-data (json-read)))
(setq org-notion-last-dispatch-result json-data)
(org-notion--handle-http-error json-data)
,@body))))
(defun org-notion-callback-default ()
"Read json string from `org-notion-dispatch' status buffer and return output"
(org-notion-with-callback (org-notion-log "%s" json-data)))
;;;; Auth
;;
(defun org-notion-token (&optional token)
"Find the Notion API Integration Token.
If `org-notion-use-auth-source' is t check auth-source first. If
nil or TOKEN missing, prompt for token. You can generate a new
token at URL `https://www.notion.so/my-integrations'."
(interactive)
(if org-notion-use-auth-source
(let ((auth-source-creation-defaults '((user . "org-notion")
(port . "443")))
(found (nth 0 (auth-source-search
:host org-notion-host
:max 1
:require '(:secret)
:create t))))
(when found
(let ((sec (plist-get found :secret)))
(if (functionp sec)
(funcall sec)
sec))))
(or token
(read-passwd "Notion API Token: "))))
;;; OOP
;;
;; Default superclass. This is inherited by all other org-notion
;; classes and should only define new static methods. The only method
;; implemented is `org-notion-print' which simply prints the fields of
;; a class instance.
(defclass org-notion-class nil
nil
:documentation "Default superclass inherited by `org-notion' classes."
:abstract "Class org-notion-class is abstract.
use `org-notion-object' `org-notion-rich-text' or `org-notion-request' to create instances.")
(cl-defmethod org-notion-print ((obj org-notion-class))
"Pretty-print EIEIO class objects as string."
(let ((slots (mapcar (lambda (slot) (aref slot 1)) (eieio-class-slots (eieio-object-class obj)))))
(setq slots (cl-remove-if (lambda (s) (not (slot-boundp obj s))) slots))
(apply #'concat
(cons (format "\n|%s|\n" (eieio-object-class-name obj)) (mapcar (lambda (slot)
(let ((slot (intern (pp-to-string slot))))
(format "%+4s: %s\n" slot (slot-value obj (intern (pp-to-string slot))))))
slots)))))
;;;; Requests
;;
(defun org-notion-search-data (query &optional sort filter start_cursor page_size)
"Prepare data for Notion search request. Return a json object.
QUERY is a string (can be empty).
SORT is either \"ascending\" or \"descending\".
FILTER is either \"page\" or \"database\".
START_CURSOR is an ID and PAGE_SIZE is an integer."
(let (data)
(push `(query . ,query) data)
(when sort
(if (and (stringp sort)
(or (string= sort "ascending")
(string= sort "descending")))
(nconc data `((sort . ((direction . ,sort) (timestamp . "last_edited_time")))))
(error "SORT must be either 'ascending' or 'descending'")))
(when filter
(if (and (stringp filter)
(or (string= filter "page")
(string= filter "database")))
(nconc data `((filter . ((value . ,filter) (property . "object")))))
(error "FILTER must be either 'page' or 'database'")))
(when start_cursor
(if (org-notion-uuid-p start_cursor)
(nconc data `((start_cursor . ,start_cursor)))
(signal 'org-notion-invalid-uuid start_cursor)))
(when page_size
(if (and (integerp page_size)
(>= org-notion-max-page-size page_size))
(nconc data `((page_size . ,page_size)))
(signal 'org-notion-invalid-page-size page_size)))
data))
(defun org-notion-database-create-data (parent properties &optional title)
"Prepare data for Notion create-database request. Return a json object."
(let (data)
(push `(parent . ,parent) data)
(nconc data `((properties . ,properties)))
(when title
(if (stringp title)
(nconc data `((title . ,title)))
(error "TITLE must be a string.")))
data))
(defun org-notion-database-update-data (database_id &optional title properties)
"Prepare data for Notion update-database request. Return a json object."
(let (data)
(push `(database_id . ,database_id) data)
(when title
(if (stringp title)
(nconc data `((title . ,title)))
(error "TITLE must be a string.")))
(when properties)
data))
(defun org-notion-database-query-data (database_id &optional sorts filter start_cursor page_size)
"Prepare data for Notion query-database request. Return a json object."
(let (data)
(push `(database_id . ,database_id) data)
(when sorts)
(when filter)
(when start_cursor
(if (org-notion-uuid-p start_cursor)
(nconc data `((start_cursor . ,start_cursor)))
(signal 'org-notion-invalid-uuid start_cursor)))
(when page_size
(if (and (integerp page_size)
(>= org-notion-max-page-size page_size))
(nconc data `((page_size . ,page_size)))
(signal 'org-notion-invalid-page-size page_size
)))
data))
(defun org-notion-page-data (parent properties &optional children icon cover)
"Prepare data for Notion create-page request. Return a json object."
(let (data)
(push `(parent . ,parent) data)
(nconc data `((properties . ,properties)))
(when children)
(when icon)
(when cover)
data))
(defclass org-notion-request-data (org-notion-class)
((id
:initform nil
:type (or null string)
:initarg :id
:documentation "ID associated with this request, if any.")
(body
:initform nil
:type (or null list)
:initarg :body
:documentation "JSON body associated with this request, if any.")))
(defun org-notion-block-update-data (obj)
"Prepare data for Notion update-block request. Return a json object."
(if (org-notion-block-p obj)
(org-notion-request-data :id (org-notion-id obj) :body (org-notion-to-json obj))
(signal 'org-notion-invalid-object obj)))
;; Stand-alone class for making HTTP requests to the Notion API.
(defclass org-notion-request (org-notion-class)
((token
:initform #'org-notion-token
:initarg :token
:documentation "Bearer token used to authenticate requests.")
(version
:initform `,org-notion-version
:initarg :version
:documentation "Notion API Version.")
(endpoint
:initform `,org-notion-endpoint
:inittarg :endpoint
:documentation "Notion API endpoint.")
(method
:initform 'current-user
:initarg :method
:type symbol
:documentation "Notion call symbol. See
`org-notion-method-types' for possible values.")
(data
:initform nil
:initarg :data
:type (or null list string org-notion-request-data)
:documentation "Payload to be sent with HTTP request.")
(callback
:initform (org-notion-callback-default)
:initarg :callback
:documentation "Callback used to handle response from Notion
API call.")
(async
:initform nil
:initarg :async
:type boolean
:documentation "If t perform request asynchronously. Note that both values will
use `url-retrieve' internally which is async. The only difference
is that when async is t, `org-notion-dispatch' will wait for and
return `org-notion-last-dispatch-result'. When async is nil
`org-notion-dispatch' returns immediately and the
`org-notion-last-dispatch-result' value will be updated by the
`url-retrieve' call."))
:documentation "Notion API request.")
(cl-defmethod org-notion-dispatch ((obj org-notion-request))
"Dispatch HTTP request with slots from `org-notion-request' OBJ instance."
(setq org-notion-last-dispatch-result nil)
(with-slots (token version endpoint method data callback async) obj
(let ((url-request-extra-headers `(("Authorization" . ,(concat "Bearer " (funcall token)))
("Notion-Version" . ,version)
("Content-Type" . "application/json")))
(callback (or callback (org-notion-callback-default))))
(pcase method
('search (let ((url-request-method "POST")
(url (concat endpoint "search"))
(url-request-data (json-encode data)))
(url-retrieve url callback nil nil nil)))
('current-user
(let ((url-request-method "GET")
(url (concat endpoint "users/me")))
(url-retrieve url callback nil nil nil)))
('user
(let ((url-request-method "GET")
;; FIX 2022-01-20: this doesn't work
(url (concat endpoint "users/" (org-notion-valid-uuid data))))
(url-retrieve url callback nil nil nil)))
('users
(let ((url-request-method "GET")
(url (concat endpoint "users/")))
(url-retrieve url callback nil nil nil)))
('database
(let ((url-request-method "GET")
(url (concat endpoint "databases/" (org-notion-valid-uuid data))))
(url-retrieve url callback nil nil nil)))
;; filter: {}
;; sorts: <>
;; start_cursor: string
;; page_size: int
('query-database
(let ((url-request-method "POST")
(url (concat endpoint (format "databases/%s/query" data))))
(url-retrieve url callback nil nil nil)))
;; parent: {type:page_id page_id:id}
;; title: rich-text
;; properties: {}
('create-database
(let ((url-request-method "POST")
(url (concat endpoint "databases")))
(url-retrieve url callback nil nil nil)))
;; parent: {type:page_id page_id:id}
;; title: rich-text
;; properties: {}
('update-database
(let ((url-request-method "PATCH")
(url (concat endpoint "databases/%s" (org-notion-valid-uuid data))))
(url-retrieve url callback nil nil nil)))
('page
(let ((url-request-method "GET")
(url (concat endpoint (format "pages/%s" (org-notion-valid-uuid data)))))
(url-retrieve url callback nil nil nil)))
('page-property
;; (ID . PROP-ID)
(let ((url-request-method "GET")
(url (concat endpoint (format "pages/%s/properties/%s" (car data) (cdr data)))))
(url-retrieve url callback nil nil nil)))
;; parent: {type:(page_id/database_id) X_id:id}
;; properties: {}
;; children: <>
;; icon: {}
;; cover: {}
('create-page
(let ((url-request-method "POST")
(url (concat endpoint "pages")))
(url-retrieve url callback nil nil nil)))
;; properties: {}
;; archived: bool
;; icon: {}
;; cover: {}
('update-page
(let ((url-request-method "PATCH")
(url (concat endpoint (format "pages/%s" data))))
(url-retrieve url callback nil nil nil)))
('block
(let ((url-request-method "GET")
(url (concat endpoint (format "blocks/%s" (org-notion-valid-uuid data)))))
(url-retrieve url callback nil nil nil)))
('block-children
(let ((url-request-method "GET")
(url (concat endpoint (format "blocks/%s/children" data))))
(url-retrieve url callback nil nil nil)))
;; type: (text/checked)
;; archived: bool
('update-block
(let ((url-request-method "PATCH")
(url (concat endpoint "blocks/%s" (oref data :id)))
(url-request-data (oref data :body)))
(url-retrieve url callback nil nil nil)))
;; children: <blocks>
;; maximum depth of nesting for each append request is 2 (!!)
('append-block
(let ((url-request-method "PATCH")
(url (concat endpoint "blocks/%s/children" (oref data :id)))
(url-request-data (oref data :body)))
(url-retrieve url callback nil nil nil)))
('delete-block
(let ((url-request-method "DELETE")
(url (concat endpoint "blocks/%s" data)))
(url-retrieve url callback nil nil nil)))
(err (signal 'org-notion-invalid-method err)))
(unless async
(while (not org-notion-last-dispatch-result)
(sleep-for org-notion-dispatch-sync-sleep))
(when org-notion-last-dispatch-result
org-notion-last-dispatch-result)))))
;;;; Cache
;;
(defsubst org-notion-objects (&optional class)
"Return a list of all org-notion class instances. if CLASS is
given, only show instances of this class."
(if class
(seq-filter
(lambda (o)
(same-class-p o class))
(hash-table-values org-notion-hashtable))
(hash-table-values org-notion-hashtable)))
(defun org-notion-clear-cache ()
"Set all internal org-notion vars to nil."
(clrhash org-notion-hashtable))
(defun org-notion-hash-p (key obj pred)
"Throw `org-notion-hash-ok' non-nil if KEY matches OBJ according to PRED.
PRED may take the same values as the elements of `org-notion-completion-list'."
(if (and (memq 'id pred)
(org-notion-string= key (org-notion-id obj)))
(throw 'org-notion-hash-ok 'id))
(if (and (memq 'type pred)
(org-notion-string= key (org-notion-type obj)))
(throw 'org-notion-hash-ok 'type))
(if (and (memq 'parent pred)
(org-notion-string= key (org-notion-parent obj)))
(throw 'org-notion-hash-ok 'parent))
(if (and (memq 'email pred)
(org-notion-string= key (org-notion-email obj)))
(throw 'org-notion-hash-ok 'email)))
(defun org-notion-gethash (key &optional pred)
"Return objects associated with KEY in `org-notion-hashtable'.
KEY must be a string or nil. Empty strings and nil are
ignored. PREDICATE may take the same values as
`org-notion-completion-list'. If the symbol id is used, return
a single object, otherwise return a list.'"
(when (not (string-empty-p key))
(let ((all-objs (gethash key org-notion-hashtable))
objs)
(if (or (not pred) (eq t pred))
all-objs)
(if (eql pred 'id)
(car all-objs)
(dolist (o all-objs objs)
(if (catch 'org-notion-hash-ok
(org-notion-hash-p key o pred))
(push o objs)))))))
(defun org-notion-puthash (obj table)
"Add OBJ to `org-notion-hashtable'. The key is the id slot, and
value is OBJ. Empty or nil id slots are ignored."
(let ((key (org-notion-id obj)))
(if (and key (not (string-empty-p key)))
(let ((objs (gethash key table)))
(puthash key (if objs
(cl-pushnew obj objs)
(list obj))
table)))))
(defun org-notion-remhash (key obj)
"Remove OBJ from list of objects associated with KEY. KEY must be
a string or nil. Empty strings and nil are ignored."
(if (and key (not (string-empty-p key)))
(let* ((key (downcase key))
(objs (gethash key org-notion-hashtable)))
(when objs
(setq objs (delq obj objs))
(if objs
(puthash key objs org-notion-hashtable)
(remhash key org-notion-hashtable))))))
(defun org-notion-hash-update (obj old new)
"Update hash for OBJ. Remove OLD, insert NEW. both OLD and NEW
are lists of values."
(dolist (i old)
(org-notion-remhash i obj))
(dolist (i new)
(org-notion-puthash i obj)))
;; Cache class inherited by org-notion-object
(defclass org-notion-cache (org-notion-class)
((cache :type symbol
:allocation :class
:documentation "The symbol used to maintain a hashtable
of org-notion instances. The instance hashtable
is treated as a variable, with new instanaces
added to it."))
:documentation "Mixin used to cache object instances based on
`eieio-instance-tracker'. Inheritors must override
`cache' which is a variable used to cache instances."
:abstract t)
(cl-defmethod cache-instance ((this org-notion-cache) &rest _slots)
"Make sure OBJ is in our cache. Optional argument SLOTS are the
initialization arguments. This will not update a duplicate
hash. The old one is always kept.
This function is a no-op if `org-notion-cache-enable' is non-nil.
If `org-notion-cache-overwrite' is non-nil, insert value even if
duplicate is detected."
(when org-notion-cache-enable
(let ((table (symbol-value (oref this cache)))
(key (org-notion-id this)))
(if (gethash key table)
(if org-notion-cache-overwrite
(progn
(org-notion-log "duplicate key: %s" key)
(puthash key this table))
(org-notion-log "duplicate key: %s" key)
nil)
(puthash key this table)))))
(cl-defmethod delete-instance ((this org-notion-cache))
"Remove THIS from cache."
(let ((id (org-notion-id this)))
(remhash id (symbol-value (oref this cache)))
(org-notion-log (format "removed key: %s" id))))
(cl-defmethod update-instance ((this org-notion-cache))
"Update hash of THIS in cache."
(puthash (org-notion-id this) this (symbol-value (oref this cache))))
;;;; Object methods
;;
;; The following generic functions are implemented by
;; `org-notion-object' subclasses.
(cl-defgeneric org-notion-from-json (obj json)
"Interpret JSON as `org-notion-object'")
(cl-defgeneric org-notion-to-json (obj)
"Interpret `org-notion-object' OBJ as json object.")
(cl-defgeneric org-notion-from-org (obj str)
"Interrpret Org-mode STR as `org-notion-object'")
(cl-defgeneric org-notion-to-org (obj &optional type)
"Interpret `org-notion-object' OBJ as Org-mode syntax TYPE.")
;;;; Objects
;;
;; Parent class of Notion objects. The 'id' slot is inherited by
;; subclasses. 'cache' is a variable used to store instances.
(defclass org-notion-object (org-notion-class org-notion-cache)
((id
:initform nil
:initarg :id
:type (or null string)
:accessor org-notion-id
:documentation "UUID v4 associated with this object")
(cache :initform 'org-notion-hashtable))
:documentation "Top-level class for Notion API objects.")
;;;;; User
;;
(defclass org-notion-user (org-notion-object)
((type
:initform nil
:initarg :type
:type (or symbol null)
:accessor org-notion-type
:documentation "Type of the user. This slot should be either
'person' or 'bot'.")
(name
:initform nil
:initarg :name
:type (or string null)
:accessor org-notion-user-name
:documentation "User's name, as displayed in Notion.")
(avatar
:initform nil
:initarg :avatar
:type (or null string)
:documentation "Chosen avatar image.")
(email
:initform nil
:initarg :email
:type (or null string)
:accessor org-notion-email
:documentation "Email address of a user. Only present if
`:type' is 'person' and integration has user capabilities