├── .luacheckrc
├── .luarc.json
├── COPYING
├── README.md
└── syncthing.koplugin
├── _meta.lua
├── insert_menu.lua
├── lib
├── LICENCE_lua-feedparser
├── LICENSE_LuaXML
├── dateparser.lua
├── handler.lua
└── xml.lua
├── main.lua
├── start-syncthing
└── syncthing
/.luacheckrc:
--------------------------------------------------------------------------------
1 | unused_args = false
2 | std = "luajit"
3 | -- ignore implicit self
4 | self = false
5 |
6 | globals = {
7 | "G_reader_settings",
8 | "G_defaults",
9 | "table.pack",
10 | "table.unpack",
11 | }
12 |
13 | read_globals = {
14 | "_ENV",
15 | }
16 |
17 | -- 211 - Unused local variable
18 | -- 631 - Line is too long
19 | ignore = {
20 | "211/__*",
21 | "631",
22 | }
23 |
--------------------------------------------------------------------------------
/.luarc.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://raw.githubusercontent.com/sumneko/vscode-lua/master/setting/schema.json",
3 | "runtime.version": "LuaJIT",
4 | }
5 |
6 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Syncthing plugin for KOReader
2 |
3 | This is a plugin for running Syncthing on e-readers running KOReader. Syncthing
4 | is a peer-to-peer file synchronization program. This makes it possible to sync
5 | files between your e-reader and computer / phone automatically. The Syncthing
6 | instance on your e-reader can be managed directly in the KOReader menu.
7 |
8 | The method of running Syncthing is originally based on [The Anarcat's blog post](https://anarc.at/hardware/tablet/kobo-clara-hd/#install-syncthing).
9 |
10 | ## Project status
11 |
12 | - This plugin has not been widely tested. Make frequent data backups and use it
13 | at your own risk!
14 | - Tested on Kobo Libra 2
15 | - Some features are not working yet, such as global discovery service
16 |
17 | ## Installation
18 |
19 | ### Prerequisites
20 |
21 | - Currently the plugin is only tested on a Kobo device. Maybe it will also work
22 | on Kindle and other Linux-based environments, but additional testing will be
23 | needed.
24 | - You should have installed KOReader and will need to copy files to the device.
25 | - You need to setup Syncthing on another device, which will be able to connect
26 | to your e-reader in your local Wi-Fi network.
27 |
28 | ### Install plugin
29 |
30 | 1. Download the [latest ZIP from GitHub](https://github.com/jasonchoimtt/koreader-syncthing/archive/refs/heads/main.zip)
31 | and extract the archive.
32 | 2. Copy the folder `syncthing.koplugin` to your KOReader installation, under
33 | the `plugins` folder. For Kobo devices, this is usually
34 | `.adds/koreader/plugins` in the device storage.
35 | 3. Restart KOReader.
36 |
37 | ### Configure devices and folders
38 |
39 | 4. The Syncthing menu will be available under the Tools tab in the file
40 | browser. Check *Syncthing* menu item to start the Syncthing server. Make
41 | sure the e-reader is also connected to Wi-Fi.
42 | 5. On your other Syncthing device, add the e-reader by scanning the QR code or
43 | entering the device ID manually.
44 | 6. Go to the *Pending* menu and accept the device.
45 | 7. On your other Syncthing device, add the e-reader to a folder.
46 | 8. Go to the *Pending* menu and accept the folder.
47 | 9. View the *Status* menu to see sync status.
48 | 10. For other options you will need to use the Syncthing GUI. Use *Set GUI
49 | Password* menu item to set GUI password and go to `http://:8384`
50 | on another device. Login with username `syncthing` and your password. You
51 | can tap *Syncthing Web GUI* menu item to see network info.
52 |
53 | ## FAQ
54 |
55 | - **Why would you want Syncthing on an e-reader?**
56 |
57 | It keeps my books and annotations continuously synchronized with my computer
58 | and my Android phone (which can has a Syncthing app). It comes in handy when
59 | you read books with KOReader on multiple devices. For the privacy-conscious
60 | people, Syncthing does not require creating a cloud account and storing your
61 | data in their cloud.
62 |
63 | - **How well does it work?**
64 |
65 | The synchronization itself usually works quite well on the e-reader side, but
66 | the connectivity is also affected by your other devices and the local network
67 | conditions. I will still need to iron out a few wrinkles to make the
68 | experience great. But having a Syncthing menu right in KOReader is the first
69 | step in making this accessible to the community.
70 |
71 | ## Developing
72 |
73 | - Syncthing binaries are included in the repository from the [official
74 | releases](https://syncthing.net/downloads/)
75 | - Using Linux ARM 32-bit binary
76 |
77 | ## Limitations
78 |
79 | - Currently, global discovery and relay is not working. That means it will not
80 | be possible to sync devices over the internet.
81 | - The Syncthing menu is still limited in functionality when it comes to managing
82 | devices and folders.
83 |
84 | ## TODO
85 |
86 | - [ ] Pull latest syncthing binary from official releases
87 | - [ ] Allow adding device to folder from e-reader
88 | - [ ] Properly accept three-way sharing
89 | - [ ] Fix global discovery service functionality
90 | - [ ] Implement conflict resolution for KOReader metadata file
91 |
--------------------------------------------------------------------------------
/syncthing.koplugin/_meta.lua:
--------------------------------------------------------------------------------
1 | local _ = require("gettext")
2 | return {
3 | name = "Syncthing",
4 | fullname = _("Syncthing"),
5 | description = _([[Continuously sync files with other devices in a peer-to-peer manner.]]),
6 | }
7 |
--------------------------------------------------------------------------------
/syncthing.koplugin/insert_menu.lua:
--------------------------------------------------------------------------------
1 | -- Add Syncthing to the Tools menu in File Manager, after cloud storage item
2 | local filemanager_order = require("ui/elements/filemanager_menu_order")
3 |
4 | local pos = 1
5 | for index, value in ipairs(filemanager_order.tools) do
6 | if value == "cloud_storage" then
7 | pos = index + 1
8 | break
9 | end
10 | end
11 |
12 | table.insert(filemanager_order.tools, pos, "syncthing")
13 |
--------------------------------------------------------------------------------
/syncthing.koplugin/lib/LICENCE_lua-feedparser:
--------------------------------------------------------------------------------
1 | feedparser is available under the (new) BSD license. it uses a
2 | portion of LuaSocket code (copyright 2007 Diego Nehab)
3 | (http://www.keplerproject.org/luaexpat/), which is under the MIT license.
4 |
5 | Copyright (c) 2009 Leo Ponomarev.
6 | All rights reserved.
7 |
8 | Redistribution and use in source and binary forms, with or without
9 | modification, are permitted provided that the following conditions are met:
10 | * Redistributions of source code must retain the above copyright
11 | notice, this list of conditions and the following disclaimer.
12 | * Redistributions in binary form must reproduce the above copyright
13 | notice, this list of conditions and the following disclaimer in the
14 | documentation and/or other materials provided with the distribution.
15 | * Neither the name of the nor the
16 | names of its contributors may be used to endorse or promote products
17 | derived from this software without specific prior written permission.
18 |
19 | THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY
20 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 |
--------------------------------------------------------------------------------
/syncthing.koplugin/lib/LICENSE_LuaXML:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Manoel Campos da Silva Filho
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/syncthing.koplugin/lib/dateparser.lua:
--------------------------------------------------------------------------------
1 | local difftime, time, date = os.difftime, os.time, os.date
2 | local format = string.format
3 | local tremove, tinsert = table.remove, table.insert
4 | local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable
5 |
6 | local dateparser={}
7 |
8 | --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore.
9 | local unix_timestamp
10 | do
11 | local now = time()
12 | local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now)))
13 | unix_timestamp = function(t, offset_sec)
14 | local success, improper_time = pcall(time, t)
15 | if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end
16 | return improper_time - local_UTC_offset_sec - offset_sec
17 | end
18 | end
19 |
20 | local formats = {} -- format names
21 | local format_func = setmetatable({}, {__mode='v'}) --format functions
22 |
23 | ---register a date format parsing function
24 | function dateparser.register_format(format_name, format_function)
25 | if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end
26 |
27 | local found
28 | for i, f in ipairs(format_func) do --for ordering
29 | if f==format_function then
30 | found=true
31 | break
32 | end
33 | end
34 | if not found then
35 | tinsert(format_func, format_function)
36 | end
37 | formats[format_name] = format_function
38 | return true
39 | end
40 |
41 | ---register a date format parsing function
42 | function dateparser.unregister_format(format_name)
43 | if type(format_name)~="string" then return nil, "format name must be a string" end
44 | formats[format_name]=nil
45 | end
46 |
47 | ---return the function responsible for handling format_name date strings
48 | function dateparser.get_format_function(format_name)
49 | return formats[format_name] or nil, ("format %s not registered"):format(format_name)
50 | end
51 |
52 | ---try to parse date string
53 | --@param str date string
54 | --@param date_format optional date format name, if known
55 | --@return unix timestamp if str can be parsed; nil, error otherwise.
56 | function dateparser.parse(str, date_format)
57 | local success, res, err
58 | if date_format then
59 | if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end
60 | success, res = pcall(formats[date_format], str)
61 | else
62 | for i, func in ipairs(format_func) do
63 | success, res = pcall(func, str)
64 | if success and res then return res end
65 | end
66 | end
67 | return success and res
68 | end
69 |
70 | dateparser.register_format('W3CDTF', function(rest)
71 |
72 | local year, day_of_year, month, day, week
73 | local hour, minute, second, second_fraction, offset_hours
74 |
75 | local alt_rest
76 |
77 | year, rest = rest:match("^(%d%d%d%d)%-?(.*)$")
78 |
79 | day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$")
80 |
81 | if day_of_year then rest=alt_rest end
82 |
83 | month, rest = rest:match("^(%d%d)%-?(.*)$")
84 |
85 | day, rest = rest:match("^(%d%d)(.*)$")
86 | if #rest>0 then
87 | rest = rest:match("^T(.*)$")
88 | hour, rest = rest:match("^([0-2][0-9]):?(.*)$")
89 | minute, rest = rest:match("^([0-6][0-9]):?(.*)$")
90 | second, rest = rest:match("^([0-6][0-9])(.*)$")
91 | second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$")
92 | if second_fraction then
93 | rest=alt_rest
94 | end
95 | if rest=="Z" then
96 | rest=""
97 | offset_hours=0
98 | else
99 | local sign, offset_h, offset_m
100 | sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$")
101 | local offset_m, alt_rest = rest:match("^(%d%d)(.*)$")
102 | if offset_m then rest=alt_rest end
103 | offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60
104 | end
105 | if #rest>0 then return nil end
106 | end
107 |
108 | year = tonumber(year)
109 | local d = {
110 | year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))),
111 | month = tonumber(month) or 1,
112 | day = tonumber(day) or 1,
113 | hour = tonumber(hour) or 0,
114 | min = tonumber(minute) or 0,
115 | sec = tonumber(second) or 0,
116 | isdst = false
117 | }
118 | local t = unix_timestamp(d, (offset_hours or 0) * 3600)
119 | if second_fraction then
120 | return t + tonumber("0."..second_fraction)
121 | else
122 | return t
123 | end
124 | end)
125 |
126 |
127 | do
128 | local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/
129 | A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9,
130 | K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5,
131 | S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12,
132 | Z = 0,
133 |
134 | EST = -5, EDT = -4, CST = -6, CDT = -5,
135 | MST = -7, MDT = -6, PST = -8, PDT = -7,
136 |
137 | GMT = 0, UT = 0, UTC = 0
138 | }
139 |
140 | local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
141 |
142 | dateparser.register_format('RFC2822', function(rest)
143 |
144 | local year, month, day, day_of_year, week_of_year, weekday
145 | local hour, minute, second, second_fraction, offset_hours
146 |
147 | local alt_rest
148 |
149 | weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$")
150 | if weekday then rest=alt_rest end
151 | day, rest=rest:match("^(%d%d?)%s+(.*)$")
152 | month, rest=rest:match("^(%w%w%w)%s+(.*)$")
153 | month = month_val[month]
154 | year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$")
155 | hour, rest = rest:match("^(%d%d?):(.*)$")
156 | minute, rest = rest:match("^(%d%d?)(.*)$")
157 | second, alt_rest = rest:match("^:(%d%d)(.*)$")
158 | if second then rest = alt_rest end
159 | local tz, offset_sign, offset_h, offset_m
160 | tz, alt_rest = rest:match("^%s+(%u+)(.*)$")
161 | if tz then
162 | rest = alt_rest
163 | offset_hours = tz_table[tz]
164 | else
165 | offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$")
166 | offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60
167 | end
168 |
169 | if #rest>0 or not (year and day and month and hour and minute) then
170 | return nil
171 | end
172 |
173 | year = tonumber(year)
174 | local d = {
175 | year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))),
176 | month = month,
177 | day = tonumber(day),
178 |
179 | hour= tonumber(hour) or 0,
180 | min = tonumber(minute) or 0,
181 | sec = tonumber(second) or 0,
182 | isdst = false
183 | }
184 | return unix_timestamp(d, offset_hours * 3600)
185 | end)
186 | end
187 |
188 | dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough
189 | dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF
190 |
191 |
192 | return dateparser
--------------------------------------------------------------------------------
/syncthing.koplugin/lib/handler.lua:
--------------------------------------------------------------------------------
1 | ---
2 | -- Overview:
3 | -- =========
4 | -- Standard XML event handler(s) for XML parser module (xml.lua)
5 | --
6 | -- Features:
7 | -- =========
8 | -- printHandler - Generate XML event trace
9 | -- domHandler - Generate DOM-like node tree
10 | -- simpleTreeHandler - Generate 'simple' node tree
11 | --
12 | -- API:
13 | -- ====
14 | -- Must be called as handler function from xmlParser
15 | -- and implement XML event callbacks (see xmlParser.lua
16 | -- for callback API definition)
17 | --
18 | -- printHandler:
19 | -- -------------
20 | --
21 | -- printHandler prints event trace for debugging
22 | --
23 | -- domHandler:
24 | -- -----------
25 | --
26 | -- domHandler generates a DOM-like node tree structure with
27 | -- a single ROOT node parent - each node is a table comprising
28 | -- fields below.
29 | --
30 | -- node = { _name = ,
31 | -- _type = ROOT|ELEMENT|TEXT|COMMENT|PI|DECL|DTD,
32 | -- _attr = { Node attributes - see callback API },
33 | -- _parent =
34 | -- _children = { List of child nodes - ROOT/NODE only }
35 | -- }
36 | --
37 | -- The dom structure is capable of representing any valid XML document
38 | --
39 | -- simpleTreeHandler
40 | -- -----------------
41 | --
42 | -- simpleTreeHandler is a simplified handler which attempts
43 | -- to generate a more 'natural' table based structure which
44 | -- supports many common XML formats.
45 | --
46 | -- The XML tree structure is mapped directly into a recursive
47 | -- table structure with node names as keys and child elements
48 | -- as either a table of values or directly as a string value
49 | -- for text. Where there is only a single child element this
50 | -- is inserted as a named key - if there are multiple
51 | -- elements these are inserted as a vector (in some cases it
52 | -- may be preferable to always insert elements as a vector
53 | -- which can be specified on a per element basis in the
54 | -- options). Attributes are inserted as a child element with
55 | -- a key of '_attr'.
56 | --
57 | -- Only Tag/Text & CDATA elements are processed - all others
58 | -- are ignored.
59 | --
60 | -- This format has some limitations - primarily
61 | --
62 | -- * Mixed-Content behaves unpredictably - the relationship
63 | -- between text elements and embedded tags is lost and
64 | -- multiple levels of mixed content does not work
65 | -- * If a leaf element has both a text element and attributes
66 | -- then the text must be accessed through a vector (to
67 | -- provide a container for the attribute)
68 | --
69 | -- In general however this format is relatively useful.
70 | --
71 | -- It is much easier to understand by running some test
72 | -- data through 'textxml.lua -simpletree' than to read this)
73 | --
74 | -- Options
75 | -- =======
76 | -- simpleTreeHandler.options.noReduce = { = bool,.. }
77 | --
78 | -- - Nodes not to reduce children vector even if only
79 | -- one child
80 | --
81 | -- domHandler.options.(comment|pi|dtd|decl)Node = bool
82 | --
83 | -- - Include/exclude given node types
84 | --
85 | -- Usage
86 | -- =====
87 | -- Pased as delegate in xmlParser constructor and called
88 | -- as callback by xmlParser:parse(xml) method.
89 | --
90 | -- See textxml.lua for examples
91 | -- License:
92 | -- ========
93 | --
94 | -- This code is freely distributable under the terms of the Lua license
95 | -- (http://www.lua.org/copyright.html)
96 | --
97 | -- History
98 | -- =======
99 | -- $Id: handler.lua,v 1.1.1.1 2001/11/28 06:11:33 paulc Exp $
100 | --
101 | -- $Log: handler.lua,v $
102 | -- Revision 1.1.1.1 2001/11/28 06:11:33 paulc
103 | -- Initial Import
104 | --@author Paul Chakravarti (paulc@passtheaardvark.com)
105 |
106 |
107 | ---Handler to generate a string prepresentation of a table
108 | --Convenience function for printHandler (Does not support recursive tables).
109 | --@param t Table to be parsed
110 | --@returns Returns a string representation of table
111 | local function showTable(t)
112 | local sep = ''
113 | local res = ''
114 | if type(t) ~= 'table' then
115 | return t
116 | end
117 | for k,v in pairs(t) do
118 | if type(v) == 'table' then
119 | v = showTable(v)
120 | end
121 | res = res .. sep .. string.format("%s=%s",k,v)
122 | sep = ','
123 | end
124 | res = '{'..res..'}'
125 | return res
126 | end
127 |
128 | ---Handler to generate a simple event trace
129 | local printHandler = function()
130 | local obj = {}
131 | obj.starttag = function(self,t,a,s,e)
132 | io.write("Start : "..t.."\n")
133 | if a then
134 | for k,v in pairs(a) do
135 | io.write(string.format(" + %s='%s'\n",k,v))
136 | end
137 | end
138 | end
139 | obj.endtag = function(self,t,s,e)
140 | io.write("End : "..t.."\n")
141 | end
142 | obj.text = function(self,t,s,e)
143 | io.write("Text : "..t.."\n")
144 | end
145 | obj.cdata = function(self,t,s,e)
146 | io.write("CDATA : "..t.."\n")
147 | end
148 | obj.comment = function(self,t,s,e)
149 | io.write("Comment : "..t.."\n")
150 | end
151 | obj.dtd = function(self,t,a,s,e)
152 | io.write("DTD : "..t.."\n")
153 | if a then
154 | for k,v in pairs(a) do
155 | io.write(string.format(" + %s='%s'\n",k,v))
156 | end
157 | end
158 | end
159 | obj.pi = function(self,t,a,s,e)
160 | io.write("PI : "..t.."\n")
161 | if a then
162 | for k,v in pairs(a) do
163 | io. write(string.format(" + %s='%s'\n",k,v))
164 | end
165 | end
166 | end
167 | obj.decl = function(self,t,a,s,e)
168 | io.write("XML Decl : "..t.."\n")
169 | if a then
170 | for k,v in pairs(a) do
171 | io.write(string.format(" + %s='%s'\n",k,v))
172 | end
173 | end
174 | end
175 | return obj
176 | end
177 |
178 |
179 | --Obtém a primeira chave de uma tabela
180 | --@param Tabela de onde deverá ser obtido o primeiro elemento
181 | --@return Retorna a primeira chave da tabela
182 | local function getFirstKey(tb)
183 | if type(tb) == "table" then
184 | --O uso da função next não funciona para pegar o primeiro elemento. Trava aqui
185 | --k, v = next(tb)
186 | --return k
187 | for k, v in pairs(tb) do
188 | return k
189 | end
190 | return nil
191 | else
192 | return tb
193 | end
194 | end
195 |
196 | ---Handler to generate a lua table from a XML content string
197 | local function simpleTreeHandler()
198 | local obj = {}
199 |
200 | obj.root = {}
201 | obj.stack = {obj.root;n=1}
202 | obj.options = {noreduce = {}}
203 |
204 | obj.reduce = function(self,node,key,parent)
205 | -- Recursively remove redundant vectors for nodes
206 | -- with single child elements
207 | for k,v in pairs(node) do
208 | if type(v) == 'table' then
209 | self:reduce(v,k,node)
210 | end
211 | end
212 | if #node == 1 and not self.options.noreduce[key] and
213 | node._attr == nil then
214 | parent[key] = node[1]
215 | else
216 | node.n = nil
217 | end
218 | end
219 |
220 | --@param t Table that represents a XML tag
221 | --@param a Attributes table (_attr)
222 | obj.starttag = function(self,t,a)
223 | local node = {}
224 | if self.parseAttributes == true then
225 | node._attr=a
226 | end
227 |
228 | local current = self.stack[#self.stack]
229 | if current[t] then
230 | table.insert(current[t],node)
231 | else
232 | current[t] = {node;n=1}
233 | end
234 | table.insert(self.stack,node)
235 | end
236 |
237 | --@param t Tag name
238 | obj.endtag = function(self,t,s)
239 | --Tabela que representa a tag atualmente sendo processada
240 | local current = self.stack[#self.stack]
241 | --Tabela que representa a tag na qual a tag
242 | --atual está contida.
243 | local prev = self.stack[#self.stack-1]
244 | if not prev[t] then
245 | error("XML Error - Unmatched Tag ["..s..":"..t.."]\n")
246 | end
247 | if prev == self.root then
248 | -- Once parsing complete recursively reduce tree
249 | self:reduce(prev,nil,nil)
250 | end
251 |
252 | local firstKey = getFirstKey(current)
253 | --Se a primeira chave da tabela que representa
254 | --a tag atual não possui nenhum elemento,
255 | --é porque não há nenhum valor associado à tag
256 | -- (como nos casos de tags automaticamente fechadas como ).
257 | --Assim, atribui uma string vazia a mesma para
258 | --que seja retornado vazio no lugar da tag e não
259 | --uma tabela. Retornando uma string vazia
260 | --simplifica para as aplicações NCLua
261 | --para imprimir tal valor.
262 | if firstKey == nil then
263 | current[t] = ""
264 | prev[t] = ""
265 | end
266 |
267 | table.remove(self.stack)
268 | end
269 |
270 | obj.text = function(self,t)
271 | local current = self.stack[#self.stack]
272 | table.insert(current,t)
273 | end
274 |
275 | obj.cdata = obj.text
276 |
277 | return obj
278 | end
279 |
280 | --- domHandler
281 | local function domHandler()
282 | local obj = {}
283 | obj.options = {commentNode=1,piNode=1,dtdNode=1,declNode=1}
284 | obj.root = { _children = {n=0}, _type = "ROOT" }
285 | obj.current = obj.root
286 | obj.starttag = function(self,t,a)
287 | local node = { _type = 'ELEMENT',
288 | _name = t,
289 | _attr = a,
290 | _parent = self.current,
291 | _children = {n=0} }
292 | table.insert(self.current._children,node)
293 | self.current = node
294 | end
295 | obj.endtag = function(self,t,s)
296 | if t ~= self.current._name then
297 | error("XML Error - Unmatched Tag ["..s..":"..t.."]\n")
298 | end
299 | self.current = self.current._parent
300 | end
301 | obj.text = function(self,t)
302 | local node = { _type = "TEXT",
303 | _parent = self.current,
304 | _text = t }
305 | table.insert(self.current._children,node)
306 | end
307 | obj.comment = function(self,t)
308 | if self.options.commentNode then
309 | local node = { _type = "COMMENT",
310 | _parent = self.current,
311 | _text = t }
312 | table.insert(self.current._children,node)
313 | end
314 | end
315 | obj.pi = function(self,t,a)
316 | if self.options.piNode then
317 | local node = { _type = "PI",
318 | _name = t,
319 | _attr = a,
320 | _parent = self.current }
321 | table.insert(self.current._children,node)
322 | end
323 | end
324 | obj.decl = function(self,t,a)
325 | if self.options.declNode then
326 | local node = { _type = "DECL",
327 | _name = t,
328 | _attr = a,
329 | _parent = self.current }
330 | table.insert(self.current._children,node)
331 | end
332 | end
333 | obj.dtd = function(self,t,a)
334 | if self.options.dtdNode then
335 | local node = { _type = "DTD",
336 | _name = t,
337 | _attr = a,
338 | _parent = self.current }
339 | table.insert(self.current._children,node)
340 | end
341 | end
342 | obj.cdata = obj.text
343 | return obj
344 | end
345 |
346 | return { simpleTreeHandler = simpleTreeHandler }
347 |
--------------------------------------------------------------------------------
/syncthing.koplugin/lib/xml.lua:
--------------------------------------------------------------------------------
1 | ---
2 | -- Overview:
3 | -- =========
4 | --
5 | -- This module provides a non-validating XML stream parser in Lua.
6 | --
7 | -- Features:
8 | -- =========
9 | --
10 | -- * Tokenises well-formed XML (relatively robustly)
11 | -- * Flexible handler based event API (see below)
12 | -- * Parses all XML Infoset elements - ie.
13 | -- - Tags
14 | -- - Text
15 | -- - Comments
16 | -- - CDATA
17 | -- - XML Decl
18 | -- - Processing Instructions
19 | -- - DOCTYPE declarations
20 | -- * Provides limited well-formedness checking
21 | -- (checks for basic syntax & balanced tags only)
22 | -- * Flexible whitespace handling (selectable)
23 | -- * Entity Handling (selectable)
24 | --
25 | -- Limitations:
26 | -- ============
27 | --
28 | -- * Non-validating
29 | -- * No charset handling
30 | -- * No namespace support
31 | -- * Shallow well-formedness checking only (fails
32 | -- to detect most semantic errors)
33 | --
34 | -- API:
35 | -- ====
36 | --
37 | -- The parser provides a partially object-oriented API with
38 | -- functionality split into tokeniser and handler components.
39 | --
40 | -- The handler instance is passed to the tokeniser and receives
41 | -- callbacks for each XML element processed (if a suitable handler
42 | -- function is defined). The API is conceptually similar to the
43 | -- SAX API but implemented differently.
44 | --
45 | -- The following events are generated by the tokeniser
46 | --
47 | -- handler:start - Start Tag
48 | -- handler:end - End Tag
49 | -- handler:text - Text
50 | -- handler:decl - XML Declaration
51 | -- handler:pi - Processing Instruction
52 | -- handler:comment - Comment
53 | -- handler:dtd - DOCTYPE definition
54 | -- handler:cdata - CDATA
55 | --
56 | -- The function prototype for all the callback functions is
57 | --
58 | -- callback(val,attrs,start,end)
59 | --
60 | -- where attrs is a table and val/attrs are overloaded for
61 | -- specific callbacks - ie.
62 | --
63 | -- Callback val attrs (table)
64 | -- -------- --- -------------
65 | -- start name { attributes (name=val).. }
66 | -- end name nil
67 | -- text nil
68 | -- cdata nil
69 | -- decl "xml" { attributes (name=val).. }
70 | -- pi pi name { attributes (if present)..
71 | -- _text =
72 | -- }
73 | -- comment nil
74 | -- dtd root element { _root = ,
75 | -- _type = SYSTEM|PUBLIC,
76 | -- _name = ,
77 | -- _uri = ,
78 | -- _internal =
79 | -- }
80 | --
81 | -- (start & end provide the character positions of the start/end
82 | -- of the element)
83 | --
84 | -- XML data is passed to the parser instance through the 'parse'
85 | -- method (Note: must be passed a single string currently)
86 | --
87 | -- Options
88 | -- =======
89 | --
90 | -- Parser options are controlled through the 'self.options' table.
91 | -- Available options are -
92 | --
93 | -- * stripWS
94 | --
95 | -- Strip non-significant whitespace (leading/trailing)
96 | -- and do not generate events for empty text elements
97 | --
98 | -- * expandEntities
99 | --
100 | -- Expand entities (standard entities + single char
101 | -- numeric entities only currently - could be extended
102 | -- at runtime if suitable DTD parser added elements
103 | -- to table (see obj._ENTITIES). May also be possible
104 | -- to expand multibyre entities for UTF-8 only
105 | --
106 | -- * errorHandler
107 | --
108 | -- Custom error handler function
109 | --
110 | -- NOTE: Boolean options must be set to 'nil' not '0'
111 | --
112 | -- Usage
113 | -- =====
114 | --
115 | -- Create a handler instance -
116 | --
117 | -- h = { start = function(t,a,s,e) .... end,
118 | -- end = function(t,a,s,e) .... end,
119 | -- text = function(t,a,s,e) .... end,
120 | -- cdata = text }
121 | --
122 | -- (or use predefined handler - see handler.lua)
123 | --
124 | -- Create parser instance -
125 | --
126 | -- p = xmlParser(h)
127 | --
128 | -- Set options -
129 | --
130 | -- p.options.xxxx = nil
131 | --
132 | -- Parse XML data -
133 | --
134 | -- xmlParser:parse("
157 |
158 |
159 | ---Parses a XML string
160 | --@param handler Handler object to be used to convert the XML string
161 | --to another formats. @see handler.lua
162 | local xmlParser = function(handler)
163 | local obj = {}
164 | -- Public attributes
165 |
166 | obj.options = {
167 | stripWS = 1,
168 | expandEntities = 1,
169 | errorHandler = function(err,pos)
170 | error(string.format("%s [char=%d]\n",
171 | err or "Parse Error",pos))
172 | end,
173 | }
174 |
175 | -- Public methods
176 |
177 | obj.parse = function(self, str, parseAttributes)
178 | if parseAttributes == nil then
179 | parseAttributes = true
180 | end
181 | self._handler.parseAttributes = parseAttributes
182 |
183 | local match,endmatch,pos = 0,0,1
184 | local text,endt1,endt2,tagstr,tagname,attrs,starttext,endtext
185 | local errstart,errend,extstart,extend
186 | while match do
187 | -- Get next tag (first pass - fix exceptions below)
188 | match,endmatch,text,endt1,tagstr,endt2 = string.find(str,self._XML,pos)
189 | if not match then
190 | if string.find(str, self._WS,pos) then
191 | -- No more text - check document complete
192 | if #self._stack ~= 0 then
193 | self:_err(self._errstr.incompleteXmlErr,pos)
194 | else
195 | break
196 | end
197 | else
198 | -- Unparsable text
199 | self:_err(self._errstr.xmlErr,pos)
200 | end
201 | end
202 | -- Handle leading text
203 | starttext = match
204 | endtext = match + string.len(text) - 1
205 | match = match + string.len(text)
206 | text = self:_parseEntities(self:_stripWS(text))
207 | if text ~= "" and self._handler.text then
208 | self._handler:text(text,nil,match,endtext)
209 | end
210 | -- Test for tag type
211 | if string.find(string.sub(tagstr,1,5),"?xml%s") then
212 | -- XML Declaration
213 | match,endmatch,text = string.find(str,self._PI,pos)
214 | if not match then
215 | self:_err(self._errstr.declErr,pos)
216 | end
217 | if match ~= 1 then
218 | -- Must be at start of doc if present
219 | self:_err(self._errstr.declStartErr,pos)
220 | end
221 | tagname,attrs = self:_parseTag(text)
222 | -- TODO: Check attributes are valid
223 | -- Check for version (mandatory)
224 | if attrs.version == nil then
225 | self:_err(self._errstr.declAttrErr,pos)
226 | end
227 | if self._handler.decl then
228 | self._handler:decl(tagname,attrs,match,endmatch)
229 | end
230 | elseif string.sub(tagstr,1,1) == "?" then
231 | -- Processing Instruction
232 | match,endmatch,text = string.find(str,self._PI,pos)
233 | if not match then
234 | self:_err(self._errstr.piErr,pos)
235 | end
236 | if self._handler.pi then
237 | -- Parse PI attributes & text
238 | tagname,attrs = self:_parseTag(text)
239 | local pi = string.sub(text,string.len(tagname)+1)
240 | if pi ~= "" then
241 | if attrs then
242 | attrs._text = pi
243 | else
244 | attrs = { _text = pi }
245 | end
246 | end
247 | self._handler:pi(tagname,attrs,match,endmatch)
248 | end
249 | elseif string.sub(tagstr,1,3) == "!--" then
250 | -- Comment
251 | match,endmatch,text = string.find(str,self._COMMENT,pos)
252 | if not match then
253 | self:_err(self._errstr.commentErr,pos)
254 | end
255 | if self._handler.comment then
256 | text = self:_parseEntities(self:_stripWS(text))
257 | self._handler:comment(text,next,match,endmatch)
258 | end
259 | elseif string.sub(tagstr,1,8) == "!DOCTYPE" then
260 | -- DTD
261 | match,endmatch,attrs = self:_parseDTD(string,pos)
262 | if not match then
263 | self:_err(self._errstr.dtdErr,pos)
264 | end
265 | if self._handler.dtd then
266 | self._handler:dtd(attrs._root,attrs,match,endmatch)
267 | end
268 | elseif string.sub(tagstr,1,8) == "![CDATA[" then
269 | -- CDATA
270 | match,endmatch,text = string.find(str,self._CDATA,pos)
271 | if not match then
272 | self:_err(self._errstr.cdataErr,pos)
273 | end
274 | if self._handler.cdata then
275 | self._handler:cdata(text,nil,match,endmatch)
276 | end
277 | else
278 | -- Normal tag
279 |
280 | -- Need check for embedded '>' in attribute value and extend
281 | -- match recursively if necessary eg.
282 |
283 | while 1 do
284 | errstart,errend = string.find(tagstr,self._ATTRERR1)
285 | if errend == nil then
286 | errstart,errend = string.find(tagstr,self._ATTRERR2)
287 | if errend == nil then
288 | break
289 | end
290 | end
291 | extstart,extend,endt2 = string.find(str,self._TAGEXT,endmatch+1)
292 | tagstr = tagstr .. string.sub(string,endmatch,extend-1)
293 | if not match then
294 | self:_err(self._errstr.xmlErr,pos)
295 | end
296 | endmatch = extend
297 | end
298 |
299 | -- Extract tagname/attrs
300 |
301 | tagname,attrs = self:_parseTag(tagstr)
302 |
303 | if (endt1=="/") then
304 | -- End tag
305 | if self._handler.endtag then
306 | if attrs then
307 | -- Shouldnt have any attributes in endtag
308 | self:_err(string.format("%s (/%s)",
309 | self._errstr.endTagErr,
310 | tagname)
311 | ,pos)
312 | end
313 | if table.remove(self._stack) ~= tagname then
314 | self:_err(string.format("%s (/%s)",
315 | self._errstr.unmatchedTagErr,
316 | tagname)
317 | ,pos)
318 | end
319 | self._handler:endtag(tagname,nil,match,endmatch)
320 | end
321 | else
322 | -- Start Tag
323 | table.insert(self._stack,tagname)
324 | if self._handler.starttag then
325 | self._handler:starttag(tagname,attrs,match,endmatch)
326 | end
327 | --TODO: Tags com fechamento automático estão sendo
328 | --retornadas como uma tabela, o que complica
329 | --para a app NCLua tratar isso. É preciso
330 | --fazer com que seja retornado um campo string vazio.
331 | -- Self-Closing Tag
332 | if (endt2=="/") then
333 | table.remove(self._stack)
334 | if self._handler.endtag then
335 | self._handler:endtag(tagname,nil,match,endmatch)
336 | end
337 | end
338 | end
339 | end
340 | pos = endmatch + 1
341 | end
342 | end
343 |
344 | -- Private attribures/functions
345 |
346 | obj._handler = handler
347 | obj._stack = {}
348 |
349 | obj._XML = '^([^<]*)<(%/?)([^>]-)(%/?)>'
350 | obj._ATTR1 = '([%w-:_]+)%s*=%s*"(.-)"'
351 | obj._ATTR2 = '([%w-:_]+)%s*=%s*\'(.-)\''
352 | obj._CDATA = '<%!%[CDATA%[(.-)%]%]>'
353 | obj._PI = '<%?(.-)%?>'
354 | obj._COMMENT = ''
355 | obj._TAG = '^(.-)%s.*'
356 | obj._LEADINGWS = '^%s+'
357 | obj._TRAILINGWS = '%s+$'
358 | obj._WS = '^%s*$'
359 | obj._DTD1 = ''
360 | obj._DTD2 = ''
361 | obj._DTD3 = ''
362 | obj._DTD4 = ''
363 | obj._DTD5 = ''
364 |
365 | obj._ATTRERR1 = '=%s*"[^"]*$'
366 | obj._ATTRERR2 = '=%s*\'[^\']*$'
367 | obj._TAGEXT = '(%/?)>'
368 |
369 | obj._ENTITIES = { ["<"] = "<",
370 | [">"] = ">",
371 | ["&"] = "&",
372 | ["""] = '"',
373 | ["'"] = "'",
374 | ["(%d+);"] = function (x)
375 | local d = tonumber(x)
376 | if d >= 0 and d < 256 then
377 | return string.char(d)
378 | else
379 | return ""..d..";"
380 | end
381 | end,
382 | ["(%x+);"] = function (x)
383 | local d = tonumber(x,16)
384 | if d >= 0 and d < 256 then
385 | return string.char(d)
386 | else
387 | return ""..x..";"
388 | end
389 | end,
390 | }
391 |
392 | obj._err = function(self,err,pos)
393 | if self.options.errorHandler then
394 | self.options.errorHandler(err,pos)
395 | end
396 | end
397 |
398 | obj._errstr = { xmlErr = "Error Parsing XML",
399 | declErr = "Error Parsing XMLDecl",
400 | declStartErr = "XMLDecl not at start of document",
401 | declAttrErr = "Invalid XMLDecl attributes",
402 | piErr = "Error Parsing Processing Instruction",
403 | commentErr = "Error Parsing Comment",
404 | cdataErr = "Error Parsing CDATA",
405 | dtdErr = "Error Parsing DTD",
406 | endTagErr = "End Tag Attributes Invalid",
407 | unmatchedTagErr = "Unbalanced Tag",
408 | incompleteXmlErr = "Incomplete XML Document",
409 | }
410 |
411 | obj._stripWS = function(self,s)
412 | if self.options.stripWS then
413 | s = string.gsub(s,'^%s+','')
414 | s = string.gsub(s,'%s+$','')
415 | end
416 | return s
417 | end
418 |
419 | obj._parseEntities = function(self,s)
420 | if self.options.expandEntities then
421 | --for k,v in self._ENTITIES do
422 | for k,v in pairs(self._ENTITIES) do
423 | --print (k, v)
424 | s = string.gsub(s,k,v)
425 | end
426 | end
427 | return s
428 | end
429 |
430 | obj._parseDTD = function(self,s,pos)
431 | -- match,endmatch,root,type,name,uri,internal
432 | local m,e,r,t,n,u,i
433 | m,e,r,t,u,i = string.find(s,self._DTD1,pos)
434 | if m then
435 | return m,e,{_root=r,_type=t,_uri=u,_internal=i}
436 | end
437 | m,e,r,t,n,u,i = string.find(s,self._DTD2,pos)
438 | if m then
439 | return m,e,{_root=r,_type=t,_name=n,_uri=u,_internal=i}
440 | end
441 | m,e,r,i = string.find(s,self._DTD3,pos)
442 | if m then
443 | return m,e,{_root=r,_internal=i}
444 | end
445 | m,e,r,t,u = string.find(s,self._DTD4,pos)
446 | if m then
447 | return m,e,{_root=r,_type=t,_uri=u}
448 | end
449 | m,e,r,t,n,u = string.find(s,self._DTD5,pos)
450 | if m then
451 | return m,e,{_root=r,_type=t,_name=n,_uri=u}
452 | end
453 | return nil
454 | end
455 |
456 | ---Parses a string representing a tag
457 | --@param s String containing tag text
458 | --@return Returns a string containing the tagname and a table attrs
459 | --containing the atributtes of tag
460 | obj._parseTag = function(self,s)
461 | local attrs = {}
462 | local tagname = string.gsub(s,self._TAG,'%1')
463 | string.gsub(s,self._ATTR1,function (k,v)
464 | attrs[string.lower(k)]=self:_parseEntities(v)
465 | attrs._ = 1
466 | end)
467 | string.gsub(s,self._ATTR2,function (k,v)
468 | attrs[string.lower(k)]=self:_parseEntities(v)
469 | attrs._ = 1
470 | end)
471 | if attrs._ then
472 | attrs._ = nil
473 | else
474 | attrs = nil
475 | end
476 | return tagname,attrs
477 | end
478 |
479 | return obj
480 |
481 | end
482 |
483 | return { xmlParser = xmlParser }
484 |
--------------------------------------------------------------------------------
/syncthing.koplugin/main.lua:
--------------------------------------------------------------------------------
1 | local DataStorage = require("datastorage")
2 | local Device = require("device")
3 | local Dispatcher = require("dispatcher")
4 | local InfoMessage = require("ui/widget/infomessage") -- luacheck:ignore
5 | local QRMessage = require("ui/widget/qrmessage")
6 | local InputDialog = require("ui/widget/inputdialog")
7 | local UIManager = require("ui/uimanager")
8 | local WidgetContainer = require("ui/widget/container/widgetcontainer")
9 | local ffiutil = require("ffi/util")
10 | local logger = require("logger")
11 | local util = require("util")
12 | local _ = require("gettext")
13 | local http = require("socket.http")
14 | local ltn12 = require("ltn12")
15 | local socket = require("socket")
16 | local socketutil = require("socketutil")
17 | local JSON = require("json")
18 | local Font = require("ui/font")
19 | local random = require("random")
20 | local T = ffiutil.template
21 |
22 | local path = DataStorage:getFullDataDir()
23 | if not util.pathExists("dropbear") then
24 | return { disabled = true, }
25 | end
26 |
27 | local Syncthing = WidgetContainer:extend{
28 | name = "Syncthing",
29 | is_doc_only = false,
30 | }
31 |
32 | local pid_path = "/tmp/syncthing_koreader.pid"
33 | local config_path = "settings/syncthing/config.xml"
34 | local device_id_path = "settings/syncthing/device-id"
35 |
36 | function Syncthing:init()
37 | self.syncthing_port = G_reader_settings:readSetting("syncthing_port") or "8384"
38 | self.ui.menu:registerToMainMenu(self)
39 | self:onDispatcherRegisterActions()
40 | end
41 |
42 | function Syncthing:start(password)
43 | if not password and not util.pathExists(config_path) then
44 | -- Use a random initial password to make sure GUI is inaccessible unless the
45 | -- user explicitly sets a password
46 | password = random.uuid()
47 | end
48 | local cmd = string.format("%s %s %s %s",
49 | "./plugins/syncthing.koplugin/start-syncthing",
50 | G_reader_settings:readSetting("home_dir"),
51 | self.syncthing_port,
52 | password or "")
53 |
54 | -- Start loopback interface so that we can access the Syncthing API later
55 | if Device:isKobo() then
56 | if os.execute("ifconfig lo up") ~= 0 then
57 | local info = InfoMessage:new{
58 | icon = "notice-warning",
59 | text = _("Failed to start Syncthing."),
60 | }
61 | UIManager:show(info)
62 | return
63 | end
64 | end
65 |
66 | -- Make a hole in the Kindle's firewall
67 | if Device:isKindle() then
68 | os.execute(string.format("%s %s %s",
69 | "iptables -A INPUT -p tcp --dport", self.syncthing_port,
70 | "-m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT"))
71 | os.execute(string.format("%s %s %s",
72 | "iptables -A OUTPUT -p tcp --sport", self.syncthing_port,
73 | "-m conntrack --ctstate ESTABLISHED -j ACCEPT"))
74 | os.execute("iptables -A INPUT -i wlan0 -p tcp --dport 22000 -j ACCEPT")
75 | os.execute("iptables -A INPUT -i wlan0 -p udp --dport 22000 -j ACCEPT")
76 | os.execute("iptables -A INPUT -i wlan0 -p udp --dport 21027 -j ACCEPT")
77 | end
78 |
79 | if not util.pathExists(path.."/settings/syncthing/") then
80 | os.execute("mkdir "..path.."/settings/syncthing")
81 | end
82 | logger.dbg("[Syncthing] Launching Syncthing : ", cmd)
83 | if os.execute(cmd) == 0 then
84 | local info = InfoMessage:new{
85 | timeout = 10,
86 | -- @translators: %1 is the Syncthing port, %2 is the network info.
87 | text = T(_("Syncthing started.\n\nSyncthing port: %1\n%2"),
88 | self.syncthing_port,
89 | Device.retrieveNetworkInfo and Device:retrieveNetworkInfo() or _("Could not retrieve network info.")),
90 | }
91 | UIManager:show(info)
92 | else
93 | local info = InfoMessage:new{
94 | icon = "notice-warning",
95 | text = _("Failed to start Syncthing."),
96 | }
97 | UIManager:show(info)
98 | end
99 | end
100 |
101 | function Syncthing:isRunning()
102 | return util.pathExists(pid_path)
103 | end
104 |
105 | function Syncthing:stop()
106 | os.execute("cat "..pid_path.." | xargs kill")
107 | UIManager:show(InfoMessage:new {
108 | text = T(_("Syncthing stopped.")),
109 | timeout = 2,
110 | })
111 |
112 | if self:isRunning() then
113 | os.remove(pid_path)
114 | end
115 |
116 | -- Plug the hole in the Kindle's firewall
117 | if Device:isKindle() then
118 | os.execute(string.format("%s %s %s",
119 | "iptables -D INPUT -p tcp --dport", self.syncthing_port,
120 | "-m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT"))
121 | os.execute(string.format("%s %s %s",
122 | "iptables -D OUTPUT -p tcp --sport", self.syncthing_port,
123 | "-m conntrack --ctstate ESTABLISHED -j ACCEPT"))
124 | os.execute("iptables -D INPUT -i wlan0 -p tcp --dport 22000 -j ACCEPT")
125 | os.execute("iptables -D INPUT -i wlan0 -p udp --dport 22000 -j ACCEPT")
126 | os.execute("iptables -D INPUT -i wlan0 -p udp --dport 21027 -j ACCEPT")
127 | end
128 | end
129 |
130 | function Syncthing:onToggleSyncthingServer()
131 | if self:isRunning() then
132 | self:stop()
133 | else
134 | self:start()
135 | end
136 | end
137 |
138 | function Syncthing:show_port_dialog(touchmenu_instance)
139 | self.port_dialog = InputDialog:new{
140 | title = _("Choose Syncthing port"),
141 | input = self.syncthing_port,
142 | input_type = "number",
143 | input_hint = self.syncthing_port,
144 | buttons = {
145 | {
146 | {
147 | text = _("Cancel"),
148 | id = "close",
149 | callback = function()
150 | UIManager:close(self.port_dialog)
151 | end,
152 | },
153 | {
154 | text = _("Save"),
155 | is_enter_default = true,
156 | callback = function()
157 | local value = tonumber(self.port_dialog:getInputText())
158 | if value and value >= 0 then
159 | self.syncthing_port = value
160 | G_reader_settings:saveSetting("syncthing_port", self.syncthing_port)
161 | UIManager:close(self.port_dialog)
162 | touchmenu_instance:updateItems()
163 | end
164 | end,
165 | },
166 | },
167 | },
168 | }
169 | UIManager:show(self.port_dialog)
170 | self.port_dialog:onShowKeyboard()
171 | end
172 |
173 | -- Function copied from newsdownloader.plugin
174 | function Syncthing:deserializeXMLString(xml_str)
175 | -- uses LuaXML https://github.com/manoelcampos/LuaXML
176 | -- The MIT License (MIT)
177 | -- Copyright (c) 2016 Manoel Campos da Silva Filho
178 | -- see: koreader/plugins/newsdownloader.koplugin/lib/LICENSE_LuaXML
179 | local treehdl = require("lib/handler")
180 | local libxml = require("lib/xml")
181 | -- Instantiate the object that parses the XML file as a Lua table.
182 | local xmlhandler = treehdl.simpleTreeHandler()
183 |
184 | -- Remove UTF-8 byte order mark, as it will cause LuaXML to fail
185 | xml_str = xml_str:gsub("^\xef\xbb\xbf", "", 1)
186 |
187 | -- Instantiate the object that parses the XML to a Lua table.
188 | local ok = pcall(function()
189 | libxml.xmlParser(xmlhandler):parse(xml_str)
190 | end)
191 | if not ok then return end
192 | return xmlhandler.root
193 | end
194 |
195 | function Syncthing:readConfig()
196 | local file = io.open(config_path, "r")
197 | if not file then return nil end
198 | local xml_str = file:read("a")
199 | file:close()
200 |
201 | return self:deserializeXMLString(xml_str)
202 | end
203 |
204 | function Syncthing:getDeviceId()
205 | local file = io.open(device_id_path, "r")
206 | if not file then return nil end
207 | local device_id = file:read("l")
208 | file:close()
209 |
210 | return device_id
211 | end
212 |
213 | function Syncthing:apiCall(api_path, method, source)
214 | local config = self:readConfig()
215 | if not config then
216 | error("Cannot extract API key")
217 | end
218 | local apiKey = config["configuration"]["gui"]["apikey"]
219 |
220 | if not method then
221 | method = "GET"
222 | end
223 |
224 | local url = string.format("http://127.0.0.1:%s/rest/%s", self.syncthing_port, api_path)
225 |
226 | logger.dbg("Syncthing: url:", url)
227 | local sink = {}
228 | socketutil:set_timeout(socketutil.LARGE_BLOCK_TIMEOUT, socketutil.LARGE_TOTAL_TIMEOUT)
229 | local code, headers, status = socket.skip(1, http.request({
230 | url = url,
231 | method = method,
232 | source = source,
233 | sink = ltn12.sink.table(sink),
234 | headers = {
235 | ["X-API-Key"] = apiKey,
236 | ["Content-Type"] = "application/json"
237 | }
238 | }))
239 | socketutil:reset_timeout()
240 |
241 | if code ~= 200 then
242 | logger.dbg("Syncthing: HTTP response code <> 200. Response status:", status or code)
243 | logger.dbg("Syncthing: Response headers:", headers)
244 | local info = InfoMessage:new{
245 | icon = "notice-warning",
246 | text = T(_("Syncthing error (%1)"), status or code),
247 | }
248 | UIManager:show(info)
249 | return nil
250 | end
251 | local str = table.concat(sink)
252 | local ok, result = pcall(JSON.decode, str)
253 | if not ok then
254 | return nil
255 | else
256 | return result
257 | end
258 | end
259 |
260 | function Syncthing:getStatusMenu()
261 | local config = self:apiCall("config") or {}
262 | local connections = self:apiCall("system/connections") or {}
263 | local device_stats = self:apiCall("stats/device") or {}
264 | local folder_stats = self:apiCall("stats/folder") or {}
265 |
266 | local function getDeviceName(device_id)
267 | for __, device in pairs(config["devices"] or {}) do
268 | if device["deviceID"] == device_id then
269 | return device["name"]
270 | end
271 | end
272 | return ""
273 | end
274 |
275 | local sub_item_table = {}
276 |
277 | table.insert(sub_item_table, {
278 | text = _("Folders"),
279 | enabled_func = function() return false end
280 | })
281 |
282 | for __, folder in pairs(config["folders"] or {}) do
283 | local status = self:apiCall(string.format("db/status?folder=%s", folder["id"])) or {}
284 | local stat = folder_stats[folder["id"]] or {}
285 |
286 | local state = status["state"]
287 | if state == "idle" then
288 | state = _("up to date")
289 | end
290 |
291 | local devices = {}
292 | for ___, device in pairs(folder["devices"]) do
293 | table.insert(devices, "- "..getDeviceName(device["deviceID"]))
294 | end
295 |
296 | table.insert(sub_item_table, {
297 | text = T("%1: %2", folder["label"], state),
298 | keep_menu_open = true,
299 | callback = function()
300 | local info = InfoMessage:new{
301 | face = Font:getFace("x_smallinfofont"),
302 | text = T(_("Folder ID: %1\nPath: %2\nErrors: %3\nLocal total items: %4\nNeed items: %5\nNeed bytes: %6\nLast scan: %7\nLast file: %8\nLast file at: %9\nDevices:\n%10"),
303 | folder["id"],
304 | folder["path"],
305 | status["errors"] or _("N/A"),
306 | status["localTotalItems"] or _("N/A"),
307 | status["needTotalItems"] or _("N/A"),
308 | status["needBytes"] or _("N/A"),
309 | stat["lastScan"] or _("N/A"),
310 | stat["lastFile"] and stat["lastFile"]["filename"] or _("N/A"),
311 | stat["lastFile"] and stat["lastFile"]["at"] or _("N/A"),
312 | table.concat(devices, "\n")),
313 | }
314 | UIManager:show(info)
315 | end
316 | })
317 | end
318 |
319 | sub_item_table[#sub_item_table].separator = true
320 |
321 | table.insert(sub_item_table, {
322 | text = _("Remote Devices"),
323 | enabled_func = function() return false end
324 | })
325 |
326 | for device_id, connection in pairs(connections["connections"] or {}) do
327 | local completion = self:apiCall(string.format("db/completion?device=%s", device_id)) or {}
328 | local percentage = (completion["completion"] and math.floor(completion["completion"]) or "").."%"
329 |
330 | local status
331 | if connection["connected"] then
332 | status = _("Connected")
333 | else
334 | local stat = device_stats[device_id] or {}
335 | status = T(_("Last seen %1"), string.sub(stat["lastSeen"] or "", 1, 16)) -- YYYY-MM-DDTHH:MM
336 | end
337 |
338 | table.insert(sub_item_table, {
339 | text = T("%1: %2, %3",
340 | getDeviceName(device_id),
341 | status,
342 | percentage),
343 | keep_menu_open = true,
344 | callback = function()
345 | local info = InfoMessage:new{
346 | face = Font:getFace("x_smallinfofont"),
347 | text = T(_("Device ID: %1\nAddress: %2\nConnected since: %3\nPaused: %4\nNeed items: %5\nNeed bytes: %6"),
348 | device_id,
349 | connection["connected"] and connection["address"] or _("N/A"),
350 | connection["connected"] and connection["startedAt"] or _("N/A"),
351 | connection["paused"] and _("Yes") or _("No"),
352 | completion["need_items"] or _("N/A"),
353 | completion["need_bytes"] or _("N/A")),
354 | }
355 | UIManager:show(info)
356 | end
357 | })
358 | end
359 |
360 | return sub_item_table
361 | end
362 |
363 | function Syncthing:getPendingMenu()
364 | local devices = self:apiCall("cluster/pending/devices") or {}
365 | local folders = self:apiCall("cluster/pending/folders") or {}
366 |
367 | local sub_item_table = {}
368 |
369 | table.insert(sub_item_table, {
370 | text = #devices and _("Pending Devices") or _("No Pending Devices"),
371 | enabled_func = function() return false end
372 | })
373 |
374 | for device_id, device in pairs(devices) do
375 | table.insert(sub_item_table, {
376 | text = T("%1 (%2)", device["name"], device_id),
377 | callback = function()
378 | local dialog
379 | dialog = InputDialog:new{
380 | title = T(_("Add Device\n%1?"), device_id),
381 | input = device["name"],
382 | input_type = "string",
383 | buttons = {
384 | {
385 | {
386 | text = _("Cancel"),
387 | id = "close",
388 | callback = function()
389 | UIManager:close(dialog)
390 | end,
391 | },
392 | {
393 | text = _("Add"),
394 | is_enter_default = true,
395 | callback = function()
396 | local body = ltn12.source.string(JSON.encode({
397 | deviceID = device_id,
398 | name = dialog:getInputText(),
399 | _editing = "new-pending"
400 | }))
401 | self:apiCall("config/devices", "POST", body)
402 |
403 | UIManager:close(dialog)
404 | end,
405 | },
406 | },
407 | },
408 | }
409 | UIManager:show(dialog)
410 | end
411 | })
412 | end
413 |
414 | sub_item_table[#sub_item_table].separator = true
415 |
416 | table.insert(sub_item_table, {
417 | text = #folders and _("Pending Folders") or _("No Pending Folders"),
418 | enabled_func = function() return false end
419 | })
420 |
421 | for folder_id, offerers in pairs(folders) do
422 | local offerer, folder = pairs(offerers["offeredBy"])(offerers["offeredBy"])
423 | table.insert(sub_item_table, {
424 | text = T("%1 (From %2)", folder["label"], offerer),
425 | callback = function()
426 | local dialog
427 | dialog = InputDialog:new{
428 | title = T(_("Add Folder %1?"), folder["label"]),
429 | input = string.format("%s/%s",
430 | G_reader_settings:readSetting("home_dir"),
431 | folder["label"]),
432 | input_type = "string",
433 | buttons = {
434 | {
435 | {
436 | text = _("Cancel"),
437 | id = "close",
438 | callback = function()
439 | UIManager:close(dialog)
440 | end,
441 | },
442 | {
443 | text = _("Add"),
444 | is_enter_default = true,
445 | callback = function()
446 | local body = ltn12.source.string(JSON.encode({
447 | id = folder_id,
448 | label = folder["label"],
449 | filesystemType = "basic",
450 | path = dialog:getInputText(),
451 | type = "sendreceive",
452 | devices = {
453 | {
454 | deviceID = self:getDeviceId(),
455 | introducedBy = ""
456 | },
457 | {
458 | deviceID = offerer
459 | }
460 | },
461 | _editing = "new-pending"
462 | }))
463 | self:apiCall("config/folders", "POST", body)
464 |
465 | UIManager:close(dialog)
466 | end,
467 | },
468 | },
469 | },
470 | }
471 | UIManager:show(dialog)
472 | end
473 | })
474 | end
475 |
476 | return sub_item_table
477 | end
478 |
479 | function Syncthing:addToMainMenu(menu_items)
480 | menu_items.syncthing = {
481 | text = _("Syncthing"),
482 | sub_item_table = {
483 | {
484 | text = _("Syncthing"),
485 | keep_menu_open = true,
486 | checked_func = function() return self:isRunning() end,
487 | callback = function(touchmenu_instance)
488 | self:onToggleSyncthingServer()
489 | touchmenu_instance:updateItems()
490 | end,
491 | },
492 | {
493 | text_func = function()
494 | return T(_("Syncthing Port: %1"), self.syncthing_port)
495 | end,
496 | keep_menu_open = true,
497 | enabled_func = function() return not self:isRunning() end,
498 | callback = function(touchmenu_instance)
499 | self:show_port_dialog(touchmenu_instance)
500 | end,
501 | },
502 | {
503 | text = _("Syncthing Web GUI"),
504 | keep_menu_open = true,
505 | enabled_func = function() return self:isRunning() end,
506 | callback = function()
507 | local info = InfoMessage:new{
508 | timeout = 60,
509 | text = T(_("Connect to port %1 for web GUI\nYou must set a password first! Default username: syncthing\n\n%2"),
510 | self.syncthing_port,
511 | Device.retrieveNetworkInfo and Device:retrieveNetworkInfo() or _("Could not retrieve network info.")),
512 | }
513 | UIManager:show(info)
514 | end,
515 | },
516 | {
517 | text = _("Set GUI Password"),
518 | keep_menu_open = true,
519 | enabled_func = function() return not self:isRunning() end,
520 | separator = true,
521 | callback = function(touchmenu_instance)
522 | local dialog
523 | dialog = InputDialog:new{
524 | title = _("Set GUI Password"),
525 | input = "",
526 | text_type = "password",
527 | buttons = {
528 | {
529 | {
530 | text = _("Cancel"),
531 | id = "close",
532 | callback = function()
533 | UIManager:close(dialog)
534 | end,
535 | },
536 | {
537 | text = _("Set"),
538 | is_enter_default = true,
539 | callback = function()
540 | if not dialog:getInputText() then
541 | return
542 | end
543 | self:start(dialog:getInputText())
544 | touchmenu_instance:updateItems()
545 |
546 | UIManager:close(dialog)
547 | end,
548 | },
549 | },
550 | },
551 | }
552 | UIManager:show(dialog)
553 | end,
554 | },
555 | {
556 | text_func = function()
557 | local device_id = self:getDeviceId()
558 | return T(_("Device ID: %1"), device_id or "Unknown")
559 | end,
560 | keep_menu_open = true,
561 | callback = function()
562 | local device_id = self:getDeviceId()
563 |
564 | local info = InfoMessage:new{
565 | timeout = 60,
566 | text = device_id or "Unknown"
567 | }
568 | UIManager:show(info)
569 | end,
570 | },
571 | {
572 | text = _("Show QR Code"),
573 | keep_menu_open = true,
574 | callback = function()
575 | local device_id = self:getDeviceId()
576 |
577 | if device_id then
578 | local info = QRMessage:new{
579 | text = device_id,
580 | width = Device.screen:getWidth(),
581 | height = Device.screen:getHeight()
582 | }
583 | UIManager:show(info)
584 | end
585 | end,
586 | },
587 | {
588 | text = _("Status"),
589 | keep_menu_open = true,
590 | enabled_func = function() return self:isRunning() end,
591 | sub_item_table_func = function()
592 | return self:getStatusMenu()
593 | end,
594 | },
595 | {
596 | text = _("Pending"),
597 | keep_menu_open = true,
598 | enabled_func = function() return self:isRunning() end,
599 | sub_item_table_func = function()
600 | return self:getPendingMenu()
601 | end,
602 | },
603 | }
604 | }
605 | end
606 |
607 | function Syncthing:onDispatcherRegisterActions()
608 | Dispatcher:registerAction("toggle_syncthing_server", { category = "none", event = "ToggleSyncthingServer", title = _("Toggle Syncthing"), general=true})
609 | end
610 |
611 | require("insert_menu")
612 |
613 | return Syncthing
614 |
--------------------------------------------------------------------------------
/syncthing.koplugin/start-syncthing:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | set -e
3 |
4 | # Save config and data under the KOReader runtime directory
5 | config_dir=settings/syncthing
6 | syncthing=plugins/syncthing.koplugin/syncthing
7 | pid_file=/tmp/syncthing_koreader.pid
8 |
9 | if [ -n "$1" ]; then
10 | home_dir=$1
11 | else
12 | home_dir=/
13 | fi
14 |
15 |
16 | if [ -n "$2" ]; then
17 | port=$2
18 | else
19 | port=8384
20 | fi
21 |
22 | if [ -n "$3" ]; then
23 | password=$3
24 | fi
25 |
26 | if [ ! -f "$config_dir/config.xml" ] || [ -n "$password" ]; then
27 | echo "Generating Syncthing configuration..."
28 | # Set HOME so that the default folder is created at $home_dir/Sync
29 | HOME=$home_dir "$syncthing" generate \
30 | --config="$config_dir" \
31 | --gui-user=syncthing \
32 | --gui-password="$password" \
33 | --skip-port-probing # Need this due to lack of IPv4 loopback in Kobo
34 | fi
35 |
36 | if [ ! -f "$config_dir/device-id" ]; then
37 | # Save the device ID to a file for easy access from KOReader
38 | "$syncthing" \
39 | --config="$config_dir" \
40 | --data="$config_dir" \
41 | --device-id > "$config_dir/device-id"
42 | fi
43 |
44 | # We need to listen to 0.0.0.0 so that the GUI is accessible over the network
45 | "$syncthing" serve \
46 | --config="$config_dir" \
47 | --data="$config_dir" \
48 | --gui-address=http://0.0.0.0:$port \
49 | --logfile="$config_dir/logs" \
50 | --log-max-old-files=10 \
51 | --log-max-size=1048576 &
52 |
53 | # Write the PID to be used for stopping Syncthing later
54 | echo $! > "$pid_file"
55 |
--------------------------------------------------------------------------------
/syncthing.koplugin/syncthing:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonchoimtt/koreader-syncthing/2e2827f1bb381af6db7af249d352e3b5133fc61c/syncthing.koplugin/syncthing
--------------------------------------------------------------------------------