├── .github
└── workflows
│ └── release.yml
├── .gitignore
├── LICENSE
├── README.md
├── manifest.json
├── package.json
├── rollup.config.js
├── screens
└── readwise_obsidian_export.gif
├── src
├── main.ts
└── status.ts
├── styles.css
├── tsconfig.json
└── versions.json
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release Obsidian plugin
2 |
3 | on:
4 | push:
5 | tags:
6 | - "*"
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v3
14 |
15 | - name: Use Node.js
16 | uses: actions/setup-node@v3
17 | with:
18 | node-version: "18.x"
19 |
20 | - name: Build plugin
21 | run: |
22 | npm install
23 | npm run build
24 |
25 | - name: Create release
26 | env:
27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
28 | run: |
29 | tag="${GITHUB_REF#refs/tags/}"
30 |
31 | gh release create "$tag" \
32 | --title="$tag" \
33 | --draft \
34 | main.js manifest.json styles.css
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Intellij
2 | *.iml
3 | .idea
4 |
5 | # npm
6 | node_modules
7 | package-lock.json
8 |
9 | # build
10 | main.js
11 | *.js.map
12 |
13 | data.json
14 | .env
15 | dist
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Readwise Official 📚
2 |
3 | 
4 |
5 | This official plugin maintained by the [Readwise](https://readwise.io) team enables you to easily and automatically export all your digital highlights to [Obsidian](https://obsidian.md) from a variety of sources such as Amazon Kindle, Apple Books, Google Play Books, Instapaper, Pocket, Medium, Twitter, PDFs, and more.
6 |
7 | 
8 |
9 | Note: This plugin requires a subscription with [Readwise](https://readwise.io) — a paid service that makes it easy to aggregate and review all your reading data into one place.
10 |
11 | ---
12 |
13 | ## Features
14 |
15 | * **Continuous, automatic syncing** — Take a highlight while reading in bed and wake up to the highlight in your Obsidian vault
16 | * **Powerful, flexible templating** — Customize the format of the export to your bespoke preferences using the Jinja2 templating language
17 | * **Enriched metadata** — Upgrade your highlight exports with extra data including the cover image, original URL, author name, chapter headings, tags (taken while you read), and more
18 | * **Premium support** — As a paid product, receive prompt replies to your questions and continuous upgrades to the plugin per your feedback
19 |
20 | ## Usage
21 |
22 | * Install the Readwise Official plugin within Obsidian
23 | * Enable the plugin
24 | * Connect the plugin to your Readwise account
25 | * Customize the export settings, if desired
26 | * Initiate the first sync
27 | * Thereafter, the plugin can be configured to sync automatically or manually
28 |
29 | ## Support
30 |
31 | * Please see our [Documentation](https://help.readwise.io/article/125-how-does-the-readwise-to-obsidian-export-integration-work) or email us at hello@readwise.io 🙂
32 |
33 | ## Community Resources
34 |
35 | * [Readwise Obsidian Plugin - Is It Any Good?](https://www.youtube.com/watch?v=g_5Pk7XwDFg) video by Santi Younger
36 | * [First Look at the Official Readwise Obsidian Plugin](https://medium.com/@benenewton/first-look-at-the-official-readwise-obsidian-plugin-5d553c0d0521) article by Ben Newton
37 | * [Getting Started with the Readwise Official Plugin](https://www.youtube.com/watch?v=Gr7kMb-Fwj8) video by Effective Remote Work
38 | * [Building a Second Brain with Readwise + Obsidian](https://www.youtube.com/watch?v=2lYwz-oK_YM) video by Systematic Mastery
39 | * [Making Unexpected Connections with Readwise and Obsidian](https://www.youtube.com/watch?v=tUfTaEhqZU8&t=27s) video by Curtis McHale
40 | * [How I View My Latest Readwise Highlights in My Obsidian Daily Note](https://benenewton.medium.com/how-i-view-my-latest-readwise-highlights-in-my-obsidian-daily-note-3d321dd6ed07) article by Ben Newton
41 | * [Color Code Your Readwise Highlights in Obsidian](https://github.com/chetachiezikeuzor/Obsidian-Snippets/blob/main/Pretty%20Highlights.css) with Chetachi's CSS snippets
42 | * [How to Import Your Shortform Highlights Into Obsidian Using Readwise](https://nicolevanderhoeven.com/blog/20210815-shortform-to-readwise/) article by Nicole van der Hoeven
43 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "readwise-official",
3 | "name": "Readwise Official",
4 | "version": "3.0.1",
5 | "minAppVersion": "1.0.0",
6 | "description": "Official Readwise <-> Obsidian integration",
7 | "author": "Readwise",
8 | "authorUrl": "https://readwise.io",
9 | "isDesktopOnly": false
10 | }
11 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "readwise-official",
3 | "version": "3.0.1",
4 | "description": "Automatically syncs your Readwise highlights with Obsidian.",
5 | "main": "main.js",
6 | "scripts": {
7 | "dev": "rollup --config rollup.config.js -w",
8 | "build": "rollup --config rollup.config.js --environment READWISE_SERVER_URL:https://readwise.io",
9 | "dist": "npm run build && mkdir -p dist && cp styles.css main.js manifest.json dist"
10 | },
11 | "keywords": [
12 | "obsidian",
13 | "readwise"
14 | ],
15 | "author": "Readwise",
16 | "license": "MIT",
17 | "dependencies": {
18 | "@zip.js/zip.js": "^2.2.33",
19 | "open": "^7.3.1"
20 | },
21 | "devDependencies": {
22 | "@rollup/plugin-commonjs": "^15.1.0",
23 | "@rollup/plugin-node-resolve": "^9.0.0",
24 | "@rollup/plugin-typescript": "^6.0.0",
25 | "@types/crypto-js": "^4.2.2",
26 | "@types/node": "^14.14.2",
27 | "dotenv": "^10.0.0",
28 | "obsidian": "https://github.com/obsidianmd/obsidian-api/tarball/master",
29 | "rollup": "^2.32.1",
30 | "rollup-plugin-dotenv": "^0.3.0",
31 | "ts-md5": "^1.3.1",
32 | "tslib": "^2.0.3",
33 | "typescript": "^4.0.3"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from '@rollup/plugin-typescript';
2 | import {nodeResolve} from '@rollup/plugin-node-resolve';
3 | import commonjs from '@rollup/plugin-commonjs';
4 | import dotenv from "rollup-plugin-dotenv";
5 |
6 | const banner =
7 | `/*
8 | THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
9 | if you want to view the source visit the plugins github repository
10 | */
11 | `;
12 |
13 | export default {
14 | input: 'src/main.ts',
15 | output: {
16 | dir: '.',
17 | format: 'cjs',
18 | exports: 'default',
19 | banner,
20 | },
21 | external: ['obsidian'],
22 | plugins: [
23 | dotenv(),
24 | typescript(),
25 | nodeResolve({browser: true}),
26 | commonjs(),
27 | ]
28 | };
29 |
--------------------------------------------------------------------------------
/screens/readwise_obsidian_export.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/readwiseio/obsidian-readwise/c292d0780d3f138ea0823d7b31016ae9596d7e7f/screens/readwise_obsidian_export.gif
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import {
2 | App,
3 | ButtonComponent,
4 | DataAdapter,
5 | Modal,
6 | normalizePath,
7 | Notice,
8 | Plugin,
9 | PluginSettingTab,
10 | Setting,
11 | Vault
12 | } from 'obsidian';
13 | import * as zip from "@zip.js/zip.js";
14 | import { Md5 } from "ts-md5";
15 | import { StatusBar } from "./status";
16 |
17 | // keep pluginVersion in sync with manifest.json
18 | const pluginVersion = "3.0.1";
19 |
20 | // switch to local dev server for development
21 | const baseURL = "https://readwise.io";
22 |
23 | interface ReadwiseAuthResponse {
24 | userAccessToken: string;
25 | }
26 |
27 | interface ExportRequestResponse {
28 | latest_id: number,
29 | status: string
30 | }
31 |
32 | interface ExportStatusResponse {
33 | totalBooks: number,
34 | booksExported: number,
35 | isFinished: boolean,
36 | taskStatus: string,
37 | artifactIds: number[],
38 | }
39 |
40 | interface ReadwisePluginSettings {
41 | token: string;
42 |
43 | /** Folder to save highlights */
44 | readwiseDir: string;
45 |
46 | /** Polling for pending export */
47 | isSyncing: boolean;
48 |
49 | /** Frequency of automatic sync */
50 | frequency: string;
51 |
52 | /** Automatically sync on load */
53 | triggerOnLoad: boolean;
54 |
55 | lastSyncFailed: boolean;
56 | lastSavedStatusID: number;
57 | currentSyncStatusID: number;
58 |
59 | /** Should get any deleted books */
60 | refreshBooks: boolean,
61 |
62 | /** Queue of books to refresh. */
63 | booksToRefresh: Array;
64 |
65 | /** Queue of books to retry because of previous failure */
66 | failedBooks: Array;
67 |
68 | /** Map of file path to book ID */
69 | booksIDsMap: { [filePath: string]: string; };
70 |
71 | /** User choice for confirming delete and reimport */
72 | reimportShowConfirmation: boolean;
73 | }
74 |
75 | // define our initial settings
76 | // quoted keys for easy copying to data.json during development
77 | const DEFAULT_SETTINGS: ReadwisePluginSettings = {
78 | "token": "",
79 | "readwiseDir": "Readwise",
80 | "frequency": "0",
81 | "triggerOnLoad": true,
82 | "isSyncing": false,
83 | "lastSyncFailed": false,
84 | "lastSavedStatusID": 0,
85 | "currentSyncStatusID": 0,
86 | "refreshBooks": false,
87 | "booksToRefresh": [],
88 | "failedBooks": [],
89 | "booksIDsMap": {},
90 | "reimportShowConfirmation": true
91 | };
92 |
93 | /** The name of the Readwise Sync history file, without the extension.
94 | * This is described as "Sync notification" in the Obsidian export settings
95 | * on the Readwise website. */
96 | const READWISE_SYNC_FILENAME = "Readwise Syncs" as const;
97 |
98 | export default class ReadwisePlugin extends Plugin {
99 | settings: ReadwisePluginSettings;
100 | fs: DataAdapter;
101 | vault: Vault;
102 | scheduleInterval: null | number = null;
103 | statusBar: StatusBar;
104 |
105 | getErrorMessageFromResponse(response: Response) {
106 | if (response && response.status === 409) {
107 | return "Sync in progress initiated by different client";
108 | }
109 | if (response && response.status === 417) {
110 | return "Obsidian export is locked. Wait for an hour.";
111 | }
112 | return `${response ? response.statusText : "Can't connect to server"}`;
113 | }
114 |
115 | async handleSyncError(buttonContext: ButtonComponent, msg: string) {
116 | await this.clearSettingsAfterRun();
117 | this.settings.lastSyncFailed = true;
118 | await this.saveSettings();
119 | if (buttonContext) {
120 | this.showInfoStatus(buttonContext.buttonEl.parentElement, msg, "rw-error");
121 | buttonContext.buttonEl.setText("Run sync");
122 | } else {
123 | this.notice(msg, true, 4, true);
124 | }
125 | }
126 |
127 | async clearSettingsAfterRun() {
128 | this.settings.isSyncing = false;
129 | this.settings.currentSyncStatusID = 0;
130 | await this.saveSettings();
131 | }
132 |
133 | async handleSyncSuccess(buttonContext: ButtonComponent, msg: string = "Synced", exportID: number = null) {
134 | await this.clearSettingsAfterRun();
135 | this.settings.lastSyncFailed = false;
136 | if (exportID) {
137 | this.settings.lastSavedStatusID = exportID;
138 | }
139 | await this.saveSettings();
140 | // if we have a button context, update the text on it
141 | // this is the case if we fired on a "Run sync" click (the button)
142 | if (buttonContext) {
143 | this.showInfoStatus(buttonContext.buttonEl.parentNode.parentElement, msg, "rw-success");
144 | buttonContext.buttonEl.setText("Run sync");
145 | }
146 | }
147 |
148 | /** Polls the Readwise API for the status of a given export;
149 | * uses recursion for polling so that it can be awaited. */
150 | async getExportStatus(statusID: number, buttonContext?: ButtonComponent, _processedArtifactIds?: Set) {
151 | if (statusID <= this.settings.lastSavedStatusID) {
152 | console.log(`Readwise Official plugin: Already saved data from export ${statusID}`);
153 | await this.handleSyncSuccess(buttonContext);
154 | this.notice("Readwise data is already up to date", false, 4);
155 | return;
156 | }
157 | const processedArtifactIds = _processedArtifactIds ?? new Set();
158 | const downloadUnprocessedArtifacts = async (allArtifactIds: number[]) => {
159 | for (const artifactId of allArtifactIds) {
160 | if (!processedArtifactIds.has(artifactId)) {
161 | await this.downloadArtifact(artifactId, buttonContext);
162 | processedArtifactIds.add(artifactId);
163 | }
164 | }
165 | };
166 | try {
167 | const response = await fetch(
168 | // status of archive build from this endpoint
169 | `${baseURL}/api/get_export_status?exportStatusId=${statusID}`,
170 | {
171 | headers: this.getAuthHeaders(),
172 | }
173 | );
174 |
175 | if (response && response.ok) {
176 | const data: ExportStatusResponse = await response.json();
177 |
178 | const WAITING_STATUSES = ['PENDING', 'RECEIVED', 'STARTED', 'RETRY'];
179 | const SUCCESS_STATUSES = ['SUCCESS'];
180 |
181 | if (WAITING_STATUSES.includes(data.taskStatus)) {
182 | if (data.booksExported) {
183 | const progressMsg = `Exporting Readwise data (${data.booksExported} / ${data.totalBooks}) ...`;
184 | this.notice(progressMsg, false, 35, true);
185 | } else {
186 | this.notice("Building export...");
187 | }
188 | // process any artifacts available while the export is still being generated
189 | await downloadUnprocessedArtifacts(data.artifactIds);
190 | // wait 1 second
191 | await new Promise(resolve => setTimeout(resolve, 1000));
192 | // then keep polling
193 | await this.getExportStatus(statusID, buttonContext, processedArtifactIds);
194 | } else if (SUCCESS_STATUSES.includes(data.taskStatus)) {
195 | // make sure all artifacts are processed
196 | await downloadUnprocessedArtifacts(data.artifactIds);
197 |
198 | await this.acknowledgeSyncCompleted(buttonContext);
199 | await this.handleSyncSuccess(buttonContext, "Synced!", statusID);
200 | this.notice("Readwise sync completed", true, 1, true);
201 | console.log("Readwise Official plugin: completed sync");
202 | // @ts-ignore
203 | if (this.app.isMobile) {
204 | this.notice("If you don't see all of your Readwise files, please reload the Obsidian app", true,);
205 |
206 | }
207 | } else {
208 | console.log("Readwise Official plugin: unknown status in getExportStatus: ", data);
209 | await this.handleSyncError(buttonContext, "Sync failed");
210 | return;
211 | }
212 | } else {
213 | console.log("Readwise Official plugin: bad response in getExportStatus: ", response);
214 | await this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response));
215 | }
216 | } catch (e) {
217 | console.log("Readwise Official plugin: fetch failed in getExportStatus: ", e);
218 | await this.handleSyncError(buttonContext, "Sync failed");
219 | }
220 | }
221 |
222 | /** Requests the archive from Readwise, polling until it's ready */
223 | async queueExport(buttonContext?: ButtonComponent, statusId?: number, auto?: boolean) {
224 | if (this.settings.isSyncing) {
225 | this.notice("Readwise sync already in progress", true);
226 | return;
227 | }
228 |
229 | console.log('Readwise Official plugin: requesting archive...');
230 | this.settings.isSyncing = true;
231 | await this.saveSettings();
232 |
233 | const parentDeleted = !await this.app.vault.adapter.exists(this.settings.readwiseDir);
234 |
235 | // kickoff archive build form this endpoint
236 | let url = `${baseURL}/api/obsidian/init?parentPageDeleted=${parentDeleted}`;
237 | if (statusId) {
238 | url += `&statusID=${statusId}`;
239 | }
240 | if (auto) {
241 | url += `&auto=${auto}`;
242 | }
243 | let response, data: ExportRequestResponse;
244 | try {
245 | response = await fetch(
246 | url,
247 | {
248 | headers: this.getAuthHeaders()
249 | }
250 | );
251 | } catch (e) {
252 | console.log("Readwise Official plugin: fetch failed in queueExport: ", e);
253 | }
254 |
255 | if (response && response.ok) {
256 | data = await response.json();
257 |
258 | if (data.latest_id <= this.settings.lastSavedStatusID) {
259 | await this.handleSyncSuccess(buttonContext);
260 | this.notice("Readwise data is already up to date", false, 4, true);
261 | return;
262 | }
263 |
264 | // save the sync status ID so it can be polled until the archive is ready
265 | this.settings.currentSyncStatusID = data.latest_id;
266 | await this.saveSettings();
267 | console.log("Readwise Official plugin: saved currentSyncStatusID", this.settings.currentSyncStatusID);
268 |
269 | if (response.status === 201) {
270 | this.notice("Syncing Readwise data");
271 | await this.getExportStatus(this.settings.currentSyncStatusID, buttonContext);
272 | console.log('Readwise Official plugin: queueExport done');
273 | } else {
274 | await this.handleSyncSuccess(buttonContext, "Synced", data.latest_id);
275 | this.notice("Latest Readwise sync already happened on your other device. Data should be up to date", false, 4, true);
276 | }
277 | } else {
278 | console.log("Readwise Official plugin: bad response in queueExport: ", response);
279 | await this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response));
280 | return;
281 | }
282 | }
283 |
284 | notice(msg: string, show = false, timeout = 0, forcing: boolean = false) {
285 | if (show) {
286 | new Notice(msg);
287 | }
288 | // @ts-ignore
289 | if (!this.app.isMobile) {
290 | this.statusBar.displayMessage(msg.toLowerCase(), timeout, forcing);
291 | } else {
292 | if (!show) {
293 | new Notice(msg);
294 | }
295 | }
296 | }
297 |
298 | showInfoStatus(container: HTMLElement, msg: string, className = "") {
299 | let info = container.find('.rw-info-container');
300 | info.setText(msg);
301 | info.addClass(className);
302 | }
303 |
304 | clearInfoStatus(container: HTMLElement) {
305 | let info = container.find('.rw-info-container');
306 | info.empty();
307 | }
308 |
309 | getAuthHeaders() {
310 | return {
311 | 'AUTHORIZATION': `Token ${this.settings.token}`,
312 | 'Obsidian-Client': `${this.getObsidianClientID()}`,
313 | 'Readwise-Client-Version': pluginVersion,
314 | };
315 | }
316 |
317 | async downloadArtifact(artifactId: number, buttonContext: ButtonComponent): Promise {
318 | // download archive from this endpoint
319 | let artifactURL = `${baseURL}/api/v2/download_artifact/${artifactId}`;
320 |
321 | let response, blob;
322 | try {
323 | response = await fetch(
324 | artifactURL, { headers: this.getAuthHeaders() }
325 | );
326 | } catch (e) {
327 | console.log("Readwise Official plugin: fetch failed in downloadExport: ", e);
328 | }
329 | if (response && response.ok) {
330 | blob = await response.blob();
331 | } else {
332 | console.log("Readwise Official plugin: bad response in downloadExport: ", response);
333 | await this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response));
334 | throw new Error(`Readwise: error while fetching artifact ${artifactId}`);
335 | }
336 |
337 | this.fs = this.app.vault.adapter;
338 |
339 | const blobReader = new zip.BlobReader(blob);
340 | const zipReader = new zip.ZipReader(blobReader);
341 | const entries = await zipReader.getEntries();
342 | if (entries.length) {
343 | for (const entry of entries) {
344 | // will be extracted from JSON data
345 | let bookID: string;
346 | let data: Record;
347 |
348 | /** Combo of file `readwiseDir` and book name.
349 | * Example: `Readwise/Books/Name of Book.json` */
350 | const processedFileName = normalizePath(
351 | entry.filename
352 | .replace(/^Readwise/, this.settings.readwiseDir)
353 | .replace(/\.json$/, ".md")
354 | );
355 | const isReadwiseSyncFile = processedFileName === `${this.settings.readwiseDir}/${READWISE_SYNC_FILENAME}.md`;
356 |
357 | try {
358 | const fileContent = await entry.getData(new zip.TextWriter());
359 | if (isReadwiseSyncFile) {
360 | data = {
361 | append_only_content: fileContent,
362 | };
363 | } else {
364 | data = JSON.parse(fileContent);
365 | }
366 |
367 | bookID = this.encodeReadwiseBookId(data.book_id) || this.encodeReaderDocumentId(data.reader_document_id);
368 |
369 | const undefinedBook = !bookID || !processedFileName;
370 | if (undefinedBook && !isReadwiseSyncFile) {
371 | console.error(`Error while processing entry: ${entry.filename}`);
372 | }
373 |
374 | // write the full document text file
375 | if (data.full_document_text && data.full_document_text_path) {
376 | const processedFullDocumentTextFileName = data.full_document_text_path.replace(/^Readwise/, this.settings.readwiseDir);
377 | console.log("Writing full document text", processedFullDocumentTextFileName);
378 | // track the book
379 | this.settings.booksIDsMap[processedFullDocumentTextFileName] = bookID;
380 | // ensure the directory exists
381 | await this.createDirForFile(processedFullDocumentTextFileName);
382 | if (!await this.fs.exists(processedFullDocumentTextFileName)) {
383 | // it's a new full document content file, just save it
384 | await this.fs.write(processedFullDocumentTextFileName, data.full_document_text);
385 | } else {
386 | // full document content file already exists — overwrite it if it wasn't edited locally
387 | const existingFullDocument = await this.fs.read(processedFullDocumentTextFileName);
388 | const existingFullDocumentHash = Md5.hashStr(existingFullDocument).toString();
389 | if (existingFullDocumentHash === data.last_full_document_hash) {
390 | await this.fs.write(processedFullDocumentTextFileName, data.full_document_text);
391 | }
392 | }
393 | }
394 |
395 | // write the actual files
396 | let contentToSave = data.full_content ?? data.append_only_content;
397 | if (contentToSave) {
398 | // track the book
399 | this.settings.booksIDsMap[processedFileName] = bookID;
400 | // ensure the directory exists
401 | await this.createDirForFile(processedFileName);
402 | if (await this.fs.exists(processedFileName)) {
403 | // if the file already exists we need to append content to existing one
404 | const existingContent = await this.fs.read(processedFileName);
405 | const existingContentHash = Md5.hashStr(existingContent).toString();
406 | if (existingContentHash !== data.last_content_hash) {
407 | // content has been modified (it differs from the previously exported full document)
408 | contentToSave = existingContent.trimEnd() + "\n" + data.append_only_content;
409 | }
410 | }
411 | await this.fs.write(processedFileName, contentToSave);
412 | }
413 |
414 | // save the entry in settings to ensure that it can be
415 | // retried later when deleted files are re-synced if
416 | // the user has `settings.refreshBooks` enabled
417 | if (bookID) await this.saveSettings();
418 | } catch (e) {
419 | console.log(`Readwise Official plugin: error writing ${processedFileName}:`, e);
420 | this.notice(`Readwise: error while writing ${processedFileName}: ${e}`, true, 4, true);
421 | if (bookID) {
422 | // handles case where user doesn't have `settings.refreshBooks` enabled
423 | await this.addToFailedBooks(bookID);
424 | await this.saveSettings();
425 | }
426 | // communicate with readwise?
427 | throw new Error(`Readwise: error while processing artifact ${artifactId}`);
428 | }
429 |
430 | if (data) {
431 | await this.removeBooksFromRefresh([this.encodeReadwiseBookId(data.book_id), this.encodeReaderDocumentId(data.reader_document_id)]);
432 | await this.removeBookFromFailedBooks([this.encodeReadwiseBookId(data.book_id), this.encodeReaderDocumentId(data.reader_document_id)]);
433 | }
434 | }
435 | await this.saveSettings();
436 | }
437 | // close the ZipReader
438 | await zipReader.close();
439 |
440 | // wait for the metadata cache to process created/updated documents
441 | await new Promise((resolve) => {
442 | const timeoutSeconds = 15;
443 | console.log(`Readwise Official plugin: waiting for metadata cache processing for up to ${timeoutSeconds}s...`)
444 | const timeout = setTimeout(() => {
445 | this.app.metadataCache.offref(eventRef);
446 | console.log("Readwise Official plugin: metadata cache processing timeout reached.");
447 | resolve();
448 | }, timeoutSeconds * 1000);
449 |
450 | const eventRef = this.app.metadataCache.on("resolved", () => {
451 | this.app.metadataCache.offref(eventRef);
452 | clearTimeout(timeout);
453 | console.log("Readwise Official plugin: metadata cache processing has finished.");
454 | resolve();
455 | });
456 | });
457 | }
458 |
459 | async acknowledgeSyncCompleted(buttonContext: ButtonComponent) {
460 | let response;
461 | try {
462 | response = await fetch(
463 | `${baseURL}/api/obsidian/sync_ack`,
464 | {
465 | headers: { ...this.getAuthHeaders(), 'Content-Type': 'application/json' },
466 | method: "POST",
467 | });
468 | } catch (e) {
469 | console.log("Readwise Official plugin: fetch failed to acknowledged sync: ", e);
470 | }
471 | if (response && response.ok) {
472 | return;
473 | } else {
474 | console.log("Readwise Official plugin: bad response in acknowledge sync: ", response);
475 | await this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response));
476 | return;
477 | }
478 | }
479 |
480 | async configureSchedule() {
481 | const minutes = parseInt(this.settings.frequency);
482 | let milliseconds = minutes * 60 * 1000; // minutes * seconds * milliseconds
483 | console.log('Readwise Official plugin: setting interval to ', milliseconds, 'milliseconds');
484 | window.clearInterval(this.scheduleInterval);
485 | this.scheduleInterval = null;
486 | if (!milliseconds) {
487 | // user set frequency to manual
488 | return;
489 | }
490 | this.scheduleInterval = window.setInterval(() => this.syncBookHighlights(undefined, true), milliseconds);
491 | this.registerInterval(this.scheduleInterval);
492 | }
493 |
494 | /** Syncs provided book IDs, or uses the booksToRefresh list if none provided.
495 | * ALL syncing starts with this function. */
496 | async syncBookHighlights(
497 | /** optional list of specific book IDs to sync */
498 | bookIds?: Array,
499 |
500 | /** if true, was not initiated by user */
501 | auto?: boolean,
502 | ) {
503 | if (!this.settings.token) return;
504 |
505 | let targetBookIds = [
506 | // try to sync provided bookIds
507 | ...(bookIds || []),
508 |
509 | // always try to sync failedBooks
510 | ...this.settings.failedBooks,
511 | ];
512 |
513 | // only sync `booksToRefresh` items if "resync deleted files" enabled
514 | if (this.settings.refreshBooks) {
515 | targetBookIds = [
516 | ...targetBookIds,
517 | ...this.settings.booksToRefresh,
518 | ];
519 | }
520 |
521 | if (!targetBookIds.length) {
522 | console.log('Readwise Official plugin: no targetBookIds, checking for new highlights');
523 | // no need to hit refresh_book_export;
524 | // just check if there's new highlights from the server
525 | await this.queueExport();
526 | return;
527 | }
528 |
529 | console.log('Readwise Official plugin: refreshing books', { targetBookIds });
530 |
531 | let requestBookIds: string[] = [];
532 | let requestReaderDocumentIds: string[] = [];
533 | targetBookIds.map(id => {
534 | const readerDocumentId = this.decodeReaderDocumentId(id);
535 | if (readerDocumentId) {
536 | requestReaderDocumentIds.push(readerDocumentId);
537 | } else {
538 | requestBookIds.push(id);
539 | }
540 | });
541 |
542 | try {
543 | const response = await fetch(
544 | // add books to next archive build from this endpoint
545 | // NOTE: should only end up calling this endpoint when:
546 | // 1. there are failedBooks
547 | // 2. there are booksToRefresh
548 | `${baseURL}/api/refresh_book_export`,
549 | {
550 | headers: { ...this.getAuthHeaders(), 'Content-Type': 'application/json' },
551 | method: "POST",
552 | body: JSON.stringify({
553 | exportTarget: 'obsidian',
554 | userBookIds: requestBookIds,
555 | readerDocumentIds: requestReaderDocumentIds,
556 | })
557 | }
558 | );
559 |
560 | if (response && response.ok) {
561 | await this.queueExport();
562 | return;
563 | } else {
564 | console.log(`Readwise Official plugin: saving book id ${bookIds} to refresh later`);
565 | const deduplicatedBookIds = new Set([...this.settings.booksToRefresh, ...bookIds]);
566 | this.settings.booksToRefresh = Array.from(deduplicatedBookIds);
567 | await this.saveSettings();
568 | return;
569 | }
570 | } catch (e) {
571 | console.log("Readwise Official plugin: fetch failed in syncBookHighlights: ", e);
572 | }
573 | }
574 |
575 | async addToFailedBooks(bookId: string) {
576 | // NOTE: settings.failedBooks was added after initial settings schema,
577 | // so not all users may have it, hence the fallback to DEFAULT_SETTINGS.failedBooks
578 | let failedBooks = [...(this.settings.failedBooks || DEFAULT_SETTINGS.failedBooks)];
579 | failedBooks.push(bookId);
580 | console.log(`Readwise Official plugin: added book id ${bookId} to failed books`);
581 | this.settings.failedBooks = failedBooks;
582 |
583 | // don't forget to save after!
584 | // but don't do that here; this allows batching when removing multiple books.
585 | }
586 |
587 | async addBookToRefresh(bookId: string) {
588 | let booksToRefresh = [...this.settings.booksToRefresh];
589 | booksToRefresh.push(bookId);
590 | console.log(`Readwise Official plugin: added book id ${bookId} to refresh list`);
591 | this.settings.booksToRefresh = booksToRefresh;
592 | await this.saveSettings();
593 | }
594 |
595 | async removeBooksFromRefresh(bookIds: Array = []) {
596 | if (!bookIds.length) return;
597 |
598 | console.log(`Readwise Official plugin: removing book ids ${bookIds.join(', ')} from refresh list`);
599 | this.settings.booksToRefresh = this.settings.booksToRefresh.filter(n => !bookIds.includes(n));
600 |
601 | // don't forget to save after!
602 | // but don't do that here; this allows batching when removing multiple books.
603 | }
604 |
605 | async removeBookFromFailedBooks(bookIds: Array = []) {
606 | if (!bookIds.length) return;
607 |
608 | console.log(`Readwise Official plugin: removing book ids ${bookIds.join(', ')} from failed list`);
609 | this.settings.failedBooks = this.settings.failedBooks.filter(n => !bookIds.includes(n));
610 |
611 | // don't forget to save after!
612 | // but don't do that here; this allows batching when removing multiple books.
613 | }
614 |
615 | async reimportFile(vault: Vault, fileName: string) {
616 | try {
617 | this.notice("Deleting and reimporting file...", true);
618 | await vault.delete(vault.getAbstractFileByPath(fileName));
619 | const bookId = this.settings.booksIDsMap[fileName];
620 | await this.addBookToRefresh(bookId);
621 |
622 | // specifically re-sync this one file (not this.settings.booksToRefresh)
623 | // because the user may have `settings.refreshBooks` disabled
624 | await this.syncBookHighlights([bookId]);
625 | } catch (e) {
626 | console.log("Readwise Official plugin: fetch failed in Reimport current file: ", e);
627 | }
628 | }
629 |
630 | async createDirForFile(filePath: string) {
631 | const dirPath = filePath.replace(/\/*$/, '').replace(/^(.+)\/[^\/]*?$/, '$1');
632 | const exists = await this.fs.exists(dirPath);
633 | if (!exists) {
634 | await this.fs.mkdir(dirPath);
635 | }
636 | }
637 |
638 | async onload() {
639 | await this.loadSettings();
640 |
641 | // @ts-expect-error - no type for isMobile
642 | if (!this.app.isMobile) {
643 | this.statusBar = new StatusBar(this.addStatusBarItem());
644 | this.registerInterval(
645 | window.setInterval(() => this.statusBar.display(), 1000)
646 | );
647 | }
648 |
649 | this.app.vault.on("rename", async (file, oldPath) => {
650 | const bookId = this.settings.booksIDsMap[oldPath];
651 | if (!bookId) {
652 | return;
653 | }
654 | delete this.settings.booksIDsMap[oldPath];
655 | this.settings.booksIDsMap[file.path] = bookId;
656 | await this.saveSettings();
657 | });
658 | this.addCommand({
659 | id: 'readwise-official-sync',
660 | name: 'Sync your data now',
661 | callback: () => {
662 | this.syncBookHighlights();
663 | }
664 | });
665 | this.addCommand({
666 | id: 'readwise-official-format',
667 | name: 'Customize formatting',
668 | callback: () => window.open(`${baseURL}/export/obsidian/preferences`)
669 | });
670 | this.addCommand({
671 | id: 'readwise-official-reimport-file',
672 | name: 'Delete and reimport this document',
673 | checkCallback: (checking: boolean) => {
674 | const activeFilePath = this.app.workspace.getActiveFile()?.path;
675 | const isRWfile = activeFilePath && activeFilePath in this.settings.booksIDsMap;
676 | if (checking) {
677 | return isRWfile;
678 | }
679 | if (this.settings.reimportShowConfirmation) {
680 | const modal = new Modal(this.app);
681 | modal.titleEl.setText("Delete and reimport this document?");
682 | modal.contentEl.createEl(
683 | 'p',
684 | {
685 | text: 'Warning: Proceeding will delete this file entirely (including any changes you made) ' +
686 | 'and then reimport a new copy of your highlights from Readwise.',
687 | cls: 'rw-modal-warning-text',
688 | });
689 | const buttonsContainer = modal.contentEl.createEl('div', { "cls": "rw-modal-btns" });
690 | const cancelBtn = buttonsContainer.createEl("button", { "text": "Cancel" });
691 | const confirmBtn = buttonsContainer.createEl("button", { "text": "Proceed", 'cls': 'mod-warning' });
692 | const showConfContainer = modal.contentEl.createEl('div', { 'cls': 'rw-modal-confirmation' });
693 | showConfContainer.createEl("label", { "attr": { "for": "rw-ask-nl" }, "text": "Don't ask me in the future" });
694 | const showConf = showConfContainer.createEl("input", { "type": "checkbox", "attr": { "name": "rw-ask-nl", "id": "rw-ask-nl" } });
695 | showConf.addEventListener('change', async (ev) => {
696 | // @ts-expect-error - target.checked is not typed (TODO add type narrowing)
697 | this.settings.reimportShowConfirmation = !ev.target.checked;
698 | await this.saveSettings();
699 | });
700 | cancelBtn.onClickEvent(() => {
701 | modal.close();
702 | });
703 | confirmBtn.onClickEvent(() => {
704 | this.reimportFile(this.app.vault, activeFilePath);
705 | modal.close();
706 | });
707 | modal.open();
708 | } else {
709 | this.reimportFile(this.app.vault, activeFilePath);
710 | }
711 | }
712 | });
713 | this.registerMarkdownPostProcessor((el, ctx) => {
714 | if (!ctx.sourcePath.startsWith(this.settings.readwiseDir)) {
715 | return;
716 | }
717 | let matches: string[];
718 | try {
719 | // @ts-ignore
720 | matches = [...ctx.getSectionInfo(el).text.matchAll(/__(.+)__/g)].map((a) => a[1]);
721 | } catch (TypeError) {
722 | // failed interaction with a Dataview element
723 | return;
724 | }
725 | const hypers = el.findAll("strong").filter(e => matches.contains(e.textContent));
726 | hypers.forEach(strongEl => {
727 | const replacement = el.createEl('span');
728 | while (strongEl.firstChild) {
729 | replacement.appendChild(strongEl.firstChild);
730 | }
731 | replacement.addClass("rw-hyper-highlight");
732 | strongEl.replaceWith(replacement);
733 | });
734 | });
735 |
736 | this.addSettingTab(new ReadwiseSettingTab(this.app, this));
737 |
738 | // ensure workspace is settled; this ensures cache is loaded
739 | this.app.workspace.onLayoutReady(async () => {
740 | if (this.settings.isSyncing && this.settings.currentSyncStatusID) {
741 | await this.getExportStatus(this.settings.currentSyncStatusID);
742 | } else {
743 | // we probably got some unhandled error...
744 | this.settings.isSyncing = false;
745 | await this.saveSettings();
746 | }
747 |
748 | if (this.settings.triggerOnLoad) {
749 | await this.syncBookHighlights(undefined, true);
750 | }
751 |
752 | await this.configureSchedule();
753 |
754 | this.app.vault.on("delete", async (file) => {
755 | const bookId = this.settings.booksIDsMap[file.path];
756 |
757 | if (bookId) {
758 | // NOTE: because `on(delete)` also adds to `booksToRefresh`,
759 | // the ID will be duplicated in `booksToRefresh`.
760 | await this.addBookToRefresh(bookId);
761 | }
762 |
763 | delete this.settings.booksIDsMap[file.path];
764 |
765 | // BUG: `on("delete")` events have no sequantial guarantees.
766 | // meaning: if a user deletes many files at once,
767 | // there is no guarantee that the event will be handled
768 | // in any specific order. this can lead to reality
769 | // drifting as book ID is deleted/saved as all the delete
770 | // events compete to remove the book ID from the map and save.
771 | await this.saveSettings();
772 | });
773 | });
774 | }
775 |
776 | onunload() {
777 | // we're not doing anything here for now...
778 | return;
779 | }
780 |
781 | async loadSettings() {
782 | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
783 | }
784 |
785 | async saveSettings() {
786 | await this.saveData(this.settings);
787 | }
788 |
789 | getObsidianClientID() {
790 | let obsidianClientId = window.localStorage.getItem('rw-ObsidianClientId');
791 | if (obsidianClientId) {
792 | return obsidianClientId;
793 | } else {
794 | obsidianClientId = Math.random().toString(36).substring(2, 15);
795 | window.localStorage.setItem('rw-ObsidianClientId', obsidianClientId);
796 | return obsidianClientId;
797 | }
798 | }
799 |
800 | async getUserAuthToken(button: HTMLElement, attempt = 0) {
801 | let uuid = this.getObsidianClientID();
802 |
803 | if (attempt === 0) {
804 | window.open(`${baseURL}/api_auth?token=${uuid}&service=obsidian`);
805 | }
806 |
807 | let response, data: ReadwiseAuthResponse;
808 | try {
809 | response = await fetch(
810 | `${baseURL}/api/auth?token=${uuid}`
811 | );
812 | } catch (e) {
813 | console.log("Readwise Official plugin: fetch failed in getUserAuthToken: ", e);
814 | }
815 | if (response && response.ok) {
816 | data = await response.json();
817 | } else {
818 | console.log("Readwise Official plugin: bad response in getUserAuthToken: ", response);
819 | this.showInfoStatus(button.parentElement, "Authorization failed. Try again", "rw-error");
820 | return;
821 | }
822 | if (data.userAccessToken) {
823 | console.log("Readwise Official plugin: successfully authenticated with Readwise");
824 | this.settings.token = data.userAccessToken;
825 | await this.saveSettings();
826 | } else {
827 | if (attempt > 20) {
828 | console.log('Readwise Official plugin: reached attempt limit in getUserAuthToken');
829 | return;
830 | }
831 | console.log(`Readwise Official plugin: didn't get token data, retrying (attempt ${attempt + 1})`);
832 | await new Promise(resolve => setTimeout(resolve, 1000));
833 | await this.getUserAuthToken(button, attempt + 1);
834 | }
835 | await this.saveSettings();
836 | return true;
837 | }
838 |
839 | encodeReadwiseBookId(rawBookId?: string): string | undefined {
840 | if (rawBookId) {
841 | return rawBookId.toString()
842 | }
843 | return undefined;
844 | }
845 |
846 | encodeReaderDocumentId(rawReaderDocumentId?: string) : string | undefined {
847 | if (rawReaderDocumentId) {
848 | return `readerdocument:${rawReaderDocumentId}`;
849 | }
850 | return undefined;
851 | }
852 |
853 | decodeReaderDocumentId(readerDocumentId?: string) : string | undefined {
854 | if (!readerDocumentId || !readerDocumentId.startsWith("readerdocument:")) {
855 | return undefined;
856 | }
857 | return readerDocumentId.replace(/^readerdocument:/, "");
858 | }
859 | }
860 |
861 | class ReadwiseSettingTab extends PluginSettingTab {
862 | plugin: ReadwisePlugin;
863 |
864 | constructor(app: App, plugin: ReadwisePlugin) {
865 | super(app, plugin);
866 | this.plugin = plugin;
867 | }
868 |
869 |
870 | display(): void {
871 | let { containerEl } = this;
872 |
873 | containerEl.empty();
874 | containerEl.createEl('h1', { text: 'Readwise Official' });
875 | containerEl.createEl('p', { text: 'Created by ' }).createEl('a', { text: 'Readwise', href: 'https://readwise.io' });
876 | containerEl.getElementsByTagName('p')[0].appendText(' 📚');
877 | containerEl.createEl('h2', { text: 'Settings' });
878 |
879 | if (this.plugin.settings.token) {
880 | new Setting(containerEl)
881 | .setName("Sync your Readwise data with Obsidian")
882 | .setDesc("On first sync, the Readwise plugin will create a new folder containing all your highlights")
883 | .setClass('rw-setting-sync')
884 | .addButton((button) => {
885 | button.setCta().setTooltip("Once the sync begins, you can close this plugin page")
886 | .setButtonText('Initiate Sync')
887 | .onClick(async () => {
888 | if (this.plugin.settings.isSyncing) {
889 | // NOTE: This is used to prevent multiple syncs at the same time. However, if a previous sync fails,
890 | // it can stop new syncs from happening. Make sure to set isSyncing to false
891 | // if there's ever errors/failures in previous sync attempts, so that
892 | // we don't block syncing subsequent times.
893 | new Notice("Readwise sync already in progress");
894 | } else {
895 | this.plugin.clearInfoStatus(containerEl);
896 | await this.plugin.syncBookHighlights();
897 | }
898 | });
899 | });
900 | let el = containerEl.createEl("div", { cls: "rw-info-container" });
901 | containerEl.find(".rw-setting-sync > .setting-item-control ").prepend(el);
902 |
903 | new Setting(containerEl)
904 | .setName("Customize formatting options")
905 | .setDesc("You can customize which items export to Obsidian and how they appear from the Readwise website")
906 | .addButton((button) => {
907 | button.setButtonText("Customize").onClick(() => {
908 | window.open(`${baseURL}/export/obsidian/preferences`);
909 | });
910 | });
911 |
912 | new Setting(containerEl)
913 | .setName('Customize base folder')
914 | .setDesc("By default, the plugin will save all your highlights into a folder named Readwise")
915 | // TODO: change this to search filed when the API is exposed (https://github.com/obsidianmd/obsidian-api/issues/22)
916 | .addText(text => text
917 | .setPlaceholder('Defaults to: Readwise')
918 | .setValue(this.plugin.settings.readwiseDir)
919 | .onChange(async (value) => {
920 | this.plugin.settings.readwiseDir = normalizePath(value || "Readwise");
921 | await this.plugin.saveSettings();
922 | }));
923 |
924 | new Setting(containerEl)
925 | .setName('Configure resync frequency')
926 | .setDesc("If not set to Manual, Readwise will automatically resync with Obsidian when the app is open at the specified interval")
927 | .addDropdown(dropdown => {
928 | dropdown.addOption("0", "Manual");
929 | dropdown.addOption("60", "Every 1 hour");
930 | dropdown.addOption((12 * 60).toString(), "Every 12 hours");
931 | dropdown.addOption((24 * 60).toString(), "Every 24 hours");
932 | dropdown.addOption((7 * 24 * 60).toString(), "Every week");
933 |
934 | // select the currently-saved option
935 | dropdown.setValue(this.plugin.settings.frequency);
936 |
937 | dropdown.onChange(async (newValue) => {
938 | // update the plugin settings
939 | this.plugin.settings.frequency = newValue;
940 | await this.plugin.saveSettings();
941 |
942 | // destroy & re-create the scheduled task
943 | this.plugin.configureSchedule();
944 | });
945 | });
946 | new Setting(containerEl)
947 | .setName("Sync automatically when Obsidian opens")
948 | .setDesc("If enabled, Readwise will automatically resync with Obsidian each time you open the app")
949 | .addToggle((toggle) => {
950 | toggle.setValue(this.plugin.settings.triggerOnLoad);
951 | toggle.onChange(async (val) => {
952 | this.plugin.settings.triggerOnLoad = val;
953 | await this.plugin.saveSettings();
954 | });
955 | }
956 | );
957 | new Setting(containerEl)
958 | .setName("Resync deleted files")
959 | .setDesc("If enabled, you can refresh individual items by deleting the file in Obsidian and initiating a resync")
960 | .addToggle((toggle) => {
961 | toggle.setValue(this.plugin.settings.refreshBooks);
962 | toggle.onChange(async (val) => {
963 | this.plugin.settings.refreshBooks = val;
964 | await this.plugin.saveSettings();
965 | if (val) {
966 | await this.plugin.syncBookHighlights();
967 | }
968 | });
969 | }
970 | );
971 |
972 | if (this.plugin.settings.lastSyncFailed) {
973 | this.plugin.showInfoStatus(containerEl.find(".rw-setting-sync .rw-info-container").parentElement, "Last sync failed", "rw-error");
974 | }
975 | } else {
976 | new Setting(containerEl)
977 | .setName("Connect Obsidian to Readwise")
978 | .setClass("rw-setting-connect")
979 | .setDesc("The Readwise plugin enables automatic syncing of all your highlights from Kindle, Instapaper, Pocket, and more. Note: Requires Readwise account.")
980 | .addButton((button) => {
981 | button.setButtonText("Connect").setCta().onClick(async (evt) => {
982 | const success = await this.plugin.getUserAuthToken(evt.target as HTMLElement);
983 | if (success) {
984 | // re-render the settings
985 | this.display();
986 |
987 | this.plugin.notice("Readwise connected", true);
988 | }
989 | });
990 | });
991 | let el = containerEl.createEl("div", { cls: "rw-info-container" });
992 | containerEl.find(".rw-setting-connect > .setting-item-control ").prepend(el);
993 | }
994 | const help = containerEl.createEl('p',);
995 | help.innerHTML = "Question? Please see our Documentation or email us at hello@readwise.io 🙂";
996 | }
997 | }
998 |
--------------------------------------------------------------------------------
/src/status.ts:
--------------------------------------------------------------------------------
1 | // Inspired by
2 | // https://github.com/renehernandez/obsidian-readwise/blob/eee5676524962ebfa7eaf1084e018dafe3c2f394/src/status.ts
3 |
4 | export class StatusBar {
5 | private messages: StatusBarMessage[] = [];
6 | private currentMessage: StatusBarMessage;
7 | private lastMessageTimestamp: number;
8 | private statusBarEl: HTMLElement;
9 |
10 | constructor(statusBarEl: HTMLElement) {
11 | this.statusBarEl = statusBarEl;
12 | }
13 |
14 | displayMessage(message: string, timeout: number, forcing: boolean = false) {
15 | if (this.messages[0] && this.messages[0].message === message) {
16 | // don't show the same message twice
17 | return;
18 | }
19 | this.messages.push({
20 | message: `readwise: ${message.slice(0, 100)}`,
21 | timeout: timeout * 1000,
22 | });
23 | if (forcing) {
24 | this.currentMessage = null;
25 | this.lastMessageTimestamp = null;
26 | this.statusBarEl.setText("");
27 | }
28 | this.display();
29 | }
30 |
31 | display() {
32 | if (this.currentMessage) {
33 | let messageAge = Date.now() - this.lastMessageTimestamp;
34 | if (messageAge >= this.currentMessage.timeout) {
35 | this.currentMessage = null;
36 | this.lastMessageTimestamp = null;
37 | }
38 | } else if (this.messages.length) {
39 | this.currentMessage = this.messages.shift();
40 | this.statusBarEl.setText(this.currentMessage.message);
41 | this.lastMessageTimestamp = Date.now();
42 | return;
43 | } else {
44 | this.statusBarEl.setText("");
45 | }
46 | }
47 | }
48 |
49 | export interface StatusBarMessage {
50 | message: string;
51 | timeout: number;
52 | }
53 |
--------------------------------------------------------------------------------
/styles.css:
--------------------------------------------------------------------------------
1 |
2 | .theme-light {
3 | --hyper-highlight: var(--text-highlight-bg, #FFF2AC);
4 | --error-color: #DB5461;
5 | --success-color: #8AAA79;
6 | --info-color: var(--text-muted, #000);
7 | }
8 |
9 | .theme-dark {
10 | --hyper-highlight: var(--text-highlight-bg, #1C5998);
11 | --error-color: #DB5461;
12 | --success-color: #8AAA79;
13 | --info-color: var(--text-muted, #fff);
14 | }
15 |
16 | .rw-info-container {
17 | margin-inline-end: 10px;
18 | }
19 |
20 | .rw-info {
21 | color: var(--info-color);
22 | font-size: smaller;
23 | }
24 |
25 | .rw-error {
26 | color: var(--error-color);
27 | }
28 | .rw-success {
29 | color: var(--success-color);
30 | }
31 |
32 |
33 | img[alt=rw-book-cover] {
34 | max-height: 200px;
35 | }
36 |
37 | .rw-hyper-highlight {
38 | background-color: var(--hyper-highlight);
39 | }
40 |
41 | .rw-modal-btns {
42 | display: flex;
43 | justify-content: flex-end;
44 | gap: 0.5rem;
45 | }
46 |
47 | .rw-modal-confirmation {
48 | display: flex;
49 | align-items: center;
50 | gap: 0.5rem;
51 | justify-content: flex-end;
52 | margin-block-start: 1em;
53 | font-size: smaller;
54 | }
55 |
56 | .rw-modal-warning-text {
57 | margin-block-start: 0;
58 | }
59 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "inlineSourceMap": true,
5 | "inlineSources": true,
6 | "module": "ESNext",
7 | "target": "es6",
8 | "allowJs": true,
9 | "noImplicitAny": true,
10 | "moduleResolution": "node",
11 | "importHelpers": true,
12 | "lib": [
13 | "dom",
14 | "es5",
15 | "scripthost",
16 | "es2015"
17 | ]
18 | },
19 | "include": [
20 | "**/*.ts"
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/versions.json:
--------------------------------------------------------------------------------
1 | {
2 | "1.0.0": "0.12.10",
3 | "1.0.1": "0.12.10",
4 | "1.0.2": "0.12.10",
5 | "1.0.3": "0.12.10",
6 | "1.0.4": "0.12.10",
7 | "1.0.5": "0.12.10",
8 | "1.0.6": "0.12.10",
9 | "1.0.7": "0.12.10",
10 | "2.0.0": "0.12.10",
11 | "2.0.1": "0.12.10",
12 | "2.1.0": "1.0.0",
13 | "2.1.1": "1.0.0",
14 | "2.1.2": "1.0.0",
15 | "2.1.3": "1.0.0",
16 | "2.1.4": "1.0.0",
17 | "3.0.0": "1.0.0",
18 | "3.0.1": "1.0.0"
19 | }
20 |
--------------------------------------------------------------------------------