├── .github
└── workflows
│ └── makefile.yml
├── .gitignore
├── COPYING
├── Makefile
├── README.md
├── SECURITY.md
├── colors
├── colors.go
└── conv.go
├── contrib
├── 0001-Remove-podcast-bulk-downloading-from-library.patch
├── README
└── lqueue
├── data
├── cache-db.go
├── cache.go
├── data.go
├── db.go
├── download.go
├── escape
│ ├── escape.go
│ └── escape_test.go
└── queue.go
├── event
├── event.go
└── handle.go
├── go.mod
├── go.sum
├── main.go
├── podbit.1
├── sound
├── queue.go
└── sound.go
├── ss.png
├── ui
├── components
│ ├── doc.go
│ ├── list.go
│ ├── menu.go
│ └── table.go
├── download.go
├── input.go
├── library.go
├── player.go
├── queue.go
├── tray.go
└── ui.go
└── ver.go
/.github/workflows/makefile.yml:
--------------------------------------------------------------------------------
1 | name: Makefile CI
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v2
16 | - uses: actions/setup-go@v3
17 | with:
18 | go-version: '>=1.18.0'
19 |
20 | - name: build
21 | run: make
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | podbit
2 | private/
3 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | EXE = podbit
2 |
3 | UISRC = ui/ui.go ui/input.go colors/colors.go ui/library.go ui/player.go ui/queue.go ui/download.go ui/tray.go
4 | UICOMPS = ui/components/menu.go ui/components/table.go ui/components/list.go
5 | SOUNDSRC = sound/sound.go sound/queue.go
6 | DATASRC = data/data.go data/queue.go data/db.go data/cache.go data/download.go
7 | EVNTSRC = event/event.go event/handle.go
8 | SRC = main.go ver.go ${INPUTSRC} ${UISRC} ${DATASRC} ${EVNTSRC} ${UICOMPS} ${SOUNDSRC}
9 |
10 | ifndef PREFIX
11 | PREFIX = /usr/local
12 | endif
13 | ifndef MANPREFIX
14 | MANPREFIX = /usr/local/share/man
15 | endif
16 |
17 | ${EXE}: ${SRC}
18 | CGO_LDFLAGS_ALLOW=".*" go build
19 |
20 | check:
21 | CGO_LDFLAGS_ALLOW=".*" go run -race . 2>race.log
22 | clean:
23 | go clean
24 |
25 | install: ${EXE}
26 | mkdir -p ${DESTDIR}${PREFIX}/bin
27 | mkdir -p ${DESTDIR}${MANPREFIX}/man1
28 |
29 | cp -f ${EXE} ${DESTDIR}${PREFIX}/bin/
30 | chmod 755 ${DESTDIR}${PREFIX}/bin/${EXE}
31 |
32 | cp -f ${EXE}.1 ${DESTDIR}${MANPREFIX}/man1/podbit.1
33 |
34 | uninstall:
35 | rm -f ${DESTDIR}${PREFIX}/bin/${EXE} \
36 | ${DESTDIR}${MANPREFIX}/man1/podbit.1
37 |
38 | .PHONY: check clean install uninstall
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Podbit - **Podboat Improved**
2 |
3 | 
4 |
5 | [](https://aur.archlinux.org/packages/podbit/)
6 | [](https://github.com/ejv2/podbit/actions/workflows/makefile.yml)
7 | [](https://goreportcard.com/report/github.com/ethanv2/podbit)
8 |
9 | Podbit is a replacement for ``newsboat``'s standard podboat tool for listening to podcasts. It is minimal, performant and tries to focus just on being a podcast client, rather than an RSS reader. Podbit has an ncurses terminal user interface and vi-like keybindings.
10 |
11 | Podbit runs on Linux and the BSDs.
12 |
13 | ## Features
14 |
15 | * Reads the standard ``newsboat`` queue file to integrate seamlessly
16 | * Automatic podcast downloading, including in parallel
17 | * Podcast playing using ``mpv``
18 | * Podcast caching and automatic deletion once finished
19 | * Vi-like "hjkl" to navigate the interface
20 |
21 | ## Requirements
22 |
23 | Podbit is written in Go. So, to build, you will need a copy of the Go command line tool. In addition, you will need:
24 |
25 | * *ncurses* development libraries and headers, including wide character support (*libncusesw*)
26 | * A normal install of ``mpv``
27 | * A copy of GNU Make
28 | * Newsboat to enqueue podcasts - *(optional)*
29 | * A YouTube downloader tool, such as ``youtube-dl`` or ``yt-dlp``, to download YouTube podcasts - *(optional)*
30 |
31 | Because of security issues in the Go tool, the provided Makefile must be used instead of simply ``go build``.
32 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Podbit runs on rolling release. You should always be using the lastest version, if possible. Minor and patch releases will mostly be used to roll out security fixes, so it is worth upgrading to them.
6 |
7 | ## Reporting a Vulnerability
8 |
9 | Plesae **do not** report security issues on the public issue tracker. Email them to the committer email of an appropriate maintainer.
10 | This will most likely be
11 |
--------------------------------------------------------------------------------
/colors/colors.go:
--------------------------------------------------------------------------------
1 | package colors
2 |
3 | import (
4 | "github.com/vit1251/go-ncursesw"
5 | )
6 |
7 | // Color pair ID definitions.
8 | const (
9 | ColorRed = iota + 1
10 | ColorGreen
11 | ColorYellow
12 | ColorBlue
13 | ColorMagenta
14 | ColorCyan
15 |
16 | BackgroundRed
17 | BackgroundGreen
18 | BackgroundYellow
19 | BackgroundBlue
20 | BackgroundMagenta
21 | BackgroundCyan
22 | )
23 |
24 | // CreateColors initialises all colors for ncurses usage.
25 | // Should be called only once per application run.
26 | func CreateColors() {
27 | goncurses.InitPair(ColorRed, goncurses.C_RED, goncurses.C_BLACK)
28 | goncurses.InitPair(ColorGreen, goncurses.C_GREEN, goncurses.C_BLACK)
29 | goncurses.InitPair(ColorYellow, goncurses.C_YELLOW, goncurses.C_BLACK)
30 | goncurses.InitPair(ColorBlue, goncurses.C_BLUE, goncurses.C_BLACK)
31 | goncurses.InitPair(ColorMagenta, goncurses.C_MAGENTA, goncurses.C_BLACK)
32 | goncurses.InitPair(ColorCyan, goncurses.C_CYAN, goncurses.C_BLACK)
33 |
34 | goncurses.InitPair(BackgroundRed, goncurses.C_BLACK, goncurses.C_RED)
35 | goncurses.InitPair(BackgroundGreen, goncurses.C_BLACK, goncurses.C_GREEN)
36 | goncurses.InitPair(BackgroundYellow, goncurses.C_BLACK, goncurses.C_YELLOW)
37 | goncurses.InitPair(BackgroundBlue, goncurses.C_BLACK, goncurses.C_BLUE)
38 | goncurses.InitPair(BackgroundMagenta, goncurses.C_BLACK, goncurses.C_MAGENTA)
39 | goncurses.InitPair(BackgroundCyan, goncurses.C_BLACK, goncurses.C_CYAN)
40 | }
41 |
--------------------------------------------------------------------------------
/colors/conv.go:
--------------------------------------------------------------------------------
1 | package colors
2 |
3 | const (
4 | // Smallest iota color value (practically always 1).
5 | colorMin = ColorRed
6 | // Largest iota color value.
7 | colorMax = BackgroundCyan
8 | // Distance between a foreground color and a background color.
9 | colorBoundary = colorMax / 2
10 | )
11 |
12 | // ToForeground returns the passed color converted such that a background color
13 | // is its foreground equivalent.
14 | func ToForeground(color int16) int16 {
15 | if color <= colorBoundary {
16 | return color
17 | }
18 |
19 | return color - colorBoundary
20 | }
21 |
22 | // ToForeground returns the passed color converted such that a foreground color
23 | // is its background equivalent.
24 | func ToBackground(color int16) int16 {
25 | if color > colorBoundary {
26 | return color
27 | }
28 |
29 | return color + colorBoundary
30 | }
31 |
--------------------------------------------------------------------------------
/contrib/0001-Remove-podcast-bulk-downloading-from-library.patch:
--------------------------------------------------------------------------------
1 | From 720e7f6aba895992f751aee6164af5449276fadc Mon Sep 17 00:00:00 2001
2 | From: Ethan Marshall
3 | Date: Fri, 21 Jul 2023 15:31:27 +0100
4 | Subject: [PATCH] Remove podcast bulk downloading from library
5 |
6 | I find this feature annoying and not particularly useful, so I provide
7 | this patch in case anybody else uses podbit in the same way I do and
8 | gets annoyed when they waste multiple GB of data on a podcast they will
9 | never re-listen to.
10 | ---
11 | ui/library.go | 47 ++++++++++++-----------------------------------
12 | 1 file changed, 12 insertions(+), 35 deletions(-)
13 |
14 | diff --git a/ui/library.go b/ui/library.go
15 | index a59a95f..45b4f94 100644
16 | --- a/ui/library.go
17 | +++ b/ui/library.go
18 | @@ -144,48 +144,25 @@ func (l *Library) StartDownload() {
19 | return
20 | }
21 |
22 | - defer func() {
23 | - // Move cursor down
24 | - l.men[l.menSel].MoveSelection(1)
25 | - }()
26 | -
27 | - targets := l.men[1].Items
28 | - if l.menSel == 1 {
29 | - _, target := l.men[1].GetSelection()
30 | - item := data.Q.GetEpisodeByURL(target)
31 | -
32 | - if item == nil {
33 | - return
34 | - }
35 | -
36 | - if y, _ := data.Downloads.IsDownloading(item.Path); y {
37 | - go StatusMessage("Episode already downloading")
38 | - return
39 | - }
40 | -
41 | - data.Downloads.Download(item)
42 | - go StatusMessage(fmt.Sprintf("Download of %s started...", item.URL))
43 | -
44 | + if l.menSel != 1 {
45 | return
46 | }
47 |
48 | - for _, elem := range targets {
49 | - if data.IsURL(elem) {
50 | - item := data.Q.GetEpisodeByURL(elem)
51 | - if item == nil {
52 | - continue
53 | - }
54 | + _, target := l.men[1].GetSelection()
55 | + item := data.Q.GetEpisodeByURL(target)
56 |
57 | - if y, _ := data.Downloads.IsDownloading(item.Path); y {
58 | - go StatusMessage("Episode already downloading")
59 | - return
60 | - }
61 | + if item == nil {
62 | + return
63 | + }
64 |
65 | - go data.Downloads.Download(item)
66 | - }
67 | + if y, _ := data.Downloads.IsDownloading(item.Path); y {
68 | + go StatusMessage("Episode already downloading")
69 | + return
70 | }
71 |
72 | - go StatusMessage("Download of multiple episodes started...")
73 | + data.Downloads.Download(item)
74 | + go StatusMessage(fmt.Sprintf("Download of %s started...", item.URL))
75 | + l.men[l.menSel].MoveSelection(1)
76 | }
77 |
78 | // StartPlaying begins playing the currently focused element.
79 | --
80 | 2.41.0
81 |
82 |
--------------------------------------------------------------------------------
/contrib/README:
--------------------------------------------------------------------------------
1 | contrib - community and user contributed stuff
2 | ----------------------------------------------
3 |
4 | The contents of this directory are optional extras which can be used alongside
5 | podbit. These are intended for use by the end user and are not used as part of
6 | the main program.
7 |
8 | Patches in this directory are intended to be applied by the end user to modify
9 | the behavior of the program or to add extra ones. They may be applied using the
10 | standard UNIX patch command:
11 |
12 | patch -p1
13 |
14 | or using `git am`:
15 |
16 | git am patches/
17 |
18 | In the latter case, a new commit is automatically added into your working tree
19 | which may make forks easier to maintain. Please remember to revert these when
20 | contributing!
21 |
22 | Scripts in this directory are useful macros and automation scripts which can
23 | make using podbit alongside newsboat a little easier.
24 |
--------------------------------------------------------------------------------
/contrib/lqueue:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # lqueue - enqueue a YTDL link to the podbit queue file
3 | # Copyright (C) 2024 - Ethan Marshall
4 | #
5 | # Usage: lqueue
6 | #
7 | # The base path defaults to ~/Downloads/Podcasts, but can be overriden
8 | # with the environment variable $PODBIT_DOWNLOAD_PATH.
9 | #
10 | # The URL is enqueued with a leading '+' (plus) sign, which instructs
11 | # podbit to download the URL using the best available YTDL tool (ytdl,
12 | # yt-dlp, etc.). If you do not need this, you can just append the file
13 | # using the standard newsboat enqueue command.
14 | #
15 | # You can create a bind to enqueue YouTube links from newsboat with this
16 | # script. For instance, the below enqueues using lquque when ",q" is pressed:
17 | # macro q set browser "lqueue %u" ; open-in-browser ; set browser " %u"
18 | # Replace with the name of your browser (firefox, chromium etc.)
19 |
20 | DLPATH=${PODBIT_DOWNLOAD_PATH:-$HOME/Downloads/Podcasts}
21 | echo "+$1 \"$DLPATH/$(basename $1)\"" >> $XDG_DATA_HOME/newsboat/queue
22 |
--------------------------------------------------------------------------------
/data/cache-db.go:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "bufio"
5 | "errors"
6 | "os"
7 | "path/filepath"
8 | "strconv"
9 | "strings"
10 | "sync"
11 | "time"
12 | )
13 |
14 | const (
15 | CacheDBFilename = "cache.db"
16 | CacheDBComment = `# This is the podbit cache.db file
17 | # It contains the last consumption time for the listed media to allow for cache cleanouts
18 | # Do not modify by hand`
19 | )
20 |
21 | var (
22 | ErrDBIO = errors.New("Error: IO error while reading from cache.db")
23 | ErrDBIOW = errors.New("Error: IO error while writing to cache.db")
24 | ErrDBSyntax = errors.New("Error: Syntax error in cache.db")
25 | ErrDBExists = errors.New("entry alredy exists")
26 | ErrDBEnoent = errors.New("no such entry in cache.db")
27 | ErrDBPruned = errors.New("entry has been marked for pruning")
28 | )
29 |
30 | // CacheSyntaxError is a syntax error which contains a line reference.
31 | type CacheSyntaxError struct {
32 | Line uint
33 | Comment string
34 | }
35 |
36 | func (c CacheSyntaxError) Error() string {
37 | return ErrDBSyntax.Error() + ": line " + strconv.FormatUint(uint64(c.Line), 10) + ": " + c.Comment
38 | }
39 |
40 | func (c CacheSyntaxError) Unwrap() error {
41 | return ErrDBSyntax
42 | }
43 |
44 | // A CacheEntry is a single entry in the db map contained within a CacheDB. It
45 | // is made up of a resume timecode and a last played/finished timestamp.
46 | type CacheEntry struct {
47 | // unix epoch time of an entry
48 | // set to <0 to indicate pruned entry
49 | finished int64
50 | // number of seconds in to the media file which we should resume at
51 | // if zero, start from the beginning (obviously!), but also is excluded
52 | // from the cache.db file
53 | resume uint64
54 | }
55 |
56 | // The CacheDB contains the timestamps which specify when media was last played
57 | // or finished. This is used to avoid the media downloads directory becoming
58 | // bigger and bigger as more and more podcasts are downloaded.
59 | //
60 | // The format for the CacheDB is simply the download filepath followed by the
61 | // timestamp which would have been stored after the last field in the queue
62 | // file. The timestamp is simply a 64-bit unix timestamp, however negative
63 | // values are interpreted as pruned items (i.e items cleaned via cache cleanup)
64 | // and will be excluded from deserialization. I doubt that anybody will have
65 | // listen times in the 1960s.
66 | //
67 | // The cache.db is assumed to be under the exclusive control of podbit and as
68 | // such is not reloaded during operation and may only be
69 | // serialized/deserialized at program entry and exit.
70 | //
71 | // Prior to Podbit v4.0, this was an extra field on the queue file, which broke
72 | // compatibility with podboat, which is obviously undesirable.
73 | type CacheDB struct {
74 | mut *sync.RWMutex
75 | // db maps episode paths to timestamps
76 | db map[string]CacheEntry
77 | }
78 |
79 | func NewCacheDB() *CacheDB {
80 | return &CacheDB{
81 | new(sync.RWMutex),
82 | make(map[string]CacheEntry),
83 | }
84 | }
85 |
86 | func (c *CacheDB) Open() error {
87 | data := os.Getenv("XDG_DATA_HOME")
88 | path := filepath.Join(data, DatabaseDirname, CacheDBFilename)
89 |
90 | f, err := os.Open(path)
91 | if err != nil {
92 | fo, err := os.Create(path)
93 | if err != nil {
94 | return err
95 | }
96 |
97 | fo.WriteString(CacheDBComment)
98 | fo.Close()
99 | return nil
100 | }
101 |
102 | defer f.Close()
103 |
104 | scanner := bufio.NewScanner(f)
105 | scanner.Split(bufio.ScanLines)
106 |
107 | i := uint(1)
108 | for scanner.Scan() {
109 | if scanner.Err() != nil {
110 | return ErrDBIO
111 | }
112 |
113 | elem := scanner.Text()
114 | // Ignore comments and blank lines
115 | if len(elem) == 0 || strings.HasPrefix(elem, "#") {
116 | continue
117 | }
118 |
119 | fields := strings.Fields(elem)
120 |
121 | if len(fields) < 2 {
122 | return CacheSyntaxError{i, "insufficient fields (expect 2/3)"}
123 | }
124 |
125 | stamp, err := strconv.ParseInt(fields[1], 10, 64)
126 | if err != nil {
127 | return CacheSyntaxError{i, "parsing timestamp: " + err.Error()}
128 | }
129 |
130 | resume := uint64(0)
131 | if len(fields) == 3 {
132 | r, err := strconv.ParseUint(fields[2], 10, 64)
133 | if err != nil {
134 | return CacheSyntaxError{i, "parsing resume timecode: " + err.Error()}
135 | }
136 |
137 | resume = r
138 | }
139 |
140 | // If we have duplicates somehow take the later stamp.
141 | s, ok := c.db[fields[0]]
142 | if ok {
143 | if s.finished >= stamp {
144 | continue
145 | }
146 | }
147 | c.db[fields[0]] = CacheEntry{stamp, resume}
148 |
149 | i++
150 | }
151 |
152 | return nil
153 | }
154 |
155 | // Save truncates the cache.db to zero bytes before zerializing the in-memory
156 | // database to the file in the accepted format.
157 | func (c *CacheDB) Save() error {
158 | data := os.Getenv("XDG_DATA_HOME")
159 | path := filepath.Join(data, DatabaseDirname, CacheDBFilename)
160 |
161 | f, err := os.Create(path)
162 | if err != nil {
163 | return ErrDBIOW
164 | }
165 | defer f.Close()
166 |
167 | f.WriteString(CacheDBComment + "\n\n")
168 |
169 | c.mut.RLock()
170 | defer c.mut.RUnlock()
171 |
172 | for url, ts := range c.db {
173 | // Pruned entries
174 | if ts.finished < 0 {
175 | continue
176 | }
177 |
178 | sts := strconv.FormatInt(ts.finished, 10)
179 | res := strconv.FormatUint(ts.resume, 10)
180 |
181 | if ts.resume != 0 {
182 | f.WriteString(url + " " + sts + " " + res + "\n")
183 | continue
184 | }
185 | f.WriteString(url + " " + sts + "\n")
186 | }
187 |
188 | return nil
189 | }
190 |
191 | // Touch updates the listen time for an episode to the current timestamp. This
192 | // method refuses to update the timestamp for any file which does not exist, so
193 | // this should be checked first.
194 | func (c *CacheDB) Touch(path string) error {
195 | // Refuse to touch a non existent path
196 | _, err := os.Stat(path)
197 | if err != nil {
198 | return err
199 | }
200 |
201 | c.mut.Lock()
202 | defer c.mut.Unlock()
203 |
204 | c.db[path] = CacheEntry{time.Now().Unix(), 0}
205 | return nil
206 | }
207 |
208 | // Resume is like Touch, except it sets the resume timecode to the given value.
209 | // Normal touches implicitly reset the resume timecode back to zero, so ensure
210 | // that this is called after any touch calls, if they should be made.
211 | func (c *CacheDB) Resume(path string, rt uint64) error {
212 | // Refuse to touch a non existent path
213 | _, err := os.Stat(path)
214 | if err != nil {
215 | return err
216 | }
217 |
218 | c.mut.Lock()
219 | defer c.mut.Unlock()
220 |
221 | orig := c.db[path]
222 | c.db[path] = CacheEntry{orig.finished, rt}
223 | return nil
224 | }
225 |
226 | // Insert inserts a new path with the given timestamp into the map. Panics if
227 | // ts < 0.
228 | func (c *CacheDB) Insert(path string, ts int64) error {
229 | if ts < 0 {
230 | panic("invalid timestamp (<0): cannot insert pruned item")
231 | }
232 |
233 | c.mut.Lock()
234 | defer c.mut.Unlock()
235 |
236 | _, ok := c.db[path]
237 | if ok {
238 | return ErrDBExists
239 | }
240 |
241 | c.db[path] = CacheEntry{ts, 0}
242 | return nil
243 | }
244 |
245 | // Prune marks an entry as having been pruned, which excludes it from being
246 | // saved at the next cache.db save.
247 | func (c *CacheDB) Prune(path string) error {
248 | c.mut.Lock()
249 | defer c.mut.Unlock()
250 |
251 | s, ok := c.db[path]
252 | if !ok {
253 | return ErrDBEnoent
254 | }
255 |
256 | // Refuse to prune more than once - obviously erroneous
257 | if s.finished < 0 {
258 | return ErrDBPruned
259 | }
260 |
261 | // Mark as pruned with negative timestamp
262 | c.db[path] = CacheEntry{-1, 0}
263 | return nil
264 | }
265 |
266 | // RawStat returns the currently recorded raw timestamp for an entry. This can
267 | // fail if an entry does not exist, or if the entry was marked for pruning.
268 | func (c *CacheDB) RawStat(path string) (*int64, *uint64, error) {
269 | c.mut.RLock()
270 | defer c.mut.RUnlock()
271 |
272 | s, ok := c.db[path]
273 | if !ok {
274 | return nil, nil, ErrDBEnoent
275 | }
276 |
277 | if s.finished < 0 {
278 | return nil, nil, ErrDBPruned
279 | }
280 |
281 | return &s.finished, &s.resume, nil
282 | }
283 |
284 | // Stat returns the currently recorded timestamp for an entry. This can fail if
285 | // an entry does not exist, or if the entry was marked for pruning.
286 | func (c *CacheDB) Stat(path string) (*time.Time, *uint64, error) {
287 | s, r, err := c.RawStat(path)
288 | if err != nil {
289 | return nil, nil, err
290 | }
291 |
292 | if s == nil {
293 | panic("incorrect rawstat: stamp ptr and err should never both be nil")
294 | }
295 |
296 | t := time.Unix(*s, 0)
297 | return &t, r, nil
298 | }
299 |
--------------------------------------------------------------------------------
/data/cache.go:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "os"
7 | "path/filepath"
8 | "sync"
9 | "time"
10 |
11 | "github.com/dhowden/tag"
12 | lcss "github.com/vmarkovtsev/go-lcss"
13 |
14 | ev "github.com/ejv2/podbit/event"
15 | )
16 |
17 | // Possible cache errors.
18 | var (
19 | ErrorIO = errors.New("Error: Failed to create cache entry")
20 | ErrorCreation = errors.New("Error: Download directory did not exist and could not be created")
21 | ErrorDownloadFailed = "Error: Failed to download from url %s"
22 | )
23 |
24 | // Cache is the current state of the on-disk cache and associated
25 | // operations.
26 | //
27 | // This structure *is* thread safe, but ONLY is used with the
28 | // correct methods. Use with care!
29 | type Cache struct {
30 | episodes sync.Map
31 |
32 | downloadsMutex sync.RWMutex // Protects the below two variables
33 | downloads []*Download
34 | ongoing int
35 |
36 | hndl ev.Handler
37 | }
38 |
39 | // Episode represents the data extracted from a single cached episode
40 | // media entry.
41 | type Episode struct {
42 | Queued bool
43 |
44 | Title string
45 | Date int
46 | Host string
47 | }
48 |
49 | // Dig through newsboat stuff to guess the download dir.
50 | // If we can't find it, just use the newsboat default and hope for the best.
51 | func (c *Cache) guessDir(queueEntries []QueueItem) string {
52 | paths := make([][]byte, 0, len(queueEntries))
53 | for _, entry := range queueEntries {
54 | paths = append(paths, []byte(entry.Path))
55 | }
56 |
57 | bcom := lcss.LongestCommonSubstring(paths...)
58 | com := string(bcom)
59 | if com != "" {
60 | return com
61 | }
62 |
63 | ret, _ := os.UserHomeDir()
64 | return ret
65 | }
66 |
67 | // Open opens and initialises the cache.
68 | // Should be called once and once only - further modifications
69 | // and cache mutations happen exclusively through other methods.
70 | func (c *Cache) Open(q *Queue, hndl ev.Handler) error {
71 | if q == nil {
72 | panic("open cache: nil queue passed")
73 | }
74 | c.hndl = hndl
75 |
76 | for _, elem := range q.Items {
77 | c.loadFile(elem.Path, true)
78 | }
79 |
80 | return nil
81 | }
82 |
83 | func (c *Cache) loadFile(path string, startup bool) {
84 | file, err := os.Open(path)
85 | if err != nil {
86 | return
87 | }
88 | defer file.Close()
89 | defer func() {
90 | // Prevent invalid media files from causing a panic
91 | if p := recover(); p != nil {
92 | fmt.Printf("\nInvalid media file %q in cache! Ignoring...\n", path)
93 | return
94 | }
95 | }()
96 |
97 | data, err := tag.ReadFrom(file)
98 | if err != nil {
99 | fmt.Printf("\nError: Invalid media file %q in cache! Ignoring...\n", path)
100 | return
101 | }
102 |
103 | artist, albumArtist := data.Artist(), data.AlbumArtist()
104 | var host string
105 | if artist == "" {
106 | host = albumArtist
107 | } else {
108 | host = artist
109 | }
110 |
111 | ep := Episode{
112 | Queued: !startup,
113 | Title: data.Title(),
114 | Date: data.Year(),
115 | Host: host,
116 | }
117 |
118 | c.episodes.Store(path, ep)
119 | }
120 |
121 | // Download starts an asynchronous download in a new goroutine. Returns the ID
122 | // in the downloads table, which must be accessed using a mutex. Item passed
123 | // should be locked by the caller prior to calling.
124 | func (c *Cache) Download(item *QueueItem) (id int, err error) {
125 | dir := filepath.Dir(item.Path)
126 | err = os.MkdirAll(dir, os.ModePerm)
127 | if err != nil {
128 | dl := Download{
129 | mut: new(sync.RWMutex),
130 | Path: item.Path,
131 | File: nil,
132 | Elem: item,
133 | Started: time.Now(),
134 | Completed: true,
135 | Success: false,
136 | Error: "Directory IO Error",
137 | Stop: nil,
138 | }
139 |
140 | c.downloadsMutex.Lock()
141 | c.downloads = append(c.downloads, &dl)
142 | id = len(c.downloads) - 1
143 | c.downloadsMutex.Unlock()
144 |
145 | return id, ErrorIO
146 | }
147 |
148 | f, err := os.Create(item.Path)
149 | dl := Download{
150 | mut: new(sync.RWMutex),
151 | Path: item.Path,
152 | File: f,
153 | Elem: item,
154 | Started: time.Now(),
155 | Stop: make(chan int),
156 | }
157 |
158 | if err != nil {
159 | dl = Download{
160 | mut: new(sync.RWMutex),
161 | Path: item.Path,
162 | File: f,
163 | Elem: item,
164 | Started: time.Now(),
165 | Completed: true,
166 | Success: false,
167 | Error: "IO Error",
168 | Stop: nil,
169 | }
170 |
171 | c.downloadsMutex.Lock()
172 | c.downloads = append(c.downloads, &dl)
173 | id = len(c.downloads) - 1
174 | c.downloadsMutex.Unlock()
175 |
176 | return id, ErrorIO
177 | }
178 |
179 | if item.Youtube {
180 | go dl.DownloadYoutube(c.hndl)
181 | } else {
182 | go dl.DownloadHTTP(c.hndl)
183 | }
184 |
185 | c.downloadsMutex.Lock()
186 | c.downloads = append(c.downloads, &dl)
187 | id = len(c.downloads) - 1
188 | c.ongoing++
189 | c.downloadsMutex.Unlock()
190 |
191 | return
192 | }
193 |
194 | // IsDownloading queries the download cache to check.
195 | // if a podcast is currently downloading.
196 | func (c *Cache) IsDownloading(path string) (bool, int) {
197 | c.downloadsMutex.RLock()
198 | defer c.downloadsMutex.RUnlock()
199 |
200 | for i, elem := range c.downloads {
201 | elem.mut.RLock()
202 | if elem.Path == path && !elem.Completed {
203 | elem.mut.RUnlock()
204 | return true, i
205 | }
206 | elem.mut.RUnlock()
207 | }
208 |
209 | return false, 0
210 | }
211 |
212 | // GetDownload returns the specified download in a thread-safely.
213 | // This should be used to get the details of a specified download
214 | // via the ID.
215 | func (c *Cache) GetDownload(ind int) Download {
216 | c.downloads[ind].mut.RLock()
217 | defer c.downloads[ind].mut.RUnlock()
218 |
219 | return *c.downloads[ind]
220 | }
221 |
222 | // Ongoing returns the current number of ongoing downloads.
223 | // The value cannot change while this function is executing.
224 | func (c *Cache) Ongoing() int {
225 | c.downloadsMutex.RLock()
226 | defer c.downloadsMutex.RUnlock()
227 |
228 | return c.ongoing
229 | }
230 |
231 | // Downloads returns all recorded downloads at this point,
232 | // including completed or failed downloads.
233 | // No downloads can start or end while this function is
234 | // executing.
235 | func (c *Cache) Downloads() []Download {
236 | c.downloadsMutex.RLock()
237 | defer c.downloadsMutex.RUnlock()
238 |
239 | dls := make([]Download, len(c.downloads))
240 |
241 | for i, elem := range c.downloads {
242 | elem.mut.RLock()
243 | dls[i] = *elem
244 | elem.mut.RUnlock()
245 | }
246 |
247 | return dls
248 | }
249 |
250 | // Query returns cached data about an episode on disk.
251 | func (c *Cache) Query(path string) (ep Episode, ok bool) {
252 | e, ok := c.episodes.Load(path)
253 | if e != nil {
254 | ep = e.(Episode)
255 | }
256 |
257 | return
258 | }
259 |
260 | // QueryAll returns all known data about the on-disk cache.
261 | func (c *Cache) QueryAll(allowQueued bool) (e []Episode) {
262 | c.episodes.Range(func(key interface{}, value interface{}) bool {
263 | ep := value.(Episode)
264 | if (!allowQueued && !ep.Queued) || allowQueued {
265 | e = append(e, ep)
266 | }
267 |
268 | return true
269 | })
270 |
271 | return
272 | }
273 |
274 | // EntryExists searches the cache to determine if the entry exists
275 | // Path should be an absolute path
276 | // If path lies outside the cache dir, false is returned.
277 | func (c *Cache) EntryExists(path string) bool {
278 | f, err := os.Open(path)
279 | if err != nil && os.IsNotExist(err) {
280 | return false
281 | }
282 |
283 | f.Close()
284 | return true
285 | }
286 |
--------------------------------------------------------------------------------
/data/data.go:
--------------------------------------------------------------------------------
1 | // Package data implements data loading, management and serialisation.
2 | // It maintains a set of singleton instances of the data sources which
3 | // should be used directly by clients.
4 | //
5 | // Although most of the data sources are designed to be thread safe,
6 | // some, such as the cache, cannot guarantee this in all use cases.
7 | package data
8 |
9 | import (
10 | "fmt"
11 | "net/url"
12 | "os"
13 | "time"
14 |
15 | ev "github.com/ejv2/podbit/event"
16 | )
17 |
18 | const (
19 | // QueueReloadInterval is how often the queue will be reloaded.
20 | QueueReloadInterval = time.Minute
21 | // EpisodeCacheTime is how long an episode is allowed to stay in cache in seconds.
22 | // Default value is three days (3 * 24 * 60 * 60).
23 | EpisodeCacheTime = 259200
24 | )
25 |
26 | // Queue reload operations.
27 | const (
28 | DataReload = iota
29 | DataSave
30 | )
31 |
32 | // Dependent data structures.
33 | var (
34 | Q Queue
35 | Stamps *CacheDB
36 | DB Database
37 | Downloads Cache
38 | )
39 |
40 | // InitData initialises all dependent data structures.
41 | // The only returned errors *will* be fatal to the program.
42 | func InitData(hndl ev.Handler) error {
43 | fmt.Print("Reading cache.db...")
44 | Stamps = NewCacheDB()
45 | err := Stamps.Open()
46 | if err != nil {
47 | return err
48 | }
49 | fmt.Println("done")
50 |
51 | fmt.Print("Reading database...")
52 | err = DB.Open()
53 | if err != nil {
54 | return err
55 | }
56 | fmt.Println("done")
57 |
58 | fmt.Print("Reading queue...")
59 | err = Q.Open()
60 | if err != nil {
61 | return err
62 | }
63 | fmt.Println("done")
64 |
65 | fmt.Print("Initialising cache...")
66 | err = Downloads.Open(&Q, hndl)
67 | if err != nil {
68 | return err
69 | }
70 | fmt.Println("done")
71 |
72 | return nil
73 | }
74 |
75 | // SaveData cleans up and saves data to disk. First ensures we have
76 | // hot-reloaded any required data. Only designed for use at startup.
77 | func SaveData() {
78 | ReloadData()
79 | CleanData()
80 |
81 | Q.Save()
82 | Stamps.Save()
83 | }
84 |
85 | // ReloadData performs a hot-reload of any data which can/needs
86 | // to be hot reloaded.
87 | //
88 | // This is called automatically on an interval by ReloadLoop
89 | // and upon saving to ensure up-to-date data.
90 | func ReloadData() {
91 | Q.Reload()
92 | }
93 |
94 | // CleanData cleans out the cache based on items which are both finished/played
95 | // and with a last listen time of more than EpisodeCacheTime seconds ago
96 | // (defaults to three days). Removed episodes are set to "pending" status (to
97 | // be downloaded) and have their cache file removed.
98 | func CleanData() {
99 | fmt.Printf("Cache cleanup...")
100 |
101 | now := time.Now().Unix()
102 | count := 0
103 |
104 | Q.Range(func(_ int, item *QueueItem) bool {
105 | if item.State != StatePlayed && item.State != StateFinished {
106 | return true
107 | }
108 |
109 | date, _, err := Stamps.RawStat(item.Path)
110 | if err != nil {
111 | tmp := time.Now().Unix()
112 | date = &tmp
113 | }
114 | diff := now - *date
115 |
116 | // If past expiry date OR never present in cache.db in the first place, prune it
117 | if diff >= EpisodeCacheTime || err != nil {
118 | item.State = StatePending
119 | if err == nil {
120 | // Ignoring error here as we check the necessary condition above
121 | Stamps.Prune(item.Path)
122 | }
123 |
124 | os.Remove(item.Path)
125 | count++
126 | }
127 |
128 | return true
129 | })
130 |
131 | fmt.Printf("done (removed %d items)\n", count)
132 | }
133 |
134 | // ReloadLoop is an infinite loop to continually reload the
135 | // file on disk into memory.
136 | //
137 | // Should allow us to hot-reload the queue file - among other
138 | // things.
139 | func ReloadLoop(upchan chan int8) {
140 | ticker := time.NewTicker(QueueReloadInterval)
141 | count := 0
142 | defer ticker.Stop()
143 |
144 | loop:
145 | for {
146 |
147 | select {
148 | case <-ticker.C:
149 | ReloadData()
150 | if count == 3 {
151 | Q.Save()
152 | count = 0
153 | continue
154 | }
155 | count++
156 | case i, ok := <-upchan:
157 | if !ok {
158 | break loop
159 | }
160 |
161 | ReloadData()
162 | if i == DataSave {
163 | Q.Save()
164 | Stamps.Save()
165 | }
166 | }
167 | }
168 | }
169 |
170 | // IsURL returns true if a string is a valid HTTP(s) URL.
171 | func IsURL(check string) bool {
172 | u, err := url.Parse(check)
173 | return err == nil && u.Scheme != "" && u.Host != ""
174 | }
175 |
176 | // LimitString limits a UTF-8 string to max visible runes, showing the full
177 | // string if it is shorter than max. If max is negative or zero, an empty
178 | // string is returned.
179 | func LimitString(in string, max int) string {
180 | r := []rune(in)
181 | if max <= 0 {
182 | return ""
183 | }
184 | if max > len(r) {
185 | return in
186 | }
187 |
188 | return string(r[:max])
189 | }
190 |
191 | // FormatTime formats a time measured in seconds.
192 | func FormatTime(seconds float64) string {
193 | round := int(seconds)
194 |
195 | s := round % 60
196 | m := round / 60
197 | h := m / 60
198 | m = m % 60
199 |
200 | return fmt.Sprintf("%.2d:%.2d:%.2d", h, m, s)
201 | }
202 |
--------------------------------------------------------------------------------
/data/db.go:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "bufio"
5 | "errors"
6 | "fmt"
7 | "os"
8 | "path/filepath"
9 | "regexp"
10 | "strings"
11 | )
12 |
13 | const (
14 | // DatabaseDirname is the directory name in which the database will be stored.
15 | DatabaseDirname = "podbit"
16 |
17 | // DatabaseFilename is the file name of the database on disk.
18 | DatabaseFilename = "db"
19 | )
20 |
21 | // DB-related error values.
22 | var (
23 | ErrorDatabaseIOFailed = errors.New("Error: IO error while reading from database file")
24 | ErrorDatabaseSyntax = "Error: Malformed database: Syntax Error on Line %d"
25 | )
26 |
27 | // Podcast is the human-provided podcast info.
28 | type Podcast struct {
29 | RegexPattern string
30 | FriendlyName string
31 |
32 | pat *regexp.Regexp
33 | }
34 |
35 | // Owns returns true if the given url is a member of this podcast.
36 | func (p *Podcast) Owns(url string) bool {
37 | if p.pat == nil {
38 | panic("invalid podcast: regex pattern not compiled")
39 | }
40 |
41 | return p.pat.MatchString(url)
42 | }
43 |
44 | // Database aggregates all podcast data from the database.
45 | type Database struct {
46 | path string
47 | podcasts []Podcast
48 | defaultPodcast Podcast
49 | }
50 |
51 | func initDatabase(db *Database) error {
52 | var err error
53 | file, err := os.Open(db.path)
54 |
55 | if err != nil {
56 | file, err = os.Create(db.path)
57 | if err != nil {
58 | return err
59 | }
60 |
61 | file.Close()
62 | } else {
63 | defer file.Close()
64 |
65 | scanner := bufio.NewScanner(file)
66 | scanner.Split(bufio.ScanLines)
67 |
68 | i := 1
69 | for scanner.Scan() {
70 | var p Podcast
71 |
72 | if scanner.Err() != nil {
73 | return ErrorDatabaseIOFailed
74 | }
75 |
76 | elem := scanner.Text()
77 | if strings.HasPrefix(elem, "#") {
78 | continue
79 | }
80 | if len(elem) == 0 {
81 | continue
82 | }
83 |
84 | fields := strings.Split(elem, " ")
85 | num := len(fields)
86 |
87 | if num < 2 {
88 | return fmt.Errorf(ErrorDatabaseSyntax, i)
89 | }
90 |
91 | p.RegexPattern = fields[0]
92 | p.FriendlyName = strings.Join(fields[1:], " ")
93 |
94 | pat, err := regexp.Compile(p.RegexPattern)
95 | if err != nil {
96 | return fmt.Errorf("Error: Malformed database: Invalid regex on Line %d: %w", i, err)
97 | }
98 | p.pat = pat
99 |
100 | db.podcasts = append(db.podcasts, p)
101 |
102 | i++
103 | }
104 | }
105 |
106 | return nil
107 | }
108 |
109 | // Open opens and parses the database.
110 | // Returned errors are usually fatal to the application.
111 | func (db *Database) Open() error {
112 | data := os.Getenv("XDG_DATA_HOME")
113 | if data == "" {
114 | home, _ := os.UserHomeDir()
115 | data = filepath.Join(home, ".local/share")
116 | }
117 |
118 | db.path = filepath.Join(data, DatabaseDirname, DatabaseFilename)
119 |
120 | // Ensure the database exists and is initialised
121 | err := initDatabase(db)
122 | if err != nil {
123 | return err
124 | }
125 |
126 | // Add a default podcast, when none else are present
127 | db.defaultPodcast = Podcast{
128 | FriendlyName: UnknownPodcastName,
129 | RegexPattern: ".*",
130 | pat: regexp.MustCompile(".*"),
131 | }
132 | db.podcasts = append(db.podcasts, db.defaultPodcast)
133 |
134 | return nil
135 | }
136 |
137 | // Save saves the database to disk.
138 | // Errors are ignored, as save operations are usually done during application
139 | // use and are temporary (or nothing can be done).
140 | func (db *Database) Save() {
141 | file, err := os.OpenFile(db.path, os.O_WRONLY|os.O_TRUNC, os.ModePerm)
142 | if err != nil {
143 | fmt.Printf("WARNING: failed to write database: %s\n", ErrorDatabaseIOFailed)
144 | }
145 |
146 | for _, elem := range db.podcasts {
147 | fmt.Fprintf(file, "%s %s\n", elem.RegexPattern, elem.FriendlyName)
148 | }
149 |
150 | file.Close()
151 | }
152 |
153 | // GetPodcasts returns all podcasts configured in the db. This guarantees that
154 | // the same name will never be given twice (i.e podcasts with multi regex will
155 | // be merged.)
156 | func (db *Database) GetPodcasts() []Podcast {
157 | list := make([]Podcast, 0, len(db.podcasts))
158 | seen := make(map[string]bool, len(db.podcasts))
159 | for _, pod := range db.podcasts {
160 | if _, ok := seen[pod.FriendlyName]; !ok {
161 | list = append(list, pod)
162 | seen[pod.FriendlyName] = true
163 | }
164 | }
165 |
166 | return list
167 | }
168 |
169 | // GetPodcastNames returns the friendly names of all configured podcasts,
170 | // gnaranteeing the absence of duplicates.
171 | func (db *Database) GetPodcastNames() []string {
172 | pod := db.GetPodcasts()
173 | nam := make([]string, 0, len(pod))
174 | for _, p := range pod {
175 | nam = append(nam, p.FriendlyName)
176 | }
177 |
178 | return nam
179 | }
180 |
181 | // GetFriendlyName returns the user-configured friendly name for a
182 | // specified URL. If one cannot be found, the url is returned.
183 | func (db *Database) GetFriendlyName(url string) string {
184 | for _, elem := range db.podcasts {
185 | if elem.Owns(url) {
186 | return elem.FriendlyName
187 | }
188 | }
189 |
190 | return url
191 | }
192 |
193 | // GetRegex returns the registered regex for a specified friendly name - as
194 | // returned by GetFriendlyName.
195 | func (db *Database) GetRegex(friendly string) string {
196 | for _, elem := range db.podcasts {
197 | if elem.FriendlyName == friendly {
198 | return elem.RegexPattern
199 | }
200 | }
201 |
202 | return ""
203 | }
204 |
205 | // GetOwner returns the owning podcast, if known. If the owning podcast is
206 | // known, the default podcast is returned.
207 | func (db *Database) GetOwner(url string) Podcast {
208 | for _, elem := range db.podcasts {
209 | if elem.Owns(url) {
210 | return elem
211 | }
212 | }
213 |
214 | return db.defaultPodcast
215 | }
216 |
--------------------------------------------------------------------------------
/data/download.go:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "net/http"
5 | "os"
6 | "os/exec"
7 | "path/filepath"
8 | "runtime"
9 | "strconv"
10 | "strings"
11 | "sync"
12 | "time"
13 |
14 | ev "github.com/ejv2/podbit/event"
15 | )
16 |
17 | // YouTube downloading constants.
18 | const (
19 | YoutubeDL string = "youtube-dl"
20 | YoutubeDLP string = "yt-dlp"
21 | YoutubeFlags string = "--add-metadata --newline --no-colors -f bestaudio --extract-audio --audio-format mp3"
22 | )
23 |
24 | // eventInterval is the minimum time between two DownloadChanged events emitted
25 | // by a downloader goroutine. This is intended to reduce thread contention
26 | // between these goroutines.
27 | const eventInterval = 500 * time.Millisecond
28 |
29 | // Download represents the statistics of a specific ongoing download.
30 | // Once the associated download is complete, the watcher goroutine
31 | // terminates.
32 | //
33 | // This struct may only be modified through associated methods.
34 | type Download struct {
35 | // Protects this download instance
36 | mut *sync.RWMutex
37 |
38 | // Path is the absolute path of the download destination
39 | Path string
40 | // File is the live file handle of the download
41 | // Will be closed once Completed == true
42 | File *os.File
43 | // Elem is the associated queue element
44 | Elem *QueueItem
45 |
46 | // Percentage is the calculated percentage currently completed
47 | Percentage float64
48 |
49 | // Size is the total size to download
50 | Size int64
51 | // Done is the currently downloaded size present on disk
52 | Done int64
53 |
54 | // Started is the timestamp of the download commencing
55 | Started time.Time
56 |
57 | // Completed == true once the operations has either finished or failed
58 | Completed bool
59 | // Success == true if the full download completed successfully
60 | Success bool
61 | // Error is the error which caused the download to fail
62 | // Empty if the download did not fail
63 | Error string
64 |
65 | // Stop will cause the download to cease immediately
66 | // Will be closed once the download completes
67 | Stop chan int
68 | }
69 |
70 | // DownloadYoutube selects an appropriate downloader (yt-dlp or
71 | // youtube-dl) and begins a YouTube download on the calling thread
72 | // (synchronously).
73 | //
74 | // Used internally by cache; avoid calling directly.
75 | func (d *Download) DownloadYoutube(hndl ev.Handler) {
76 | d.Elem.RLock()
77 | if !d.Elem.Youtube {
78 | panic("download: downloading non-youtube with youtube-dl")
79 | }
80 | d.Elem.RUnlock()
81 |
82 | // Work around "already downloaded" errors from youtube-dl
83 | d.File.Close()
84 | os.Remove(d.File.Name())
85 |
86 | defer func() {
87 | Downloads.downloadsMutex.Lock()
88 | Downloads.ongoing--
89 | Downloads.downloadsMutex.Unlock()
90 | }()
91 | defer close(d.Stop)
92 |
93 | // Determine downloader program - use yt-dlp if available, else use ytdl
94 | loader := ""
95 | if _, err := exec.LookPath(YoutubeDLP); err == nil {
96 | loader = YoutubeDLP
97 | } else if _, err := exec.LookPath(YoutubeDL); err == nil {
98 | loader = YoutubeDL
99 | } else {
100 | d.mut.Lock()
101 | d.Completed = true
102 | d.Success = false
103 | d.Error = "No YouTube downloader"
104 | d.mut.Unlock()
105 |
106 | return
107 | }
108 |
109 | d.Elem.RLock()
110 | h, _ := os.UserHomeDir()
111 | tmppath := filepath.Join(h, "podbit-ytdl"+strconv.FormatInt(time.Now().UnixMicro(), 10))
112 | flags := append(strings.Split(YoutubeFlags, " "), "-o", tmppath+".%(ext)s", d.Elem.URL)
113 | d.Elem.RUnlock()
114 |
115 | proc := exec.Command(loader, flags...)
116 | r, err := proc.StdoutPipe()
117 | if err != nil {
118 | d.mut.Lock()
119 | d.Completed = true
120 | d.Success = false
121 | d.Error = "Downloader IO Error"
122 | d.mut.Unlock()
123 |
124 | return
125 | }
126 | proc.Start()
127 |
128 | // NOTE: Do not need to runtime.Gosched here to prevent contention, because IO waiting
129 | // occurs on this thread and the runtime will implicitly call it for us when there's no
130 | // pending data. Manually calling causes net performance loss
131 |
132 | buf := make([]byte, 4096)
133 | lastPost := time.Now()
134 | for err == nil {
135 | _, err = r.Read(buf)
136 | line := string(buf)
137 | fields := strings.Fields(line)
138 |
139 | if fields[0] != "[download]" || len(fields) < 2 {
140 | continue
141 | }
142 |
143 | d.mut.Lock()
144 | d.Percentage, _ = strconv.ParseFloat(fields[1][:len(fields[1])-1], 64)
145 | d.Percentage /= 100
146 | d.mut.Unlock()
147 |
148 | if time.Since(lastPost) >= eventInterval {
149 | hndl.Post(ev.DownloadChanged)
150 | lastPost = time.Now()
151 | }
152 |
153 | select {
154 | case <-d.Stop:
155 | d.mut.Lock()
156 | d.Error = "Cancelled"
157 | d.Completed = true
158 | d.Success = false
159 | d.mut.Unlock()
160 |
161 | r.Close()
162 | proc.Process.Kill()
163 | return
164 | default:
165 | }
166 | }
167 | hndl.Post(ev.DownloadChanged)
168 | r.Close()
169 |
170 | if err.Error() != "EOF" {
171 | d.mut.Lock()
172 | d.Completed = true
173 | d.Success = false
174 | d.Error = "Downloader IO Error"
175 | d.mut.Unlock()
176 | return
177 | }
178 |
179 | err = proc.Wait()
180 | if err != nil {
181 | d.mut.Lock()
182 | d.Completed = true
183 | d.Success = false
184 | d.Error = "Download failed"
185 | d.mut.Unlock()
186 | return
187 | }
188 |
189 | // Move from temp location
190 | os.Rename(tmppath+".mp3", d.Path)
191 |
192 | // Final clean up
193 | d.Elem.Lock()
194 | d.Elem.State = StateReady
195 |
196 | d.mut.Lock()
197 | d.Completed = true
198 | d.Success = true
199 |
200 | Downloads.downloadsMutex.Lock()
201 | Downloads.loadFile(d.Elem.Path, false)
202 | Downloads.downloadsMutex.Unlock()
203 |
204 | d.mut.Unlock()
205 | d.Elem.Unlock()
206 |
207 | hndl.Post(ev.DownloadChanged)
208 | }
209 |
210 | // DownloadHTTP connects to the URL of the specified download
211 | // and downloads to download path on the calling thread
212 | // (synchronously)
213 | //
214 | // Used internally by cache; avoid calling directly.
215 | func (d *Download) DownloadHTTP(hndl ev.Handler) {
216 | d.Elem.RLock()
217 | resp, err := http.Get(d.Elem.URL)
218 | if err != nil || resp.StatusCode != http.StatusOK {
219 | d.mut.Lock()
220 | d.Completed = true
221 | d.Success = false
222 | d.Error = "Download failed"
223 | d.mut.Unlock()
224 |
225 | Downloads.downloadsMutex.Lock()
226 | Downloads.ongoing--
227 | Downloads.downloadsMutex.Unlock()
228 |
229 | os.Remove(d.Elem.Path)
230 | hndl.Post(ev.DownloadChanged)
231 | return
232 | }
233 | d.Elem.RUnlock()
234 |
235 | d.mut.Lock()
236 | size, _ := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
237 | d.Size = size
238 | d.mut.Unlock()
239 |
240 | d.Elem.Lock()
241 | d.Elem.State = StatePending
242 | d.Elem.Unlock()
243 |
244 | var count int64
245 | var read int
246 | dlerr := ""
247 | buf := make([]byte, 32*1024) // 32kb
248 | lastPost := time.Now()
249 |
250 | outer:
251 | for err == nil {
252 | read, err = resp.Body.Read(buf)
253 | d.File.WriteAt(buf, count)
254 | count += int64(read)
255 |
256 | d.mut.Lock()
257 | d.Done = count
258 | d.Percentage = float64(d.Done) / float64(d.Size)
259 | d.mut.Unlock()
260 |
261 | if time.Since(lastPost) >= eventInterval {
262 | hndl.Post(ev.DownloadChanged)
263 | lastPost = time.Now()
264 | }
265 |
266 | if Downloads.Ongoing() > 1 {
267 | runtime.Gosched() // Give the other threads a turn
268 | }
269 |
270 | select {
271 | case <-d.Stop:
272 | dlerr = "Cancelled"
273 | break outer
274 | default:
275 | }
276 | }
277 |
278 | d.mut.Lock()
279 | d.Completed = true
280 | if (err != nil && err.Error() != "EOF") || dlerr != "" {
281 | d.Success = false
282 | d.Error = dlerr
283 | } else {
284 | d.Success = true
285 |
286 | d.Elem.Lock()
287 | d.Elem.State = StateReady
288 | d.Elem.Unlock()
289 | }
290 | d.mut.Unlock()
291 |
292 | Downloads.downloadsMutex.Lock()
293 | d.Elem.RLock()
294 | Downloads.loadFile(d.Elem.Path, false)
295 | Downloads.ongoing--
296 | d.Elem.RUnlock()
297 | Downloads.downloadsMutex.Unlock()
298 |
299 | resp.Body.Close()
300 | d.File.Close()
301 |
302 | hndl.Post(ev.DownloadChanged)
303 | close(d.Stop)
304 | }
305 |
--------------------------------------------------------------------------------
/data/escape/escape.go:
--------------------------------------------------------------------------------
1 | // Package escape maps unneeded Unicode characters to an ASCII equivalent and
2 | // removes dangerous unprinting characters.
3 | //
4 | // Many applications do not need/want to support Unicode, but still wish to be
5 | // able to be fed most Unicode input from their respective language. For
6 | // instance, programs using ncurses are incapable of using wide characters
7 | // without compile-time hacking. In addition, lookalike homoglyph characters
8 | // can be used in social engineering attacks or to circumvent naive filters.
9 | // This package attempts to act as a "temporary" solution to all these problems
10 | // by converting such characters to a sane, ASCII equivalent.
11 | //
12 | // As UTF-8 is backward compatible with ASCII, all outputted strings are still
13 | // valid UTF-8.
14 | //
15 | // Data sourced from http://homoglyphs.net/
16 | //
17 | // Deprecated: This library is not for use. You should really just support
18 | // UTF-8 instead.
19 | package escape
20 |
21 | // Convertibles are runes which should be converted from the map key to the map
22 | // value. Eg:
23 | //
24 | // Convertibles['″'] --> '"'
25 | //
26 | // Although values may appear to be the same (as they are homoglyphs), they
27 | // have a different internal representation and are NOT the same value.
28 | var Convertibles = map[rune]rune{
29 | // Punctuation
30 | '″': '"',
31 | '‘': '\'',
32 | '’': '\'',
33 | '‚': ',',
34 | '⁎': '*',
35 | '‐': '-',
36 | '⁄': '/',
37 | '‹': '<',
38 | '›': '>',
39 | '⁓': '~',
40 | ';': ';',
41 |
42 | // Cyrillic lookalikes (upper)
43 | 'А': 'A',
44 | 'В': 'B',
45 | 'С': 'C',
46 | 'Е': 'E',
47 | 'Ԍ': 'G',
48 | 'Н': 'H',
49 | 'І': 'I',
50 | 'Ј': 'J',
51 | 'К': 'K',
52 | 'М': 'M',
53 | 'О': 'O',
54 | 'Р': 'P',
55 | 'Ѕ': 'S',
56 | 'Т': 'T',
57 | 'Ѵ': 'V',
58 | 'Х': 'X',
59 | 'Ү': 'Y',
60 | // Cyrillic lookalikes (lower)
61 | 'а': 'a',
62 | 'Ь': 'b',
63 | 'с': 'c',
64 | 'ԁ': 'd',
65 | 'е': 'e',
66 | 'һ': 'h',
67 | 'і': 'i',
68 | 'ј': 'j',
69 | 'о': 'o',
70 | 'р': 'p',
71 | 'ѕ': 's',
72 | 'ѵ': 'v',
73 | 'ѡ': 'w',
74 | 'х': 'x',
75 | 'у': 'y',
76 |
77 | // Greek lookalikes (upper)
78 | 'Α': 'A',
79 | 'Β': 'B',
80 | 'β': 'b',
81 | 'Ϲ': 'C',
82 | 'Ε': 'E',
83 | 'Ϝ': 'F',
84 | 'Η': 'H',
85 | 'Ι': 'I',
86 | 'Κ': 'K',
87 | 'Μ': 'M',
88 | 'Ν': 'N',
89 | 'Ο': 'O',
90 | 'Ρ': 'P',
91 | 'Τ': 'T',
92 | 'Χ': 'X',
93 | 'Υ': 'Y',
94 | 'Ζ': 'Z',
95 | // Greek lookalikes (lower)
96 | 'ϲ': 'c',
97 | 'ο': 'o',
98 | 'ν': 'v',
99 |
100 | // Roman numerals (upper)
101 | 'Ⅽ': 'C',
102 | 'Ⅾ': 'D',
103 | 'Ⅰ': 'I',
104 | 'Ⅼ': 'L',
105 | 'Ⅿ': 'M',
106 | 'Ⅴ': 'V',
107 | 'Ⅹ': 'X',
108 | // Roman numerals (lower)
109 | 'ⅽ': 'c',
110 | 'ⅾ': 'd',
111 | 'ⅰ': 'i',
112 | 'ⅼ': 'l',
113 | 'ⅿ': 'm',
114 | 'ⅴ': 'v',
115 | 'ⅹ': 'x',
116 |
117 | // Fullwidth (punctuation)
118 | '!': '!',
119 | '"': '"',
120 | '$': '$',
121 | '%': '%',
122 | '&': '&',
123 | ''': '\'',
124 | '(': '(',
125 | ')': ')',
126 | '*': '*',
127 | '+': '+',
128 | ',': ',',
129 | '-': '-',
130 | '.': ',',
131 | '/': '/',
132 | '\': '\\',
133 | ':': ':',
134 | ';': ';',
135 | '<': '<',
136 | '=': '=',
137 | '>': '>',
138 | '?': '?',
139 | '@': '@',
140 | '[': '[',
141 | ']': ']',
142 | '^': '^',
143 | '_': '_',
144 | '`': '`',
145 | '{': '{',
146 | '}': '}',
147 | '~': '~',
148 | '|': '|',
149 | // Fullwidth (numbers)
150 | '0': '0',
151 | '1': '1',
152 | '2': '2',
153 | '3': '3',
154 | '4': '4',
155 | '5': '5',
156 | '6': '6',
157 | '7': '7',
158 | '8': '8',
159 | '9': '9',
160 | // Fullwidth (upper)
161 | 'A': 'A',
162 | 'B': 'B',
163 | 'C': 'C',
164 | 'D': 'D',
165 | 'E': 'E',
166 | 'F': 'F',
167 | 'G': 'G',
168 | 'H': 'H',
169 | 'I': 'I',
170 | 'J': 'J',
171 | 'K': 'K',
172 | 'L': 'L',
173 | 'M': 'M',
174 | 'N': 'N',
175 | 'O': 'O',
176 | 'P': 'P',
177 | 'Q': 'Q',
178 | 'R': 'R',
179 | 'S': 'S',
180 | 'T': 'T',
181 | 'U': 'U',
182 | 'V': 'V',
183 | 'W': 'W',
184 | 'X': 'X',
185 | 'Y': 'Y',
186 | 'Z': 'Z',
187 | // Fullwidth (lower)
188 | 'a': 'a',
189 | 'b': 'b',
190 | 'c': 'c',
191 | 'd': 'd',
192 | 'e': 'e',
193 | 'f': 'f',
194 | 'g': 'g',
195 | 'h': 'h',
196 | 'i': 'i',
197 | 'j': 'j',
198 | 'k': 'k',
199 | 'l': 'l',
200 | 'm': 'm',
201 | 'n': 'n',
202 | 'o': 'o',
203 | 'p': 'p',
204 | 'q': 'q',
205 | 'r': 'r',
206 | 's': 's',
207 | 't': 't',
208 | 'u': 'u',
209 | 'v': 'v',
210 | 'w': 'w',
211 | 'x': 'x',
212 | 'y': 'y',
213 | 'z': 'z',
214 | }
215 |
216 | // Escape returns s with all occurrences of unnecessary or confusing Unicode
217 | // replaced with safe ASCII equivalents.
218 | func Escape(s string) string {
219 | arr := []rune(s)
220 | for i, r := range arr {
221 | arr[i] = EscapeRune(r)
222 | }
223 |
224 | return string(arr)
225 | }
226 |
227 | func EscapeBytes(buf []byte) []byte {
228 | return []byte(Escape(string(buf)))
229 | }
230 |
231 | // EscapeRune returns r as a safe rune, meaning that it has been converted if
232 | // an unsafe, unnecessary or confusing Unicode character to a safe ASCII
233 | // equivalent.
234 | func EscapeRune(r rune) rune {
235 | rep, ok := Convertibles[r]
236 | if ok {
237 | return rep
238 | }
239 |
240 | return r
241 | }
242 |
--------------------------------------------------------------------------------
/data/escape/escape_test.go:
--------------------------------------------------------------------------------
1 | package escape_test
2 |
3 | import (
4 | "strings"
5 | "testing"
6 | "unicode/utf8"
7 |
8 | "github.com/ejv2/podbit/data/escape"
9 | )
10 |
11 | var EscapeTests = []struct {
12 | Orig, Expects string
13 | }{
14 | {"", ""},
15 | {" ", " "},
16 | {"The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy dog"},
17 | {"The quick brown fox’s lazy jumping dog", "The quick brown fox's lazy jumping dog"},
18 | {"ABCDEF", "ABCDEF"},
19 | {"0xBADF00D", "0xBADF00D"},
20 | {"ethan_v2", "ethan_v2"},
21 | }
22 |
23 | // TestConvertibles runs data validation tests on escape.Convertibles.
24 | func TestConvertibles(t *testing.T) {
25 | t.Run("SelfMapping", testSelfMapping)
26 | t.Run("ASCIIMapping", testASCIIMapping)
27 | }
28 |
29 | // testSelfMapping tests if any keys in the Convertibles set map to themselves
30 | // (should never happen).
31 | func testSelfMapping(t *testing.T) {
32 | for key, val := range escape.Convertibles {
33 | if key == val {
34 | t.Errorf("selfmap: %U maps to itself (value %U)", key, val)
35 | }
36 | }
37 | }
38 |
39 | // testASCIIMapping tests if any keys in the Convertibles set map to non-ASCII
40 | // characters (should never happen). Additionally, tests if any ASCII
41 | // characters have unwittingly been entered to be converted (again, should
42 | // never happen).
43 | func testASCIIMapping(t *testing.T) {
44 | for key, val := range escape.Convertibles {
45 | if int32(key) <= 127 {
46 | t.Errorf("asciimap: ascii value found to be converted: %U", key)
47 | }
48 | if int32(val) > 127 {
49 | t.Errorf("asciimap: non-ascii value found as safe conversion: %U", val)
50 | }
51 | }
52 | }
53 |
54 | func TestEscape(t *testing.T) {
55 | t.Run("EscapeString", testEscapeString)
56 | t.Run("EscapeBytes", testEscapeBytes)
57 | }
58 |
59 | // testEscapeString tests if each given input string can be mapped to the
60 | // correct output string using only safe characters. The returned must be fully
61 | // valid UTF-8.
62 | func testEscapeString(t *testing.T) {
63 | for _, elem := range EscapeTests {
64 | e := escape.Escape(elem.Orig)
65 | if e != elem.Expects {
66 | t.Errorf("escape: bad escape: expected %q, got %q", elem.Expects, e)
67 | }
68 | if !utf8.ValidString(e) {
69 | t.Errorf("escape: bad escape: invalid UTF-8: %s", e)
70 | }
71 | }
72 | }
73 |
74 | // testEscapeBytes runs the same tests as testEscapeString, but converts each
75 | // string to a slice of bytes first, expecting the exact same results, but in
76 | // byte form. Returned bytes must be fully valid UTF-8.
77 | func testEscapeBytes(t *testing.T) {
78 | for _, elem := range EscapeTests {
79 | by := []byte(elem.Orig)
80 | e := escape.EscapeBytes(by)
81 |
82 | if len(e) != len(elem.Expects) {
83 | t.Errorf("escape: bad escape: expected len %d, got %d", len(elem.Expects), len(e))
84 | }
85 | for i, entry := range e {
86 | if entry != elem.Expects[i] {
87 | t.Errorf("escape: bad escape: expected %q, got %q", elem.Expects, e)
88 | }
89 | }
90 |
91 | if !utf8.Valid(e) {
92 | t.Errorf("escape: bad escape: invalid UTF-8: %s", string(e))
93 | }
94 | }
95 | }
96 |
97 | func FuzzEscape(f *testing.F) {
98 | for _, elem := range EscapeTests {
99 | f.Add(elem.Orig)
100 | }
101 |
102 | f.Fuzz(func(t *testing.T, a string) {
103 | out := escape.Escape(a)
104 | if !utf8.ValidString(out) {
105 | t.Errorf("escape: bad escape fuzz: unvalid UTF-8")
106 | }
107 |
108 | for key := range escape.Convertibles {
109 | if strings.ContainsRune(out, key) {
110 | t.Errorf("escape: bad escape fuzz: still contains forbidden rune")
111 | }
112 | }
113 | })
114 | }
115 |
--------------------------------------------------------------------------------
/data/queue.go:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "bufio"
5 | "errors"
6 | "fmt"
7 | "os"
8 | "path/filepath"
9 | "strconv"
10 | "strings"
11 | "sync"
12 | )
13 |
14 | // RangeFunc is the callback definition for a thread-safe
15 | // cycle through the queue array. The arguments are formed
16 | // in the style of a for range loop. The returned boolean
17 | // will exit the looping if it is not true.
18 | type RangeFunc func(i int, item *QueueItem) bool
19 |
20 | // Queue parsing/management errors.
21 | var (
22 | ErrorNotFound = errors.New("Error: Failed to locate newsboat queue file")
23 | ErrorNotOpen = errors.New("Error: Cannot parse a queue that is not open")
24 | ErrorIOFailed = errors.New("Error: IO error while reading from queue file")
25 | ErrorQueueSyntax = "Error: Malformed queue: Syntax error on line %d"
26 | )
27 |
28 | // PossibleDirs are the locations where the queue will search for a newsboat
29 | // queue file.
30 | var PossibleDirs = []string{
31 | ".local/share/newsboat",
32 | ".newsboat",
33 | }
34 |
35 | const (
36 | // QueueFilename is the name of the file for the queue.
37 | QueueFilename = "queue"
38 | // UnknownPodcastName is the name used for episodes from an unknown podcast.
39 | UnknownPodcastName = "Unrecognised"
40 | )
41 |
42 | // Possible states of download queue.
43 | const (
44 | StatePending = iota // Pending download
45 | StateReady // Downloaded and ready to play
46 | StatePlayed // Played at least once
47 | StateFinished // Finished to the end
48 | )
49 |
50 | // StateStrings are the names used to serialise or display queue
51 | // statuses to the user.
52 | var StateStrings = [4]string{
53 | "",
54 | "downloaded",
55 | "played",
56 | "finished",
57 | }
58 |
59 | // QueueItem represents an item in the player queue
60 | // as provided by newsboat.
61 | type QueueItem struct {
62 | *sync.RWMutex
63 |
64 | URL string
65 | Path string
66 | State int
67 | Youtube bool
68 | }
69 |
70 | // Queue represents the newsboat queue.
71 | type Queue struct {
72 | path string
73 | file *os.File
74 |
75 | // mutex protects all of the below
76 | mutex sync.RWMutex
77 | Items []*QueueItem
78 | // both of below are cached references into the items array
79 | Podmap map[string][]*QueueItem
80 | Linkmap map[string]*QueueItem
81 | }
82 |
83 | func (q *Queue) parseField(fields []string, num int) (item QueueItem) {
84 | item.URL = fields[0]
85 | item.Path = strings.ReplaceAll(fields[1], "\"", "")
86 | item.RWMutex = new(sync.RWMutex)
87 |
88 | if strings.HasPrefix(item.URL, "+") {
89 | item.Youtube = true
90 | item.URL = item.URL[1:]
91 | }
92 |
93 | // NOTE: Not closing file or handling error here as both are handled
94 | // implicitly below
95 | _, err := os.Open(item.Path)
96 |
97 | if num == 2 || (err != nil && os.IsNotExist(err)) {
98 | item.State = StatePending
99 | } else {
100 | switch fields[2] {
101 | case "downloaded":
102 | item.State = StateReady
103 | case "played":
104 | item.State = StatePlayed
105 | case "finished":
106 | item.State = StateFinished
107 | default:
108 | item.State = StateReady
109 | }
110 |
111 | if num > 3 {
112 | date, err := strconv.ParseInt(fields[3], 10, 64)
113 | if err != nil {
114 | return
115 | }
116 |
117 | // Ignore error here as errors will occur during reloads for duplicate entries.
118 | Stamps.Insert(item.Path, date)
119 | }
120 | }
121 |
122 | return
123 | }
124 |
125 | // Open opens and parses the newsboat queue file.
126 | // Returned errors are usually fatal to the application.
127 | func (q *Queue) Open() error {
128 | // Init stuff inside queue that we need here
129 | q.Linkmap = make(map[string]*QueueItem)
130 | q.Podmap = make(map[string][]*QueueItem)
131 |
132 | // First try the most likely places
133 | var err error
134 | found := false
135 | home, _ := os.UserHomeDir()
136 | data := os.Getenv("XDG_DATA_HOME")
137 |
138 | for _, elem := range PossibleDirs {
139 | q.path = filepath.Join(home, elem, QueueFilename)
140 | q.file, err = os.Open(q.path)
141 |
142 | if err == nil {
143 | found = true
144 | break
145 | }
146 | }
147 |
148 | // Next try XDG
149 | if !found {
150 | q.path = filepath.Join(home, data, "newsboat", QueueFilename)
151 | q.file, err = os.Open(q.path)
152 |
153 | if err == nil {
154 | found = true
155 | }
156 | }
157 |
158 | // If we still haven't found it, we never will
159 | if !found {
160 | return ErrorNotFound
161 | }
162 |
163 | q.mutex.Lock()
164 | defer q.mutex.Unlock()
165 |
166 | scanner := bufio.NewScanner(q.file)
167 | scanner.Split(bufio.ScanLines)
168 |
169 | i := 1
170 | for scanner.Scan() {
171 | if scanner.Err() != nil {
172 | return ErrorIOFailed
173 | }
174 |
175 | elem := scanner.Text()
176 | fields := strings.Split(elem, " ")
177 | num := len(fields)
178 |
179 | if num < 2 {
180 | return fmt.Errorf(ErrorQueueSyntax, i)
181 | }
182 |
183 | item := q.parseField(fields, num)
184 | pod := DB.GetOwner(item.URL)
185 |
186 | if _, ok := q.Linkmap[item.URL]; ok {
187 | fmt.Printf("WARNING: Duplicate entry in queue (line %d, url: %s) - dropping subsequent entries\n", i, item.URL)
188 | continue
189 | }
190 |
191 | q.Items = append(q.Items, &item)
192 | q.Linkmap[item.URL] = q.Items[len(q.Items)-1]
193 | q.Podmap[pod.FriendlyName] = append(q.Podmap[pod.FriendlyName], q.Items[len(q.Items)-1])
194 | i++
195 | }
196 |
197 | return nil
198 | }
199 |
200 | // Reload performs a hot-reload
201 | //
202 | // Merges are performed on the simple basis that new lines are the
203 | // data we want. All other changes are wiped and completely ignored.
204 | func (q *Queue) Reload() {
205 | q.mutex.Lock()
206 | defer q.mutex.Unlock()
207 |
208 | q.file.Close()
209 |
210 | var err error
211 | q.file, err = os.Open(q.path)
212 | if err != nil {
213 | fmt.Println("WARNING: Failed to open queue when reloading")
214 | return
215 | }
216 |
217 | scanner := bufio.NewScanner(q.file)
218 |
219 | i := 1
220 | for scanner.Scan() {
221 | if scanner.Err() != nil {
222 | fmt.Println("WARNING: Failed to reload queue")
223 | return
224 | }
225 |
226 | elem := scanner.Text()
227 |
228 | fields := strings.Split(elem, " ")
229 | num := len(fields)
230 |
231 | if num < 2 {
232 | fmt.Println("WARNING: Invalid queue found while reloading")
233 | return
234 | }
235 |
236 | item := q.parseField(fields, num)
237 | pod := DB.GetOwner(item.URL)
238 |
239 | if _, ok := q.Linkmap[item.URL]; ok {
240 | continue
241 | }
242 |
243 | q.Items = append(q.Items, &item)
244 | q.Linkmap[item.URL] = q.Items[len(q.Items)-1]
245 | q.Podmap[pod.FriendlyName] = append(q.Podmap[pod.FriendlyName], q.Items[len(q.Items)-1])
246 | i++
247 | }
248 | }
249 |
250 | // Save dumps the current state into the queue file, disregarding changes
251 | // and without syncing contained state.
252 | //
253 | // The file is first truncated and blanked.
254 | func (q *Queue) Save() {
255 | q.mutex.RLock()
256 | defer q.mutex.RUnlock()
257 |
258 | file, err := os.OpenFile(q.path, os.O_TRUNC|os.O_WRONLY, os.ModePerm)
259 | if err != nil {
260 | fmt.Printf("WARNING: Failed to save queue file: %s\n", err.Error())
261 | }
262 | defer file.Close()
263 |
264 | for _, elem := range q.Items {
265 | prefix := ""
266 |
267 | if elem.Youtube {
268 | prefix = "+"
269 | }
270 |
271 | ss := StateStrings[elem.State]
272 | if ss != "" {
273 | ss = " " + ss
274 | }
275 |
276 | fmt.Fprintf(file, "%s%s \"%s\"%s\n", prefix, elem.URL, elem.Path, ss)
277 | }
278 | }
279 |
280 | // Range loops through the queue array in a thread-safe fashion
281 | // using a callback which receives each item in the queue in the
282 | // same format as a for range loop.
283 | //
284 | // It *IS* save to modify the queue in the callback.
285 | func (q *Queue) Range(callback RangeFunc) {
286 | q.mutex.Lock()
287 | defer q.mutex.Unlock()
288 |
289 | for i := range q.Items {
290 | if !callback(i, q.Items[i]) {
291 | return
292 | }
293 | }
294 | }
295 |
296 | // RevRange range loops through the queue array in reverse order in a thread
297 | // safe fashion using a callback which receives each item in the queue in the
298 | // same format as a range loop.
299 | //
300 | // It *IS* safe to modify the queue in this callback.
301 | func (q *Queue) RevRange(callback RangeFunc) {
302 | q.mutex.Lock()
303 | defer q.mutex.Unlock()
304 |
305 | for i := len(q.Items) - 1; i >= 0; i-- {
306 | if !callback(i, q.Items[i]) {
307 | return
308 | }
309 | }
310 | }
311 |
312 | // RLock calls RLock on the internal RWMutex.
313 | func (q *Queue) RLock() {
314 | q.mutex.RLock()
315 | }
316 |
317 | // RUnlock calls RLock on the internal RWMutex. This should ALWAYS be deferred.
318 | func (q *Queue) RUnlock() {
319 | q.mutex.RUnlock()
320 | }
321 |
322 | // Lock calls Lock on the internal RWMutex.
323 | func (q *Queue) Lock() {
324 | q.mutex.Lock()
325 | }
326 |
327 | // Unlock calls Lock on the internal RWMutex. This should ALWAYS be deferred.
328 | func (q *Queue) Unlock() {
329 | q.mutex.Unlock()
330 | }
331 |
332 | // GetPodcasts returns each individual podcast detected through the queue file
333 | // and database.
334 | //
335 | // Deprecated: Use DB.GetPodcastNames.
336 | func (q *Queue) GetPodcasts() (podcasts []string) {
337 | q.mutex.RLock()
338 | defer q.mutex.RUnlock()
339 |
340 | podcasts = make([]string, 0, len(q.Podmap))
341 | for pod := range q.Podmap {
342 | podcasts = append(podcasts, pod)
343 | }
344 |
345 | return
346 | }
347 |
348 | // GetEpisodeByURL searches the queue file for an entry with the requested URL.
349 | func (q *Queue) GetEpisodeByURL(url string) *QueueItem {
350 | q.mutex.RLock()
351 | defer q.mutex.RUnlock()
352 |
353 | return q.Linkmap[url]
354 | }
355 |
356 | // GetEpisodeByTitle searches the queue file for an entry
357 | // with the requested title from cache.
358 | func (q *Queue) GetEpisodeByTitle(title string) (found *QueueItem) {
359 | q.Range(func(_ int, elem *QueueItem) bool {
360 | find, ok := Downloads.Query(elem.Path)
361 | if ok && find.Title == title {
362 | found = elem
363 | return false
364 | }
365 |
366 | return true
367 | })
368 |
369 | return
370 | }
371 |
372 | // GetByStatus returns all queue entries which are currently
373 | // in the status marked in state.
374 | func (q *Queue) GetByStatus(status int) (found []*QueueItem) {
375 | q.Range(func(_ int, elem *QueueItem) bool {
376 | if elem.State == status {
377 | found = append(found, elem)
378 | }
379 |
380 | return true
381 | })
382 |
383 | return
384 | }
385 |
386 | // GetPodcastEpisodes returns all episodes found to match a given episode, or
387 | // an empty array for an unknown podcast or configured podcast with no episodes.
388 | func (q *Queue) GetPodcastEpisodes(friendlyName string) []*QueueItem {
389 | q.mutex.RLock()
390 | defer q.mutex.RUnlock()
391 |
392 | arr, ok := q.Podmap[friendlyName]
393 | if !ok {
394 | return []*QueueItem{}
395 | }
396 | return arr
397 | }
398 |
--------------------------------------------------------------------------------
/event/event.go:
--------------------------------------------------------------------------------
1 | package ev
2 |
3 | // Event classes.
4 | // ev.Handler passes events as integers between goroutines. These integers are
5 | // not arbitrary and are selected by the caller. This allows the receiving
6 | // goroutine to select which events are relevant to it using simple arithmetic
7 | // and/or a switch case.
8 | const (
9 | Keystroke = iota
10 | Resize
11 | TrayMessage
12 | PlayerChanged
13 | DownloadChanged
14 | RequestShutdown
15 | )
16 |
--------------------------------------------------------------------------------
/event/handle.go:
--------------------------------------------------------------------------------
1 | package ev
2 |
3 | // Handler is a multiplexer over multiple subsystems waiting for events in
4 | // parallel. When an event is delivered from one subsystem, handler bounces the
5 | // message to all other listening handlers.
6 | //
7 | // Handler is thread safe, provided that handlers are only added in sequence
8 | // and it is only ever passed by value after initialisation completes.
9 | type Handler struct {
10 | msg chan int
11 | hndl []chan int
12 | }
13 |
14 | func NewHandler() *Handler {
15 | return &Handler{
16 | make(chan int, 1),
17 | make([]chan int, 0, 3),
18 | }
19 | }
20 |
21 | func (h Handler) Run() {
22 | for msg := range h.msg {
23 | for _, elem := range h.hndl {
24 | elem <- msg
25 | }
26 | }
27 | }
28 |
29 | func (h *Handler) Register() chan int {
30 | hndl := make(chan int, 1)
31 | h.hndl = append(h.hndl, hndl)
32 | return hndl
33 | }
34 |
35 | func (h Handler) Post(ev int) {
36 | h.msg <- ev
37 | }
38 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/ejv2/podbit
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/blang/mpv v0.0.0-20160810175505-d56d7352e068
7 | github.com/dhowden/tag v0.0.0-20201120070457-d52dcb253c63
8 | github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b
9 | github.com/vit1251/go-ncursesw v0.0.0-20211216195139-e61a3c4242a5
10 | github.com/vmarkovtsev/go-lcss v0.0.0-20181022055826-27bee2e750a5
11 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1
12 | )
13 |
14 | require (
15 | github.com/stretchr/testify v1.9.0 // indirect
16 | golang.org/x/sys v0.1.0 // indirect
17 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
18 | )
19 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/blang/mpv v0.0.0-20160810175505-d56d7352e068 h1:P3ukpA1t7dgNIfe21LpB+zIBDQ1Dik9K1DMPdO/TcUA=
2 | github.com/blang/mpv v0.0.0-20160810175505-d56d7352e068/go.mod h1:E3TTEJpVApQMkhVk3Lr0sAmcbcclY3pGgPbRsy+rdlk=
3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
4 | github.com/dhowden/tag v0.0.0-20201120070457-d52dcb253c63 h1:/u5RVRk3Nh7Zw1QQnPtUH5kzcc8JmSSRpHSlGU/zGTE=
5 | github.com/dhowden/tag v0.0.0-20201120070457-d52dcb253c63/go.mod h1:SniNVYuaD1jmdEEvi+7ywb1QFR7agjeTdGKyFb0p7Rw=
6 | github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b h1:FQ7+9fxhyp82ks9vAuyPzG0/vVbWwMwLJ+P6yJI5FN8=
7 | github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b/go.mod h1:HMcgvsgd0Fjj4XXDkbjdmlbI505rUPBs6WBMYg2pXks=
8 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
9 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
10 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
11 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
12 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
14 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
15 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
16 | github.com/vit1251/go-ncursesw v0.0.0-20211216195139-e61a3c4242a5 h1:38QNnaytR3Mhq0YO05IBNMImfFYQB2Tk5Ct/V1MWOwI=
17 | github.com/vit1251/go-ncursesw v0.0.0-20211216195139-e61a3c4242a5/go.mod h1:gTXTX4x80o63QC2qsY+NdlLgj+eiWKMwsY2YMZe6e44=
18 | github.com/vmarkovtsev/go-lcss v0.0.0-20181022055826-27bee2e750a5 h1:JMlKHhtxrLtEoDrzvluDg8Whac9lpCDjC2q+ANAZ20c=
19 | github.com/vmarkovtsev/go-lcss v0.0.0-20181022055826-27bee2e750a5/go.mod h1:MFFcz/mNHTQ7m0AaXNtnO8P3wv9wkcnBOLxR93EoIr0=
20 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
21 | golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
22 | golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
23 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
24 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
25 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
26 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
27 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
28 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "os"
7 | "os/signal"
8 | "path/filepath"
9 | "syscall"
10 | "time"
11 |
12 | "github.com/ejv2/podbit/colors"
13 | "github.com/ejv2/podbit/data"
14 | ev "github.com/ejv2/podbit/event"
15 | "github.com/ejv2/podbit/sound"
16 | "github.com/ejv2/podbit/ui"
17 |
18 | "github.com/juju/fslock"
19 | goncurses "github.com/vit1251/go-ncursesw"
20 | )
21 |
22 | const (
23 | homebase = "podbit"
24 | pidfile = "podbit.lock"
25 | )
26 |
27 | var (
28 | homedir string
29 | confdir string
30 |
31 | events *ev.Handler
32 | keystroke = make(chan rune)
33 | newMen = make(chan ui.Menu)
34 | exit = make(chan struct{})
35 | reload = make(chan int8)
36 | )
37 |
38 | // Flags.
39 | var (
40 | KeepPlayed = flag.Bool("nocleanup", false, "Disable cache cleanups and keep all finished items")
41 | PurgeQueue = flag.Bool("purge", false, "Purge finished items from the queue file as well as disk")
42 | )
43 |
44 | func banner() {
45 | fmt.Printf("Starting Podbit v%d.%d.%d...\n", verMaj, verMin, verPatch)
46 | }
47 |
48 | func initDirs() {
49 | share := os.Getenv("XDG_DATA_HOME")
50 | config, _ := os.UserConfigDir()
51 |
52 | if share == "" {
53 | share = ".local/share"
54 | }
55 |
56 | homedir = filepath.Join(share, homebase)
57 | confdir = filepath.Join(config, homebase)
58 |
59 | herr := os.MkdirAll(homedir, os.ModeDir|os.ModePerm)
60 | cerr := os.MkdirAll(confdir, os.ModeDir|os.ModePerm)
61 |
62 | if herr != nil || cerr != nil {
63 | fmt.Println("Error: Failed to create required directory(s)")
64 | os.Exit(1)
65 | }
66 | }
67 |
68 | func alreadyRunning() (bool, *fslock.Lock) {
69 | lockpath := filepath.Join(homedir, pidfile)
70 | lock := fslock.New(lockpath)
71 | err := lock.TryLock()
72 |
73 | if err != nil {
74 | return true, nil
75 | }
76 |
77 | return false, lock
78 | }
79 |
80 | func initColors() {
81 | if goncurses.HasColors() {
82 | goncurses.StartColor()
83 | }
84 |
85 | colors.CreateColors()
86 | }
87 |
88 | func initTTY() {
89 | goncurses.Raw(true)
90 | goncurses.Echo(false)
91 | goncurses.Cursor(0)
92 | }
93 |
94 | func initSignals(exit chan struct{}) {
95 | sigchan := make(chan os.Signal, 1)
96 | signal.Notify(sigchan, os.Interrupt, syscall.SIGTERM)
97 | go func() {
98 | <-sigchan
99 | exit <- struct{}{}
100 | }()
101 | }
102 |
103 | func main() {
104 | banner()
105 | flag.Parse()
106 | initDirs()
107 | initSignals(exit)
108 |
109 | running, lock := alreadyRunning()
110 | if running {
111 | fmt.Println("Error: Podbit is already running")
112 | os.Exit(1)
113 | }
114 | defer lock.Unlock()
115 |
116 | events = ev.NewHandler()
117 | now := time.Now()
118 | err := data.InitData(*events)
119 | if err != nil {
120 | fmt.Println("\n" + err.Error())
121 | return
122 | }
123 | defer data.SaveData()
124 | go data.ReloadLoop(reload)
125 |
126 | fmt.Print("Initialising sound system...")
127 | sound.Plr, err = sound.NewPlayer(events)
128 | if err != nil {
129 | fmt.Printf("\nError: Failed to initialise sound system: %s\n", err.Error())
130 | os.Exit(1)
131 | }
132 | fmt.Println("done")
133 |
134 | go sound.Mainloop()
135 | defer sound.Plr.Destroy()
136 |
137 | scr, err := goncurses.Init()
138 | if err != nil {
139 | fmt.Printf("Error: Failed to initialize UI: %s\n", err)
140 | os.Exit(1)
141 | }
142 | initTTY()
143 | initColors()
144 | defer goncurses.End()
145 |
146 | ui.InitUI(scr, ui.LibraryMenu, events, keystroke, newMen, reload)
147 | go ui.RenderLoop()
148 |
149 | // Welcome message
150 | startup := time.Since(now)
151 | go ui.StatusMessage(fmt.Sprintf("Podbit v%d.%d.%d -- %d episodes of %d podcasts loaded in %.2fs",
152 | verMaj,
153 | verMin,
154 | verPatch,
155 | len(data.Q.Items), len(data.Q.GetPodcasts()),
156 | startup.Seconds()))
157 |
158 | // Run events handler and kickstart listeners
159 | go events.Run()
160 | events.Post(ev.Keystroke)
161 |
162 | // Initialisation is done; use this thread as the input loop
163 | ui.InputLoop(exit)
164 | }
165 |
--------------------------------------------------------------------------------
/podbit.1:
--------------------------------------------------------------------------------
1 | .TH PODBIT 1
2 | .SH NAME
3 | podbit - play and download podcasts
4 | .SH SYNOPSIS
5 | .SY podbit
6 | .YS
7 | .SH DESCRIPTION
8 | .P
9 | .B Podbit
10 | reads the newsboat queue file for podcasts from RSS. Downloads will be completed
11 | in parallel. Once downloaded, audio files will be played using
12 | .B mpv
13 | in the background, with an
14 | .B ncmpcpp
15 | inspired user interface. Podcasts will be downloaded to your configured download
16 | directory via the newsboat configuration file. See
17 | .BR newsboat (1)
18 | .SH KEYBINDINGS
19 | .TP
20 | .B 1
21 | Show the player menu
22 | .TP
23 | .B 2
24 | Activate the queue menu
25 | .TP
26 | .B 3
27 | Activate the download menu
28 | .TP
29 | .B 4
30 | Activate the library menu
31 | .TP
32 | .B r
33 | Reload the queue file
34 | .TP
35 | .B p
36 | Pause/unpause
37 | .TP
38 | .B s
39 | Stop playing the current podcast
40 | .TP
41 | .B c
42 | Clear the queue
43 | .TP
44 | .B a
45 | Download all undownloaded
46 | .TP
47 | .B ]
48 | Seek forwards five seconds
49 | .TP
50 | .B [
51 | Seek backward five seconds
52 | .TP
53 | .B }
54 | Seek forwards one minute
55 | .TP
56 | .B {
57 | Seek backward one minute
58 | .TP
59 | .B Control-L
60 | Redraw the screen
61 | .TP
62 | .B q
63 | Quit
64 | .SH SEE ALSO
65 | .BR newsboat (1)
66 | .BR podboat (1)
67 | .BR mpv (1)
68 | .SH CREDITS
69 | Written by Ethan Marshall - 2021
70 | .SH BUGS
71 | Please report bugs to
72 | .UR https://github.com/ejv2/podbit/
73 | .UE
74 |
--------------------------------------------------------------------------------
/sound/queue.go:
--------------------------------------------------------------------------------
1 | package sound
2 |
3 | import (
4 | "sync"
5 |
6 | "github.com/ejv2/podbit/data"
7 | )
8 |
9 | // Singleton state.
10 | var (
11 | mut sync.RWMutex
12 |
13 | head int
14 | queue []*data.QueueItem
15 | )
16 |
17 | // Enqueue is the low-level enqueue routine.
18 | // Enqueues a raw QueueItem for playback.
19 | func Enqueue(item *data.QueueItem) {
20 | mut.Lock()
21 | defer mut.Unlock()
22 |
23 | queue = append(queue, item)
24 | }
25 |
26 | // EnqueueByURL searches data sources for episodes under
27 | // Remember to download before playing!
28 | // If you know episode is downloaded, use EnqueueByTitle - it's faster.
29 | func EnqueueByURL(url string) {
30 | item := data.Q.GetEpisodeByURL(url)
31 | if item != nil {
32 | Enqueue(item)
33 | }
34 | }
35 |
36 | // EnqueueByTitle searches data sources for episodes under the title .
37 | // Only the first match (if multiple are somehow present) is used.
38 | //
39 | // The availability of a title implies presence in cache, so don't bother to
40 | // download the episode.
41 | func EnqueueByTitle(title string) {
42 | item := data.Q.GetEpisodeByTitle(title)
43 | if item != nil {
44 | Enqueue(item)
45 | }
46 | }
47 |
48 | // EnqueueByPodcast bulk enqueues episodes by the name/url of their parent podcast .
49 | // Does not check or care about download status.
50 | //
51 | // If is empty or does not exist, no action is taken.
52 | //
53 | // If a url is provided, a lookup is performed to find the friendly name.
54 | // If a friendly name could not be found, the url is used instead.
55 | // If a friendly name is provided, no lookup is performed.
56 | func EnqueueByPodcast(ident string) {
57 | comp := data.DB.GetFriendlyName(ident)
58 |
59 | data.Q.Range(func(i int, elem *data.QueueItem) bool {
60 | name := data.DB.GetFriendlyName(elem.URL)
61 | if name == comp {
62 | Enqueue(data.Q.Items[i]) // Do not return: we are queueing in bulk
63 | }
64 |
65 | return true
66 | })
67 | }
68 |
69 | // JumpTo will force the head to the specified location.
70 | // If the new location is invalid, no action is taken.
71 | // After the jump, the player is instructed to play the
72 | // new head.
73 | func JumpTo(index int) {
74 | if index >= len(queue) {
75 | return
76 | }
77 |
78 | head = index
79 |
80 | Plr.Stop()
81 | }
82 |
83 | // PlayNow enqueues an episode and jumps to it, followed
84 | // by a call to the player to play the new head.
85 | func PlayNow(item *data.QueueItem) {
86 | Enqueue(item)
87 | JumpTo(len(queue) - 1)
88 | }
89 |
90 | // ClearQueue truncates the queue to zero items.
91 | func ClearQueue() {
92 | queue = queue[:0]
93 | head = 0
94 |
95 | Plr.Stop()
96 | }
97 |
98 | // Dequeue removes an item from the queue at index.
99 | // If index is invalid, no action is taken.
100 | func Dequeue(index int) {
101 | mut.Lock()
102 | defer mut.Unlock()
103 |
104 | if index >= len(queue) {
105 | return
106 | }
107 |
108 | var after []*data.QueueItem
109 | prior := queue[:index]
110 | if index < len(queue)-1 {
111 | after = queue[index+1:]
112 | } else {
113 | after = make([]*data.QueueItem, 0)
114 | }
115 |
116 | queue = append(prior, after...)
117 |
118 | if index == head-1 {
119 | Plr.Stop()
120 | head--
121 | }
122 |
123 | if index < head-1 && head > 0 {
124 | head--
125 | }
126 |
127 | // Catch all - prevent crashes from spurious deletes
128 | if head < 0 {
129 | head = 0
130 | }
131 | }
132 |
133 | // GetQueue returns the raw queue in QueueItem slice form
134 | // You should not edit the returned values, as this looses
135 | // all thread protection.
136 | func GetQueue() []*data.QueueItem {
137 | mut.RLock()
138 | defer mut.RUnlock()
139 |
140 | return queue
141 | }
142 |
143 | // PopHead returns the head of the queue, increasing
144 | // the head beyond the end (if present). The boolean returned
145 | // indicates if the player should stop - which occurs in the
146 | // case of the end of the queue or an empty queue.
147 | func PopHead() (*data.QueueItem, bool) {
148 | mut.Lock()
149 | defer mut.Unlock()
150 |
151 | if len(queue) > 0 {
152 | if head >= len(queue) {
153 | return nil, true
154 | }
155 |
156 | i := queue[head]
157 | head++
158 |
159 | return i, false
160 | }
161 |
162 | return nil, true
163 | }
164 |
165 | // GetHead returns the current queue item at the head of the
166 | // queue (playing) and the index into the queue. This function
167 | // does not pop any items (the head remains unchanged).
168 | func GetHead() (h *data.QueueItem, pos int) {
169 | mut.RLock()
170 | defer mut.RUnlock()
171 |
172 | if len(queue) > 0 && len(queue) > head-1 && head-1 >= 0 {
173 | pos = head - 1
174 | h = queue[pos]
175 | }
176 |
177 | return
178 | }
179 |
180 | // GetNext returns the item which is enqueued to play next
181 | // after the current entry has finished. If there is not an
182 | // item enqueued next, returns nil and -1.
183 | func GetNext() (*data.QueueItem, int) {
184 | if len(queue) > head {
185 | return queue[head], head
186 | }
187 |
188 | return nil, -1
189 | }
190 |
191 | // DownloadAtHead returns if the item next to play (before the head)
192 | // is the expected ongoing download. Used by the sound system to detect
193 | // download dequeues.
194 | func DownloadAtHead(expect *data.QueueItem) bool {
195 | mut.RLock()
196 | defer mut.RUnlock()
197 |
198 | return len(queue) != 0 && head-1 >= 0 && queue[head-1] == expect
199 | }
200 |
--------------------------------------------------------------------------------
/sound/sound.go:
--------------------------------------------------------------------------------
1 | // Package sound is responsible for playing audio and managing mpv instances
2 | //
3 | // This package is usually interacted with by the front-end UI code to add
4 | // items to the queue. The rest happens automatically using multi-threaded
5 | // player logic. All that needs to be maintained from the interface side is
6 | // the queue and the rest is run automatically.
7 | //
8 | // The queue is a simple FIFO structure formed from a slice of QueueEntries.
9 | // Entries that require downloading are handled gracefully and with as little
10 | // user impact as possible. Usually, the user won't even notice anything happened.
11 | //
12 | // Sound is played through an idle MPV instance which sits in the background and
13 | // receives media to play when appropriate
14 | package sound
15 |
16 | import (
17 | "fmt"
18 | "math"
19 | "os/exec"
20 | "time"
21 |
22 | "github.com/ejv2/podbit/data"
23 | ev "github.com/ejv2/podbit/event"
24 |
25 | "github.com/blang/mpv"
26 | )
27 |
28 | // Useful player vars.
29 | var (
30 | // PlayerName is the name of the player program to spawn.
31 | PlayerName = "mpv"
32 | // The path to the RPC endpoint.
33 | PlayerRPC = "/tmp/podbit-mpv"
34 | // PlayerArgs are the standard arguments to use for the player.
35 | // These are not the final configs of the player, but just used
36 | // to idle mpv ready to receive instructions.
37 | PlayerArgs = []string{"--idle", "--no-video", "--input-ipc-server=" + PlayerRPC}
38 | // UpdateTime is the time between queue checks and supervision updates.
39 | UpdateTime = 500 * time.Millisecond
40 | )
41 |
42 | // Internal: Types of actions.
43 | const (
44 | actPause = iota
45 | actUnpause
46 | actToggle
47 | actStop
48 | actTerm
49 | actSeek
50 |
51 | reqPaused
52 | reqPlaying
53 | reqWaiting
54 | reqTimings
55 | )
56 |
57 | // WaitFunc is the function to call waiting between each update.
58 | type WaitFunc func(u chan int)
59 |
60 | // Player represents the current player instance. This persists
61 | // after the media has completed playing and becomes ineffective
62 | // until the next call to play.
63 | type Player struct {
64 | proc *exec.Cmd
65 |
66 | hndl ev.Handler
67 | event chan int
68 | dlchan chan struct{}
69 |
70 | act chan int
71 | dat chan interface{}
72 |
73 | ipcc *mpv.IPCClient
74 | ctrl *mpv.Client
75 |
76 | waiting bool
77 | download *data.QueueItem
78 |
79 | exhausted bool
80 | playing bool
81 | manualStop bool
82 |
83 | Now *data.QueueItem
84 | NowPlaying string
85 | NowPodcast string
86 | }
87 |
88 | // Plr is the singleton player instance.
89 | var Plr Player
90 |
91 | func updateWait(u chan int) {
92 | time.Sleep(UpdateTime)
93 | u <- 1
94 | }
95 |
96 | func endWait(u chan int) {
97 | Plr.Wait()
98 | time.Sleep(time.Second)
99 |
100 | Plr.playing = false
101 | Plr.NowPlaying = ""
102 | Plr.NowPodcast = ""
103 |
104 | // Set state to finished
105 | data.Q.Range(func(_ int, item *data.QueueItem) bool {
106 | if item.Path == Plr.Now.Path {
107 | if !Plr.manualStop {
108 | item.State = data.StateFinished
109 |
110 | // We just played this fime so I reckon we can ignore
111 | // file not found errors.
112 | data.Stamps.Touch(item.Path)
113 | }
114 | return false
115 | }
116 |
117 | return true
118 | })
119 |
120 | Plr.manualStop = false
121 | Plr.hndl.Post(ev.PlayerChanged)
122 | u <- 1
123 | }
124 |
125 | func downloadWait(u chan int) {
126 | var id int
127 | for y := true; y && DownloadAtHead(Plr.download); y, id = data.Downloads.IsDownloading(Plr.download.Path) {
128 | <-Plr.dlchan
129 | }
130 |
131 | Plr.waiting = false
132 |
133 | dl := data.Downloads.GetDownload(id)
134 |
135 | // Only attempt to play if
136 | // a) still present
137 | // b) the download succeeded
138 | if DownloadAtHead(Plr.download) && dl.Success {
139 | head--
140 | }
141 |
142 | Plr.hndl.Post(ev.PlayerChanged)
143 | u <- 1
144 | }
145 |
146 | // NewPlayer constructs a new player. This does not yet
147 | // launch any processes or play any media.
148 | func NewPlayer(events *ev.Handler) (p Player, err error) {
149 | p.act = make(chan int)
150 | p.dat = make(chan interface{})
151 | p.dlchan = make(chan struct{}, 1)
152 |
153 | p.hndl = *events
154 | p.event = events.Register()
155 |
156 | return
157 | }
158 |
159 | // ConnectPlayer attempts to connect to the RPC endpoint
160 | // Sadly, this is needed because of an exceptionally bad
161 | // design choice in the mpv library forcing me to create
162 | // this bad workaround. :( .
163 | func (p *Player) connect() (err error) {
164 | defer func() {
165 | if r := recover(); r != nil {
166 | err = fmt.Errorf("Error: Player connection")
167 | }
168 | }()
169 |
170 | p.ipcc = mpv.NewIPCClient(PlayerRPC)
171 | p.ctrl = mpv.NewClient(p.ipcc)
172 |
173 | return
174 | }
175 |
176 | func (p *Player) start() {
177 | p.proc = exec.Command(PlayerName, PlayerArgs...)
178 | p.proc.Start()
179 |
180 | go p.procWatcher()
181 |
182 | for err := p.connect(); err != nil; {
183 | err = p.connect()
184 | }
185 | }
186 |
187 | func (p *Player) procWatcher() {
188 | p.proc.Wait()
189 | // Should mpv exit unexpectedly, we need to close the program
190 | // gracefully.
191 | p.hndl.Post(ev.RequestShutdown)
192 | }
193 |
194 | func (p *Player) load(filename string, starttime int) {
195 | if p.proc == nil || p.ctrl == nil {
196 | p.start()
197 | }
198 |
199 | p.ctrl.Loadfile(filename, mpv.LoadFileModeAppendPlay)
200 |
201 | // Wait for track to load
202 | for loaded := ""; loaded != "\""+filename+"\""; loaded, _ = p.ctrl.Path() {
203 | }
204 | for {
205 | pos, _ := p.ctrl.PercentPosition()
206 | if pos != 0 {
207 | break
208 | }
209 | }
210 |
211 | p.ctrl.Seek(starttime, mpv.SeekModeAbsolute)
212 | }
213 |
214 | func (p *Player) play(q *data.QueueItem) {
215 | _, s, err := data.Stamps.Stat(q.Path)
216 | if err != nil {
217 | tmp := uint64(0)
218 | s = &tmp
219 | }
220 | if *s > uint64(math.MaxInt) {
221 | tmp := uint64(math.MaxInt)
222 | s = &tmp
223 | }
224 |
225 | p.load(q.Path, int(*s))
226 |
227 | if q.State != data.StatePending {
228 | Plr.Now = q
229 |
230 | now, ok := data.Downloads.Query(q.Path)
231 | if !ok {
232 | p.NowPlaying = ""
233 | p.NowPodcast = ""
234 | }
235 |
236 | if now.Title == "" {
237 | p.NowPlaying = q.URL
238 | } else {
239 | p.NowPlaying = now.Title
240 | }
241 |
242 | p.NowPodcast = data.DB.GetFriendlyName(q.URL)
243 |
244 | p.playing = true
245 | p.unpause()
246 | }
247 | }
248 |
249 | // Stop ends playback of the current audio track, but does not
250 | // destroy the sound mainloop. This will usually result in the
251 | // next podcast playing.
252 | func (p *Player) Stop() {
253 | p.act <- actStop
254 | }
255 |
256 | func (p *Player) stop() {
257 | if !p.playing {
258 | return
259 | }
260 |
261 | Plr.NowPlaying = ""
262 | Plr.NowPodcast = ""
263 | p.manualStop = true
264 |
265 | pos, err := p.ctrl.Position()
266 | if err == nil {
267 | data.Stamps.Resume(p.Now.Path, uint64(pos))
268 | }
269 |
270 | p.ctrl.Exec("stop")
271 | p.playing = false
272 | }
273 |
274 | // Destroy forces the current player instance to terminate and destroys
275 | // the sound mainloop.
276 | // Blocks until the process is guaranteed destroyed.
277 | func (p *Player) Destroy() {
278 | p.act <- actTerm
279 | <-p.dat
280 | }
281 |
282 | // IsPaused requests the sound mainloop to return if it is paused. If
283 | // the mainloop is not playing, this function returns false. If the mainloop
284 | // is busy or processing audio, this function blocks until the mainloop is
285 | // ready.
286 | func (p *Player) IsPaused() bool {
287 | p.act <- reqPaused
288 |
289 | r := <-p.dat
290 | return r.(bool)
291 | }
292 |
293 | func (p *Player) isPaused() bool {
294 | if !p.playing {
295 | return false
296 | }
297 |
298 | paused, _ := p.ctrl.Pause()
299 | return paused
300 | }
301 |
302 | // IsPlaying requests that the sound mainloop return if it is currently
303 | // playing audio. If the mainloop is busy or processing audio, this function
304 | // blocks until the mainloop is ready.
305 | func (p *Player) IsPlaying() bool {
306 | p.act <- reqPlaying
307 |
308 | r := <-p.dat
309 | return r.(bool)
310 | }
311 |
312 | func (p *Player) isPlaying() bool {
313 | return p.playing
314 | }
315 |
316 | // IsWaiting checks if the mainloop is waiting on an episode to download
317 | // before playing it.
318 | func (p *Player) IsWaiting() bool {
319 | p.act <- reqWaiting
320 |
321 | r := <-p.dat
322 | return r.(bool)
323 | }
324 |
325 | func (p *Player) isWaiting() bool {
326 | return p.waiting
327 | }
328 |
329 | // Pause will stop audio playback, but preserve the position in the audio and
330 | // queue. Will block until this is complete. Has no effect if not playing.
331 | func (p *Player) Pause() {
332 | p.act <- actPause
333 | }
334 |
335 | func (p *Player) pause() {
336 | if !p.playing {
337 | return
338 | }
339 |
340 | // Leave playing set to true so we know not to play another episode
341 | p.ctrl.SetPause(true)
342 | }
343 |
344 | // Unpause will restore the position into the audio and queue from a pause
345 | // and resume playback. Will block until this is complete. Has no effect if
346 | // not paused or playing.
347 | func (p *Player) Unpause() {
348 | p.act <- actUnpause
349 | }
350 |
351 | func (p *Player) unpause() {
352 | if !p.playing {
353 | return
354 | }
355 |
356 | // Leave playing set to true so we know not to play another episode
357 | p.ctrl.SetPause(false)
358 | }
359 |
360 | // Toggle pauses if the mainloop is unpaused, otherwise unpauses.
361 | func (p *Player) Toggle() {
362 | p.act <- actToggle
363 | }
364 |
365 | func (p *Player) toggle() {
366 | if !p.playing {
367 | return
368 | }
369 |
370 | paused, _ := p.ctrl.Pause()
371 | p.ctrl.SetPause(!paused)
372 | }
373 |
374 | // GetTimings returns the current time and duration
375 | // of the ongoing player. Returns zero if we are
376 | // not playing currently.
377 | //
378 | // This function is thread safe but may block until
379 | // data is available.
380 | func (p *Player) GetTimings() (float64, float64) {
381 | p.act <- reqTimings
382 |
383 | dat := (<-p.dat).([2]float64)
384 | return dat[0], dat[1]
385 | }
386 |
387 | func (p *Player) getTimings() (float64, float64) {
388 | if !p.playing {
389 | return 0, 0
390 | }
391 |
392 | pos, _ := p.ctrl.Position()
393 | dur, _ := p.ctrl.Duration()
394 |
395 | return pos, dur
396 | }
397 |
398 | // Seek moves the player head relative to the current
399 | // position.
400 | func (p *Player) Seek(off int) {
401 | p.act <- actSeek
402 | p.dat <- off
403 | }
404 |
405 | func (p *Player) seek(off int) {
406 | if !p.playing {
407 | return
408 | }
409 |
410 | p.ctrl.Seek(off, mpv.SeekModeRelative)
411 | }
412 |
413 | // Wait for the current episode to complete.
414 | func (p *Player) Wait() {
415 | if !p.playing {
416 | return
417 | }
418 |
419 | now, _ := p.ctrl.Filename()
420 | for filename := now; filename == now; filename, _ = p.ctrl.Filename() {
421 | if !p.isPaused() {
422 | p.hndl.Post(ev.PlayerChanged)
423 | }
424 | time.Sleep(UpdateTime)
425 | }
426 | }
427 |
428 | func (p *Player) Event(e int) {
429 | switch e {
430 | case ev.DownloadChanged:
431 | select {
432 | case p.dlchan <- struct{}{}:
433 | default:
434 | }
435 | }
436 | }
437 |
438 | // Mainloop - Main sound handling thread loop
439 | //
440 | // Loops infinitely waiting for sound events, managing the queue, mpv
441 | // processes and player data handling. Can be communicated with through
442 | // a series of channels indicating different actions.
443 | func Mainloop() {
444 | var wait WaitFunc
445 | var elem *data.QueueItem
446 | u := make(chan int)
447 |
448 | for {
449 | wait = updateWait
450 | elem, Plr.exhausted = PopHead()
451 |
452 | if !Plr.playing && !Plr.waiting && !Plr.exhausted && len(queue) > 0 {
453 | if elem.State != data.StatePending && data.Downloads.EntryExists(elem.Path) {
454 | elem.Lock()
455 |
456 | Plr.play(elem)
457 | wait = endWait
458 |
459 | // Set status to played
460 | elem.State = data.StatePlayed
461 | data.Stamps.Touch(elem.Path)
462 |
463 | elem.Unlock()
464 | } else {
465 | Plr.waiting = true
466 |
467 | elem.RLock()
468 | if y, _ := data.Downloads.IsDownloading(elem.Path); y {
469 | Plr.download = elem
470 | } else {
471 |
472 | _, err := data.Downloads.Download(elem)
473 | if err != nil {
474 | continue
475 | }
476 |
477 | Plr.download = elem
478 | }
479 |
480 | elem.RUnlock()
481 | wait = downloadWait
482 | }
483 | }
484 |
485 | go wait(u)
486 | keepWaiting := true
487 | for keepWaiting {
488 | select {
489 | case <-u:
490 | keepWaiting = false
491 | case e := <-Plr.event:
492 | Plr.Event(e)
493 | case action := <-Plr.act:
494 | switch action {
495 | case actTerm:
496 | if Plr.proc != nil {
497 | Plr.stop()
498 | Plr.proc.Process.Kill()
499 | }
500 |
501 | Plr.dat <- 1
502 | return
503 | case actStop:
504 | Plr.stop()
505 | case actPause:
506 | Plr.pause()
507 | case actUnpause:
508 | Plr.unpause()
509 | case actToggle:
510 | Plr.toggle()
511 | case actSeek:
512 | dat := <-Plr.dat
513 | Plr.seek(dat.(int))
514 |
515 | case reqPaused:
516 | Plr.dat <- Plr.isPaused()
517 | case reqPlaying:
518 | Plr.dat <- Plr.isPlaying()
519 | case reqWaiting:
520 | Plr.dat <- Plr.isWaiting()
521 | case reqTimings:
522 | d, p := Plr.getTimings()
523 | arr := [2]float64{d, p}
524 |
525 | Plr.dat <- arr
526 | }
527 | }
528 | }
529 | }
530 | }
531 |
--------------------------------------------------------------------------------
/ss.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ejv2/podbit/c3251defef01b306fc6bf5a92f393e7c1a2bb184/ss.png
--------------------------------------------------------------------------------
/ui/components/doc.go:
--------------------------------------------------------------------------------
1 | // Package components implements re-usable sections of UI which can be
2 | // used by multiple sections of the program in multiple different ways.
3 | //
4 | // They are designed to be as self-contained and as simple to use as
5 | // possible, with immediate-mode UI used as a reference model.
6 | //
7 | // As a general rule, it is safe to assume that none of this package is
8 | // thread-safe, as it is only really designed for use by the UI thread.
9 | // That being said, there is nothing stopping you from connecting some
10 | // methods up to channel listeners or just locking the UI using a mutex
11 | // either.
12 | package components
13 |
--------------------------------------------------------------------------------
/ui/components/list.go:
--------------------------------------------------------------------------------
1 | package components
2 |
3 | // A Selecter represents any object which has a visibly selected
4 | // element and which is capable of changing said element.
5 | type Selecter interface {
6 | GetSelection() (int, interface{})
7 | ChangeSelection(index int)
8 | MoveSelection(offset int)
9 | }
10 |
11 | // List represents a generic component which contains elements
12 | // of an arbitrary type. The list can be scrolled and has an
13 | // associated selected element.
14 | type List[Item any] struct {
15 | W, H int
16 | Items []Item
17 |
18 | scroll int
19 | sel int
20 | }
21 |
22 | // GetSelection returns the currently selected menu element, or
23 | // nil if none is selected.
24 | func (l *List[Item]) GetSelection() (int, Item) {
25 | if len(l.Items) < 1 {
26 | return 0, *new(Item)
27 | }
28 |
29 | return l.sel, l.Items[l.sel]
30 | }
31 |
32 | // ChangeSelection changes the selection to the index specified.
33 | // If index is out of range, no action is taken.
34 | func (l *List[Item]) ChangeSelection(index int) {
35 | if index >= len(l.Items) || index < 0 {
36 | return
37 | }
38 |
39 | l.sel = index
40 |
41 | scrollAt := l.H + l.scroll + 1
42 | underscrollAt := l.scroll - 1
43 | if l.sel >= scrollAt {
44 | l.scroll += (l.sel - scrollAt) + 1
45 | } else if l.sel <= underscrollAt {
46 | l.scroll = l.sel
47 | }
48 | }
49 |
50 | // MoveSelection changes the selected item relative to the current
51 | // position. If the new selection would be out of range, no action
52 | // is taken.
53 | func (l *List[Item]) MoveSelection(offset int) {
54 | off := l.sel + offset
55 | l.ChangeSelection(off)
56 | }
57 |
--------------------------------------------------------------------------------
/ui/components/menu.go:
--------------------------------------------------------------------------------
1 | package components
2 |
3 | import (
4 | "github.com/ejv2/podbit/colors"
5 | "github.com/vit1251/go-ncursesw"
6 | )
7 |
8 | // Menu represents a vertical panel menu of cellular entries
9 | // taking up an entire row from X to W
10 | //
11 | // Menu handles focus, scrolling and the managing of elements
12 | // at each render.
13 | type Menu struct {
14 | X, Y int
15 | Win goncurses.Window
16 |
17 | Selected bool
18 | prevw, prevh int
19 |
20 | List[string]
21 | }
22 |
23 | // Render immediately renders the menu to the specified
24 | // fields X, Y, H and W.
25 | func (m *Menu) Render() {
26 | // Reset scroll if invalid or not selected
27 | if len(m.Items) <= m.scroll || !m.Selected {
28 | m.scroll = 0
29 | m.sel = 0
30 | }
31 |
32 | items := m.Items[m.scroll:]
33 | c := m.scroll
34 |
35 | if m.prevw != m.W || m.prevh != m.H {
36 | m.scroll = 0
37 | }
38 | m.prevw, m.prevh = m.W, m.H
39 |
40 | if m.scroll+m.H < m.sel {
41 | m.sel = m.H
42 | }
43 |
44 | for i, elem := range items {
45 | if c == m.sel && m.Selected {
46 | m.Win.ColorOn(colors.BackgroundBlue)
47 | } else if i > m.H {
48 | break
49 | }
50 |
51 | capped, decode := elem, []rune(elem)
52 | if len(decode) > m.W {
53 | capped = string(decode[len(decode)-m.W:])
54 | capped = "<" + capped
55 | } else {
56 | // Pad out to fill row
57 | for i := len(decode); i <= m.W; i++ {
58 | capped += " "
59 | }
60 | }
61 |
62 | m.Win.MovePrint(m.Y+i, m.X, capped)
63 | c++
64 |
65 | m.Win.ColorOff(colors.BackgroundBlue)
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/ui/components/table.go:
--------------------------------------------------------------------------------
1 | package components
2 |
3 | import (
4 | "github.com/ejv2/podbit/colors"
5 | "github.com/ejv2/podbit/data"
6 |
7 | "github.com/vit1251/go-ncursesw"
8 | )
9 |
10 | // A Column is a vertical section of a table, defined by a
11 | // pair of both a "width" and a "label".
12 | //
13 | // The width is the fraction of the table width the column
14 | // should take up (defined between zero and one). Table's
15 | // render method will panic if any column has a "width"
16 | // of less than zero or greater than one, or if an impossible
17 | // combination of widths was requested.
18 | //
19 | // The width is the label which will be displayed at the top of the table.
20 | // The color is the ncurses color to activate when selected.
21 | type Column struct {
22 | Label string
23 | Width float64
24 | Color int16
25 | }
26 |
27 | // Table represents a vertical, headed table structure, useful
28 | // for displaying a slice of structs.
29 | type Table struct {
30 | X, Y int
31 | Win *goncurses.Window
32 |
33 | // See column struct for docs
34 | Columns []Column
35 | // Each slice represents each column entry (eg, 0 = first column)
36 | List[[]string]
37 |
38 | prevw, prevh int
39 | prevlen int
40 | }
41 |
42 | // Render immediately renders the table to the requested coords X and Y
43 | // with the space taken up limited to the space W*H.
44 | func (t *Table) Render() {
45 | // Reduce height to be actual usable space (minus headings)
46 | t.H -= 2
47 |
48 | items := t.Items[t.scroll:]
49 | if t.prevw != t.W || t.prevh != t.H {
50 | t.scroll = 0
51 | }
52 | if t.scroll+t.H < t.sel {
53 | t.sel = t.H
54 | }
55 | if t.sel < 0 {
56 | t.sel = 0
57 | }
58 | if t.sel > len(t.Items)-1 {
59 | t.sel = len(t.Items) - 1
60 | }
61 | t.prevw, t.prevh = t.W, t.H
62 | t.prevlen = len(t.Items)
63 |
64 | t.Win.AttrOn(goncurses.A_BOLD)
65 | t.Win.HLine(t.Y+1, t.X, goncurses.ACS_HLINE, t.W)
66 | t.Win.AttrOff(goncurses.A_BOLD)
67 |
68 | off := 0
69 | for i, elem := range t.Columns {
70 | colw := int(float64(t.W) * elem.Width)
71 | if off > t.W || colw > t.W {
72 | panic("invalid table header: impossible column width")
73 | }
74 |
75 | elem.Label = data.LimitString(elem.Label, colw)
76 |
77 | t.Win.AttrOn(goncurses.A_BOLD)
78 | t.Win.MovePrint(t.Y, t.X+off, elem.Label)
79 | t.Win.AttrOff(goncurses.A_BOLD)
80 |
81 | c := t.scroll
82 | for j, entry := range items {
83 | if i >= len(entry) {
84 | panic("invalid table entry: missing fields")
85 | } else if j > t.H {
86 | break
87 | }
88 |
89 | capped := entry[i]
90 | sel := c == t.sel
91 |
92 | capped = data.LimitString(capped, colw-1)
93 | decode := []rune(capped)
94 |
95 | // Pad out to fill row
96 | for i := len(decode); i < colw && off+len(decode) < t.W; i++ {
97 | capped += " "
98 | }
99 |
100 | if sel {
101 | t.Win.ColorOn(elem.Color)
102 | } else {
103 | t.Win.ColorOn(colors.ToForeground(elem.Color))
104 | }
105 |
106 | t.Win.MovePrint(t.Y+j+2, t.X+off, capped)
107 |
108 | if sel {
109 | t.Win.ColorOff(elem.Color)
110 | } else {
111 | t.Win.ColorOff(colors.ToForeground(elem.Color))
112 | }
113 |
114 | c++
115 | }
116 |
117 | off += colw
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/ui/download.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 |
7 | "github.com/ejv2/podbit/colors"
8 | "github.com/ejv2/podbit/data"
9 | ev "github.com/ejv2/podbit/event"
10 | "github.com/ejv2/podbit/sound"
11 | "github.com/ejv2/podbit/ui/components"
12 | )
13 |
14 | var downloadHeadings []components.Column = []components.Column{
15 | {
16 | Label: "ID",
17 | Width: 0.1,
18 | Color: colors.BackgroundGreen,
19 | },
20 | {
21 | Label: "%",
22 | Width: 0.1,
23 | Color: colors.BackgroundYellow,
24 | },
25 | {
26 | Label: "Episode",
27 | Width: 0.4,
28 | Color: colors.BackgroundBlue,
29 | },
30 | {
31 | Label: "Status",
32 | Width: 0.4,
33 | Color: colors.BackgroundRed,
34 | },
35 | }
36 |
37 | type Downloads struct {
38 | tbl components.Table
39 | }
40 |
41 | func (q *Downloads) Name() string {
42 | return "Downloads"
43 | }
44 |
45 | func (q *Downloads) Render(x, y int) {
46 | q.tbl.X, q.tbl.Y = x, y
47 | q.tbl.W, q.tbl.H = w, h-5
48 | q.tbl.Win = root
49 |
50 | q.tbl.Columns = downloadHeadings
51 |
52 | q.tbl.Items = nil
53 | for i, elem := range data.Downloads.Downloads() {
54 | item := make([]string, len(downloadHeadings))
55 |
56 | item[0] = strconv.FormatInt(int64(i), 10)
57 | item[1] = strconv.FormatFloat(elem.Percentage*100, 'f', 2, 64)
58 |
59 | ep, ok := data.Downloads.Query(elem.Path)
60 | if ok {
61 | item[2] = ep.Title
62 | } else {
63 | item[2] = elem.Path
64 | }
65 |
66 | if elem.Completed {
67 | if elem.Success {
68 | item[3] = "Finished"
69 | } else {
70 | item[3] = fmt.Sprintf("Failed (%s)", elem.Error)
71 | }
72 | } else {
73 | if elem.Elem.Youtube && elem.Percentage == 1 {
74 | item[3] = "Encoding"
75 | } else {
76 | item[3] = "In progress"
77 | }
78 | }
79 |
80 | q.tbl.Items = append(q.tbl.Items, item)
81 | }
82 |
83 | q.tbl.Render()
84 | }
85 |
86 | func (q *Downloads) Should(event int) bool {
87 | return event == ev.Keystroke || event == ev.DownloadChanged || event == ev.PlayerChanged
88 | }
89 |
90 | func (q *Downloads) Input(c rune) {
91 | switch c {
92 | case 'j':
93 | q.tbl.MoveSelection(1)
94 | case 'k':
95 | q.tbl.MoveSelection(-1)
96 | case 'g':
97 | q.tbl.ChangeSelection(0)
98 | case 'G':
99 | q.tbl.ChangeSelection(len(q.tbl.Items) - 1)
100 | case 'd':
101 | q.Cancel()
102 | case 13:
103 | q.Enqueue()
104 | }
105 | }
106 |
107 | func (q *Downloads) Enqueue() {
108 | i, _ := q.tbl.GetSelection()
109 | d := data.Downloads.Downloads()[i].Path
110 |
111 | var found *data.QueueItem
112 | data.Q.Range(func(i int, item *data.QueueItem) bool {
113 | if item.Path == d {
114 | found = item
115 | return false
116 | }
117 |
118 | return true
119 | })
120 |
121 | if found != nil {
122 | go StatusMessage("Enqueued: Download will play once completed")
123 | sound.Enqueue(found)
124 | }
125 |
126 | q.tbl.MoveSelection(1)
127 | }
128 |
129 | func (q *Downloads) Cancel() {
130 | i, _ := q.tbl.GetSelection()
131 | if i >= len(data.Downloads.Downloads()) {
132 | return
133 | }
134 |
135 | dl := data.Downloads.Downloads()[i]
136 | if !dl.Completed {
137 | go func() {
138 | dl.Stop <- 1
139 | go StatusMessage("Download cancelled")
140 | }()
141 | } else {
142 | go StatusMessage("Cannot cancel completed download")
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/ui/input.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "unicode/utf8"
7 |
8 | "github.com/ejv2/podbit/data"
9 | ev "github.com/ejv2/podbit/event"
10 | "github.com/ejv2/podbit/sound"
11 | )
12 |
13 | var (
14 | exitChan chan struct{}
15 | )
16 |
17 | func getInput(out chan rune, errc chan error) {
18 | var buf [4]byte
19 | var err error
20 |
21 | _, err = os.Stdin.Read(buf[:])
22 | if err != nil {
23 | errc <- err
24 | out <- 0x0
25 | }
26 |
27 | c, _ := utf8.DecodeRune(buf[:])
28 |
29 | errc <- nil
30 | out <- c
31 | }
32 |
33 | // Exit requests that the input handler shuts down and gracefully
34 | // exits the program via a return to the main function.
35 | func Exit() {
36 | close(exitChan)
37 | }
38 |
39 | // InputLoop - main UI input handler
40 | //
41 | // Receives all key inputs serially, one character at a time
42 | // If there is no global keybinding for this key, we pass it
43 | // to the UI subsystem, which can deal with it from there.
44 | //
45 | // Any and all key inputs causes an immediate and full UI redraw.
46 | func InputLoop(exit chan struct{}) {
47 | exitChan = exit
48 |
49 | var c rune
50 | var char = make(chan rune)
51 | var err = make(chan error, 1)
52 |
53 | for {
54 | go getInput(char, err)
55 |
56 | select {
57 | case c = <-char:
58 | if <-err != nil {
59 | return
60 | }
61 |
62 | switch c {
63 |
64 | case '1':
65 | ActivateMenu(PlayerMenu)
66 | case '2':
67 | ActivateMenu(QueueMenu)
68 | case '3':
69 | ActivateMenu(DownloadMenu)
70 | case '4':
71 | ActivateMenu(LibraryMenu)
72 | case 'r':
73 | go func() {
74 | reload <- data.DataReload
75 | StatusMessage("Queue file reloaded")
76 | }()
77 | case 'R':
78 | go func() {
79 | reload <- data.DataSave
80 | StatusMessage("Queue file saved")
81 | }()
82 | case 'p':
83 | sound.Plr.Toggle()
84 | case 's':
85 | sound.Plr.Stop()
86 | case 'c':
87 | sound.ClearQueue()
88 | case 'a':
89 | pending := data.Q.GetByStatus(data.StatePending)
90 | for _, elem := range pending {
91 | go data.Downloads.Download(elem)
92 | }
93 |
94 | msg := fmt.Sprintf("Downloading %d episodes in parallel", len(pending))
95 | go StatusMessage(msg)
96 | case ']':
97 | sound.Plr.Seek(5)
98 | case '[':
99 | sound.Plr.Seek(-5)
100 | case '}':
101 | sound.Plr.Seek(60)
102 | case '{':
103 | sound.Plr.Seek(-60)
104 | case '\f': // Control-L
105 | root.Clear()
106 | UpdateDimensions(root)
107 | case 'q':
108 | if data.Downloads.Ongoing() == 0 {
109 | return
110 | }
111 |
112 | StatusMessage("Error: Cannot quit with ongoing downloads")
113 | default:
114 | PassKeystroke(c)
115 | }
116 |
117 | eventsHndl.Post(ev.Keystroke)
118 | case <-exit:
119 | return
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/ui/library.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/ejv2/podbit/data"
7 | ev "github.com/ejv2/podbit/event"
8 | "github.com/ejv2/podbit/sound"
9 | "github.com/ejv2/podbit/ui/components"
10 |
11 | goncurses "github.com/vit1251/go-ncursesw"
12 | )
13 |
14 | // Library represents the list menu type and state.
15 | //
16 | // Library displays all detected and configured podcasts, along
17 | // with associated episodes sorted into said podcasts.
18 | type Library struct {
19 | men [2]components.Menu
20 |
21 | menSel int
22 | }
23 |
24 | func (l *Library) Name() string {
25 | return "Library"
26 | }
27 |
28 | func (l *Library) renderPodcasts(x, y int) {
29 | l.men[0].X = x
30 | l.men[0].Y = y
31 |
32 | l.men[0].W, l.men[0].H = (w/2)-1, (h - 5)
33 | l.men[0].Win = *root
34 |
35 | pods := data.DB.GetPodcastNames()
36 | fpods := make([]string, 0, len(pods))
37 | for _, pod := range pods {
38 | if len(data.Q.GetPodcastEpisodes(pod)) != 0 {
39 | fpods = append(fpods, pod)
40 | }
41 | }
42 | l.men[0].Items = fpods
43 |
44 | l.men[0].Selected = true
45 |
46 | if len(l.men[0].Items) > 0 {
47 | l.men[0].Render()
48 | } else {
49 | root.MovePrint(y, x, "No podcasts")
50 | }
51 | }
52 |
53 | func (l *Library) renderEpisodes(x, y int) {
54 | if len(l.men[0].Items) < 1 {
55 | return
56 | }
57 |
58 | l.men[1].X = x
59 | l.men[1].Y = y
60 |
61 | l.men[1].W, l.men[1].H = (w/2)-2, (h - 5)
62 | l.men[1].Win = *root
63 |
64 | l.men[1].Items = l.men[1].Items[:0]
65 |
66 | _, pod := l.men[0].GetSelection()
67 | eps := data.Q.GetPodcastEpisodes(pod)
68 |
69 | for i := len(eps) - 1; i >= 0; i-- {
70 | ep := eps[i]
71 | ep.RLock()
72 |
73 | text := ""
74 |
75 | entry, ok := data.Downloads.Query(ep.Path)
76 | title := entry.Title
77 | if !ok || title == "" {
78 | text = ep.URL
79 | } else {
80 | text = title
81 | }
82 |
83 | l.men[1].Items = append(l.men[1].Items, text)
84 | ep.RUnlock()
85 | }
86 |
87 | l.men[1].Selected = (l.menSel == 1)
88 |
89 | l.men[1].Render()
90 | }
91 |
92 | func (l *Library) Render(x, y int) {
93 | l.renderPodcasts(x, y)
94 |
95 | root.AttrOn(goncurses.A_BOLD)
96 | root.VLine(y, w/2, goncurses.ACS_VLINE, h-2-y)
97 | root.AttrOff(goncurses.A_BOLD)
98 |
99 | l.renderEpisodes(w/2+1, y)
100 | }
101 |
102 | func (l *Library) Should(event int) bool {
103 | return event == ev.Keystroke
104 | }
105 |
106 | func (l *Library) Input(c rune) {
107 | switch c {
108 | case 'j':
109 | l.men[l.menSel].MoveSelection(1)
110 | case 'k':
111 | l.men[l.menSel].MoveSelection(-1)
112 | case 'h':
113 | l.MoveSelection(-1)
114 | case 'l':
115 | l.MoveSelection(1)
116 | case 'g':
117 | l.men[l.menSel].ChangeSelection(0)
118 | case 'G':
119 | l.men[l.menSel].ChangeSelection(len(l.men[l.menSel].Items) - 1)
120 | case ' ':
121 | l.StartDownload()
122 | case 13:
123 | l.StartPlaying(false) // Enter key - enqueue
124 | case '\t':
125 | l.StartPlaying(true) // Tab key - play NOW!
126 | }
127 | }
128 |
129 | func (l *Library) ChangeSelection(index int) {
130 | if index >= len(l.men) || index < 0 {
131 | return
132 | }
133 |
134 | l.menSel = index
135 |
136 | if l.menSel == 0 {
137 | l.men[1].ChangeSelection(0)
138 | }
139 | }
140 |
141 | func (l *Library) MoveSelection(direction int) {
142 | if direction == 0 {
143 | return
144 | }
145 |
146 | off := l.menSel + direction
147 | l.ChangeSelection(off)
148 | }
149 |
150 | // StartDownload downloads the currently focused library entry.
151 | func (l *Library) StartDownload() {
152 | if len(l.men[0].Items) < 1 || len(l.men[1].Items) < 1 {
153 | return
154 | }
155 |
156 | defer func() {
157 | // Move cursor down
158 | l.men[l.menSel].MoveSelection(1)
159 | }()
160 |
161 | targets := l.men[1].Items
162 | if l.menSel == 1 {
163 | _, target := l.men[1].GetSelection()
164 | item := data.Q.GetEpisodeByURL(target)
165 |
166 | if item == nil {
167 | return
168 | }
169 |
170 | item.RLock()
171 | defer item.RUnlock()
172 | if y, _ := data.Downloads.IsDownloading(item.Path); y {
173 | go StatusMessage("Episode already downloading")
174 | return
175 | }
176 |
177 | data.Downloads.Download(item)
178 | go StatusMessage(fmt.Sprintf("Download of %s started...", item.URL))
179 |
180 | return
181 | }
182 |
183 | for _, elem := range targets {
184 | if data.IsURL(elem) {
185 | item := data.Q.GetEpisodeByURL(elem)
186 | if item == nil {
187 | continue
188 | }
189 |
190 | item.RLock()
191 | if y, _ := data.Downloads.IsDownloading(item.Path); y {
192 | go StatusMessage("Episode already downloading")
193 | return
194 | }
195 | item.RUnlock()
196 |
197 | go data.Downloads.Download(item)
198 | }
199 | }
200 |
201 | go StatusMessage("Download of multiple episodes started...")
202 | }
203 |
204 | // StartPlaying begins playing the currently focused element.
205 | // If the current focus requires downloading (and enough information
206 | // is known to oblige) it will first be downloaded.
207 | func (l *Library) StartPlaying(immediate bool) {
208 | if len(l.men[0].Items) < 1 || len(l.men[1].Items) < 1 {
209 | return
210 | }
211 |
212 | defer func() {
213 | // Move cursor down
214 | l.men[l.menSel].MoveSelection(1)
215 | }()
216 |
217 | if l.menSel == 1 {
218 | var item *data.QueueItem
219 | _, entry := l.men[1].GetSelection()
220 | if data.IsURL(entry) {
221 | item = data.Q.GetEpisodeByURL(entry)
222 | } else {
223 | item = data.Q.GetEpisodeByTitle(entry)
224 | }
225 |
226 | if immediate {
227 | go StatusMessage(fmt.Sprintf("Now playing episode %q", entry))
228 | sound.PlayNow(item)
229 | } else {
230 | go StatusMessage(fmt.Sprintf("Enqueued episode %q to play", entry))
231 | sound.Enqueue(item)
232 | }
233 |
234 | } else {
235 | if immediate {
236 | return
237 | }
238 |
239 | _, entry := l.men[0].GetSelection()
240 | sound.EnqueueByPodcast(entry)
241 | go StatusMessage("Multiple episodes enqueued...")
242 | }
243 | }
244 |
--------------------------------------------------------------------------------
/ui/player.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "math"
5 |
6 | "github.com/ejv2/podbit/colors"
7 | "github.com/ejv2/podbit/data"
8 | ev "github.com/ejv2/podbit/event"
9 | "github.com/ejv2/podbit/sound"
10 |
11 | "github.com/vit1251/go-ncursesw"
12 | )
13 |
14 | // Player is the full screen player component.
15 | //
16 | // Player displays the currently playing episode, the next up
17 | // episode, progress through the episode etc.
18 | //
19 | // This is mostly for user convenience and visual appeal.
20 | type Player struct{}
21 |
22 | func (l *Player) Name() string {
23 | return "Now playing"
24 | }
25 |
26 | func (l *Player) Render(x, y int) {
27 | pos, dur := sound.Plr.GetTimings()
28 | percent := pos / dur
29 | p, d := data.FormatTime(pos), data.FormatTime(dur)
30 | ep, pod := data.LimitString(sound.Plr.NowPlaying, w-1), data.LimitString(sound.Plr.NowPodcast, w-1)
31 |
32 | minxt := int(math.Max(0, float64((w-len([]rune(ep)))/2)))
33 | minxp := int(math.Max(0, float64((w-len([]rune(pod)))/2)))
34 |
35 | var stat, div string
36 | if sound.Plr.IsPlaying() {
37 | stat = "Now Playing: "
38 | div = "by"
39 | } else {
40 | stat = "Not playing"
41 | div = ""
42 | }
43 |
44 | // Now playing
45 | root.ColorOn(colors.ColorRed)
46 | root.MovePrint(x+4, (w-len(stat))/2, stat)
47 | root.ColorOff(colors.ColorRed)
48 |
49 | // [episode name]
50 | root.AttrOn(goncurses.A_BOLD)
51 | root.MovePrint(x+6, minxt, ep)
52 | root.AttrOff(goncurses.A_BOLD)
53 |
54 | // by
55 | root.ColorOn(colors.ColorGreen)
56 | root.MovePrint(x+8, (w-len(div))/2, div)
57 | root.ColorOff(colors.ColorGreen)
58 |
59 | // [podcast name]
60 | root.ColorOn(colors.ColorYellow)
61 | root.MovePrint(x+10, minxp, pod)
62 | root.ColorOff(colors.ColorGreen)
63 |
64 | root.MovePrint(h-(h/3), 0, p)
65 | root.MovePrint(h-(h/3), w-len(d), d)
66 |
67 | root.HLine(h-(h/3), len(p)+1, goncurses.ACS_HLINE, w-len(d)-len(p)-2)
68 | root.MovePrint(h-(h/3), len(p), "|")
69 | root.MovePrint(h-(h/3), len(p)+1+(w-len(d)-len(p)-2), "|")
70 |
71 | wid := int(float64(w-len(d)-len(p)-2) * percent)
72 |
73 | root.ColorOn(colors.ColorBlue)
74 | root.HLine(h-(h/3), len(p)+1, goncurses.ACS_HLINE, wid)
75 | root.ColorOff(colors.ColorBlue)
76 |
77 | // Next up
78 | cur, _ := sound.GetNext()
79 | lbl := "Next up: "
80 | if cur != nil {
81 | var txt string
82 | if entry, ok := data.Downloads.Query(cur.Path); ok && entry.Title != "" {
83 | txt = entry.Title
84 | } else {
85 | txt = cur.URL
86 | }
87 | clipped := data.LimitString(txt, w-1)
88 |
89 | root.ColorOn(colors.ColorRed)
90 | root.MovePrint(h-(h/3)+2, (w-len(lbl))/2, lbl)
91 | root.ColorOff(colors.ColorRed)
92 |
93 | root.MovePrint(h-(h/3)+3, (w-len(clipped))/2, clipped)
94 | }
95 | }
96 |
97 | func (l *Player) Should(event int) bool {
98 | return event == ev.Keystroke || event == ev.PlayerChanged
99 | }
100 |
101 | func (l *Player) Input(c rune) {
102 | switch c {
103 | case ' ':
104 | sound.Plr.Toggle()
105 | case 'h':
106 | sound.Plr.Seek(-5)
107 | case 'l':
108 | sound.Plr.Seek(5)
109 |
110 | case 'H':
111 | sound.Plr.Seek(-60)
112 | case 'L':
113 | sound.Plr.Seek(60)
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/ui/queue.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "github.com/ejv2/podbit/colors"
5 | "github.com/ejv2/podbit/data"
6 | ev "github.com/ejv2/podbit/event"
7 | "github.com/ejv2/podbit/sound"
8 | "github.com/ejv2/podbit/ui/components"
9 | )
10 |
11 | var queueHeadings []components.Column = []components.Column{
12 | {
13 | Label: "",
14 | Width: 0.1,
15 | Color: colors.BackgroundRed,
16 | },
17 | {
18 | Label: "Name",
19 | Width: 0.5,
20 | Color: colors.BackgroundBlue,
21 | },
22 | {
23 | Label: "Podcast",
24 | Width: 0.4,
25 | Color: colors.BackgroundGreen,
26 | },
27 | }
28 |
29 | // Queue displays the current play queue.
30 | // Not to be confused with the current download queue, Download.
31 | type Queue struct {
32 | tbl components.Table
33 | }
34 |
35 | func (q *Queue) Name() string {
36 | return "Queue"
37 | }
38 |
39 | func (q *Queue) Render(x, y int) {
40 | q.tbl.X, q.tbl.Y = x, y
41 | q.tbl.W, q.tbl.H = w, h-5
42 | q.tbl.Win = root
43 |
44 | q.tbl.Columns = queueHeadings
45 |
46 | q.tbl.Items = nil
47 | for _, elem := range sound.GetQueue() {
48 | item := make([]string, len(queueHeadings))
49 | dat, ok := data.Downloads.Query(elem.Path)
50 | pod := data.DB.GetFriendlyName(elem.URL)
51 |
52 | if !ok || dat.Title == "" {
53 | item[1] = elem.URL
54 | } else {
55 | item[1] = dat.Title
56 | }
57 |
58 | if !ok {
59 | // In need of download
60 | item[0] += "!!"
61 | } else if sound.Plr.NowPlaying == item[1] {
62 | // Currently playing
63 | item[0] += ">>"
64 | }
65 |
66 | item[2] = pod
67 |
68 | q.tbl.Items = append(q.tbl.Items, item)
69 | }
70 |
71 | q.tbl.Render()
72 | }
73 |
74 | func (q *Queue) Should(event int) bool {
75 | return event == ev.Keystroke || event == ev.PlayerChanged
76 | }
77 |
78 | func (q *Queue) Input(c rune) {
79 | switch c {
80 | case 'j':
81 | q.tbl.MoveSelection(1)
82 | case 'k':
83 | q.tbl.MoveSelection(-1)
84 | case 'g':
85 | q.tbl.ChangeSelection(0)
86 | case 'G':
87 | q.tbl.ChangeSelection(len(q.tbl.Items) - 1)
88 | case 'd':
89 | i, _ := q.tbl.GetSelection()
90 | sound.Dequeue(i)
91 | case 13: // Enter key - Jump to this position
92 | i, _ := q.tbl.GetSelection()
93 | sound.JumpTo(i)
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/ui/tray.go:
--------------------------------------------------------------------------------
1 | package ui
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "time"
7 |
8 | "github.com/ejv2/podbit/colors"
9 | "github.com/ejv2/podbit/data"
10 | ev "github.com/ejv2/podbit/event"
11 | "github.com/ejv2/podbit/sound"
12 |
13 | "github.com/vit1251/go-ncursesw"
14 | )
15 |
16 | const (
17 | // MessageTime is the maximum time a message will show for.
18 | MessageTime time.Duration = 2 * time.Second
19 | )
20 |
21 | var (
22 | statusMessage = make(chan string)
23 | lastStatus time.Time
24 |
25 | status string
26 | )
27 |
28 | // RenderTray renders the statusbar tray at the bottom of the screen.
29 | // Tray takes up two vertical cells and the entirety of the width.
30 | // The top cell is a horizontal line denoting a player status bar.
31 | // The bottom cell is the status text.
32 | func RenderTray(scr *goncurses.Window, w, h int) {
33 | scr.HLine(h-2, 0, goncurses.ACS_HLINE, w)
34 |
35 | pos, dur := sound.Plr.GetTimings()
36 | percent := pos / dur
37 |
38 | scr.ColorOn(colors.ColorBlue)
39 | scr.HLine(h-2, 0, '-', int(percent*float64(w)))
40 |
41 | head := int(math.Max((percent*float64(w))-1, 0))
42 | scr.MovePrint(h-2, head, ">")
43 | scr.ColorOff(colors.ColorBlue)
44 |
45 | now := time.Now()
46 | if now.Sub(lastStatus) > MessageTime {
47 | select {
48 | case status = <-statusMessage:
49 | lastStatus = now
50 | go func() {
51 | time.Sleep(MessageTime)
52 | eventsHndl.Post(ev.TrayMessage)
53 | }()
54 | default:
55 | status = ""
56 | }
57 | }
58 |
59 | if status != "" {
60 | root.ColorOn(colors.ColorYellow)
61 | root.AttrOn(goncurses.A_BOLD)
62 | scr.MovePrint(h-1, 0, status)
63 | root.AttrOff(goncurses.A_BOLD)
64 | root.ColorOff(colors.ColorYellow)
65 | } else {
66 | if sound.Plr.IsPlaying() {
67 | var status string
68 | if sound.Plr.IsPaused() {
69 | status = "Paused"
70 | } else {
71 | status = "Playing"
72 | }
73 |
74 | root.ColorOn(colors.ColorRed)
75 | scr.MovePrintf(h-1, 0, "%s: ", status)
76 | root.ColorOff(colors.ColorRed)
77 |
78 | root.ColorOn(colors.ColorBlue)
79 | scr.MovePrintf(h-1, len(status)+2, "%s - %s", sound.Plr.NowPlaying, sound.Plr.NowPodcast)
80 | root.ColorOff(colors.ColorBlue)
81 |
82 | } else if sound.Plr.IsWaiting() {
83 | root.ColorOn(colors.ColorRed)
84 | scr.MovePrint(h-1, 0, "Waiting for download...")
85 | root.ColorOff(colors.ColorRed)
86 | } else {
87 | root.ColorOn(colors.ColorRed)
88 | scr.MovePrint(h-1, 0, "Not playing")
89 | root.ColorOff(colors.ColorRed)
90 | }
91 | }
92 |
93 | // Timing tray
94 | pos, dur = sound.Plr.GetTimings()
95 | p, d := data.FormatTime(pos), data.FormatTime(dur)
96 | code := fmt.Sprintf("[%s/%s]", p, d)
97 | root.ColorOn(colors.ColorRed)
98 | scr.MovePrintf(h-1, w-len(code), "%s", code)
99 | root.ColorOff(colors.ColorRed)
100 | }
101 |
102 | // StatusMessage sends a status message to the tray.
103 | //
104 | // Will block for the previous message to finish first.
105 | // Every message can be guaranteed MessageTime display time.
106 | func StatusMessage(msg string) {
107 | statusMessage <- msg
108 | }
109 |
--------------------------------------------------------------------------------
/ui/ui.go:
--------------------------------------------------------------------------------
1 | // Package ui implements podbit's main UI and front end user code.
2 | //
3 | // This package runs mostly in a separate UI thread and is as thread-safe
4 | // as possible.
5 | //
6 | // Due to limitations in the C library ncurses, the render loop is
7 | // designed to only let one thread use ncurses callbacks at a time,
8 | // with as little loss in performance as possible. Threads will wait
9 | // for the time to redraw using channels and modes. Usually, three
10 | // separate threads will run at a time: the menu thread, tray thread
11 | // and main thread. These all interact using the aforementioned channels
12 | // to draw the screen in sync.
13 | //
14 | // The "redraw" chanel is the main channel around which the UI code
15 | // revolves. It is an integer channel which receives a "mode". This
16 | // mode allows you to select which part of the UI to redraw. This *can*
17 | // be all of them. The UI threads wait around for the redraw channel to
18 | // instruct them as to when they should draw the screen.
19 | //
20 | // The "exit" channel simply instructs us to exit immediately. This should
21 | // *NEVER* be used inside a render callback, least a deadlock in the UI
22 | // code be caused.
23 | package ui
24 |
25 | import (
26 | "os"
27 | "os/signal"
28 | "syscall"
29 |
30 | ev "github.com/ejv2/podbit/event"
31 |
32 | goncurses "github.com/vit1251/go-ncursesw"
33 | "golang.org/x/term"
34 | )
35 |
36 | // A Menu is a renderable UI element which takes up most of primary.
37 | // screen space and is capable of handling unhandled keybinds.
38 | type Menu interface {
39 | Name() string
40 | Render(x, y int)
41 | Should(event int) bool
42 | Input(c rune)
43 | }
44 |
45 | var (
46 | root *goncurses.Window
47 | w, h int
48 |
49 | eventsHndl ev.Handler
50 | events chan int
51 | currentMenu Menu
52 |
53 | menuChan chan Menu
54 | keystroke chan rune
55 | reload chan int8
56 | )
57 |
58 | // Menu singletons.
59 | var (
60 | PlayerMenu = new(Player) // Full screen player.
61 | QueueMenu = new(Queue) // Player queue display.
62 | DownloadMenu = new(Downloads) // Shows ongoing downloads.
63 | LibraryMenu = new(Library) // Library of podcasts and episodes.
64 | )
65 |
66 | // Watch the terminal for resizes and redraw when needed.
67 | func watchResize(sig chan os.Signal, scr *goncurses.Window) {
68 | for {
69 | <-sig
70 | eventsHndl.Post(ev.Resize)
71 | }
72 | }
73 |
74 | // InitUI initialises the UI subsystem.
75 | func InitUI(scr *goncurses.Window, initialMenu Menu, hndl *ev.Handler, k chan rune, m chan Menu, r chan int8) {
76 | keystroke = k
77 | menuChan = m
78 | root = scr
79 | currentMenu = initialMenu
80 | reload = r
81 |
82 | eventsHndl = *hndl
83 | events = hndl.Register()
84 |
85 | resizeChan := make(chan os.Signal, 1)
86 | signal.Notify(resizeChan, syscall.SIGWINCH)
87 | go watchResize(resizeChan, scr)
88 |
89 | UpdateDimensions(scr)
90 | }
91 |
92 | // UpdateDimensions changes the dimensions of the drawable area.
93 | //
94 | // Called automatically on detected terminal resizes by the resizeLoop
95 | // thread.
96 | func UpdateDimensions(scr *goncurses.Window) {
97 | var err error
98 | w, h, err = term.GetSize(int(os.Stdin.Fd()))
99 |
100 | if err != nil {
101 | w, h = 72, 90
102 | }
103 |
104 | if w < 10 || h < 5 {
105 | Exit()
106 | }
107 |
108 | goncurses.ResizeTerm(h, w)
109 | }
110 |
111 | func renderMenu() {
112 | if currentMenu == nil {
113 | return
114 | }
115 |
116 | // Clear region
117 | for i := 0; i < h-2; i++ {
118 | root.Move(i, 0)
119 | root.ClearToEOL()
120 | }
121 | root.Move(0, 0)
122 |
123 | // Title Text
124 | root.AttrOn(goncurses.A_BOLD)
125 | root.Printf("%s", currentMenu.Name())
126 | root.HLine(1, 0, goncurses.ACS_HLINE, w)
127 | root.AttrOff(goncurses.A_BOLD)
128 |
129 | // Actually render menu
130 | currentMenu.Render(0, 2)
131 | }
132 |
133 | func renderTray() {
134 | for i := h - 2; i <= h; i++ {
135 | root.Move(i, 0)
136 | root.ClearToEOL()
137 | }
138 |
139 | RenderTray(root, w, h)
140 | }
141 |
142 | // ActivateMenu sets the current menu to the requested value.
143 | // This DOES NOT redraw the screen until manually caused by an event.
144 | func ActivateMenu(newMenu Menu) {
145 | menuChan <- newMenu
146 | }
147 |
148 | // PassKeystroke performs a keystroke passthrough for the active menu.
149 | func PassKeystroke(c rune) {
150 | keystroke <- c
151 | }
152 |
153 | // RenderLoop is the main render callback for the program.
154 | // This is intended to run in its own thread.
155 | func RenderLoop() {
156 | for {
157 | select {
158 | case newMenu := <-menuChan:
159 | currentMenu = newMenu
160 | case event, ok := <-events:
161 | if !ok {
162 | return
163 | }
164 | if event == ev.RequestShutdown {
165 | close(exitChan)
166 | return
167 | }
168 |
169 | if event == ev.Resize {
170 | UpdateDimensions(root)
171 | renderMenu()
172 | } else if currentMenu.Should(event) {
173 | renderMenu()
174 | }
175 | renderTray()
176 | root.Refresh()
177 | case c := <-keystroke:
178 | currentMenu.Input(c)
179 | }
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/ver.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | const (
4 | verMaj = 3
5 | verMin = 1
6 | verPatch = 0
7 | )
8 |
--------------------------------------------------------------------------------