├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── fediboat
├── __init__.py
├── __main__.py
├── api
│ ├── __init__.py
│ ├── auth.py
│ └── timelines.py
├── cli.py
├── entities.py
├── screens.py
├── settings.py
└── timeline.tcss
├── pyproject.toml
├── pytest.ini
└── tests
├── conftest.py
├── data
├── new_thread_statuses.json
├── notifications.json
├── old_notifications.json
├── old_statuses.json
├── old_thread_statuses.json
├── statuses.json
└── thread_status.json
├── test_api.py
└── test_tui.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110 | .pdm.toml
111 | .pdm-python
112 | .pdm-build/
113 |
114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115 | __pypackages__/
116 |
117 | # Celery stuff
118 | celerybeat-schedule
119 | celerybeat.pid
120 |
121 | # SageMath parsed files
122 | *.sage.py
123 |
124 | # Environments
125 | .env
126 | .venv
127 | env/
128 | venv/
129 | ENV/
130 | env.bak/
131 | venv.bak/
132 |
133 | # Spyder project settings
134 | .spyderproject
135 | .spyproject
136 |
137 | # Rope project settings
138 | .ropeproject
139 |
140 | # mkdocs documentation
141 | /site
142 |
143 | # mypy
144 | .mypy_cache/
145 | .dmypy.json
146 | dmypy.json
147 |
148 | # Pyre type checker
149 | .pyre/
150 |
151 | # pytype static type analyzer
152 | .pytype/
153 |
154 | # Cython debug symbols
155 | cython_debug/
156 |
157 | # PyCharm
158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160 | # and can be added to the global gitignore or merged into this file. For a more nuclear
161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162 | #.idea/
163 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include fediboat *.tcss
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Fediboat
2 | Fediboat - Mastodon TUI client with a Newsboat-like interface.
3 |
4 | 
5 |
6 | ## Installation
7 | Install pipx following their [installation instructions](https://pipx.pypa.io/stable/installation/).
8 |
9 | Install Fediboat:
10 | ```
11 | pipx install fediboat
12 | ```
13 |
14 | ## Usage
15 | Log in to your Mastodon account:
16 | ```
17 | fediboat login
18 | ```
19 |
20 | Run the client:
21 | ```
22 | fediboat tui
23 | ```
24 |
25 | ## Features
26 | - Markdown support
27 | - Use your favourite text editor (vim)
28 | - Simple, configurable and extensible
29 |
--------------------------------------------------------------------------------
/fediboat/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/N333RDY/fediboat/87aa0e14764cc85b61c9692ba4b8d71c1c86a322/fediboat/__init__.py
--------------------------------------------------------------------------------
/fediboat/__main__.py:
--------------------------------------------------------------------------------
1 | from fediboat.cli import cli
2 |
3 | if __name__ == "__main__":
4 | cli()
5 |
--------------------------------------------------------------------------------
/fediboat/api/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/N333RDY/fediboat/87aa0e14764cc85b61c9692ba4b8d71c1c86a322/fediboat/api/__init__.py
--------------------------------------------------------------------------------
/fediboat/api/auth.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 |
4 | class APIError(Exception):
5 | pass
6 |
7 |
8 | class LoginError(APIError):
9 | pass
10 |
11 |
12 | class AppCreateError(APIError):
13 | pass
14 |
15 |
16 | def get_headers(access_token: str):
17 | return {"Authorization": f"Bearer {access_token}"}
18 |
19 |
20 | def create_app(instance_url: str, scopes: str = "read write follow") -> dict:
21 | return requests.post(
22 | f"{instance_url}/api/v1/apps",
23 | data={
24 | "client_name": "Fediboat",
25 | "redirect_uris": "urn:ietf:wg:oauth:2.0:oob",
26 | "scopes": scopes,
27 | "website": "https://github.com/Lo-Riot/fediboat",
28 | },
29 | ).json()
30 |
31 |
32 | def auth(
33 | instance_url: str,
34 | client_id: int,
35 | client_secret: str,
36 | authz_code: str,
37 | scope: str = "read write follow",
38 | ) -> str:
39 | resp = requests.post(
40 | f"{instance_url}/oauth/token",
41 | data={
42 | "client_id": client_id,
43 | "client_secret": client_secret,
44 | "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
45 | "grant_type": "authorization_code",
46 | "code": authz_code,
47 | "scope": scope,
48 | },
49 | ).json()
50 | return resp["access_token"]
51 |
52 |
53 | def verify_credentials(instance_url: str, access_token: str) -> dict:
54 | """Returns account id or raises LoginError"""
55 | resp = requests.get(
56 | f"{instance_url}/api/v1/accounts/verify_credentials",
57 | headers=get_headers(access_token),
58 | )
59 | resp_data = resp.json()
60 |
61 | if resp.status_code != 200:
62 | raise LoginError(resp_data["error"])
63 | return resp_data
64 |
--------------------------------------------------------------------------------
/fediboat/api/timelines.py:
--------------------------------------------------------------------------------
1 | from typing import Callable, Generator, Sequence, TypeAlias, TypeVar
2 | from urllib.parse import urlencode, urlparse
3 |
4 | from bs4 import BeautifulSoup
5 | from pydantic import TypeAdapter
6 | from requests import Response, Session, codes
7 | from textual import log
8 |
9 | from fediboat.api.auth import APIError
10 | from fediboat.entities import (
11 | Context,
12 | EntityProtocol,
13 | Notification,
14 | Status,
15 | TUIEntity,
16 | )
17 | from fediboat.settings import AuthSettings, Config
18 |
19 | TimelineCallable: TypeAlias = Callable[
20 | [Session, AuthSettings], Generator[list[TUIEntity], None, None]
21 | ]
22 | Entity = TypeVar("Entity", bound=EntityProtocol)
23 | QueryParams: TypeAlias = str | int | bool | Sequence[str]
24 |
25 |
26 | def get_timelines(config: Config) -> dict[str, TimelineCallable]:
27 | return {
28 | "Home": home_timeline_generator,
29 | "Local": local_timeline_generator,
30 | "Global": global_timeline_generator,
31 | "Notifications": get_notifications_timeline(config),
32 | "Personal": personal_timeline_generator,
33 | "Bookmarks": bookmarks_timeline_generator,
34 | }
35 |
36 |
37 | def handle_request_errors(resp: Response, *args, **kwargs):
38 | if resp.status_code != codes.ok:
39 | resp_json = resp.json()
40 | raise APIError(
41 | f"Endpoint: {urlparse(resp.url).path}\nError: {resp_json['error']}"
42 | )
43 |
44 |
45 | def _html_to_plain_text(status: Status) -> Status:
46 | soup = BeautifulSoup(status.content, "html.parser")
47 | log("id:", status.id)
48 | log(f"html:\n{soup.prettify()}")
49 |
50 | for element in soup.find_all("br"):
51 | element.replace_with(" \n")
52 |
53 | plain_text = ""
54 | for element in soup.find_all("p"):
55 | plain_text += element.get_text() + "\n\n"
56 |
57 | if not plain_text:
58 | plain_text = soup.get_text()
59 |
60 | log("plain text:", repr(plain_text))
61 | return status.model_copy(update={"content": plain_text})
62 |
63 |
64 | def _timeline_generator(
65 | session: Session,
66 | api_endpoint: str,
67 | validator: TypeAdapter[list[Entity]],
68 | **query_params: QueryParams,
69 | ) -> Generator[list[Entity], None, None]:
70 | next_url: str = f"{api_endpoint}?{urlencode(query_params, doseq=True)}"
71 | while next_url:
72 | resp = session.get(next_url)
73 | resp_json = resp.json()
74 | yield validator.validate_python(resp_json)
75 |
76 | if resp.links.get("next") is None or resp.links["next"]["url"] == next_url:
77 | return
78 |
79 | next_url = resp.links["next"]["url"]
80 |
81 |
82 | def status_to_entity(status: Status) -> TUIEntity:
83 | if status.reblog is not None:
84 | cleaned_status = _html_to_plain_text(status.reblog)
85 | else:
86 | cleaned_status = _html_to_plain_text(status)
87 |
88 | return TUIEntity(
89 | status=cleaned_status,
90 | author=status.account.acct,
91 | )
92 |
93 |
94 | def statuses_to_entities(statuses: list[Status]) -> list[TUIEntity]:
95 | return [status_to_entity(status) for status in statuses]
96 |
97 |
98 | def notifications_to_entities(notifications: list[Notification]) -> list[TUIEntity]:
99 | entities: list[TUIEntity] = []
100 | for notification in notifications:
101 | cleaned_status = None
102 | if notification.status is not None:
103 | cleaned_status = _html_to_plain_text(notification.status)
104 |
105 | entities.append(
106 | TUIEntity(
107 | status=cleaned_status,
108 | author=notification.account.acct,
109 | notification_type=notification.type,
110 | )
111 | )
112 | return entities
113 |
114 |
115 | def context_to_entities(context: Context, status: Status) -> list[TUIEntity]:
116 | ancestors = statuses_to_entities(context.ancestors)
117 | descendants = statuses_to_entities(context.descendants)
118 | return ancestors + [status_to_entity(status)] + descendants
119 |
120 |
121 | def status_timeline_generator(
122 | session: Session, api_endpoint: str, **query_params: QueryParams
123 | ) -> Generator[list[TUIEntity], None, None]:
124 | for statuses in _timeline_generator(
125 | session, api_endpoint, TypeAdapter(list[Status]), **query_params
126 | ):
127 | yield statuses_to_entities(statuses)
128 |
129 |
130 | def notification_timeline_generator(
131 | session: Session, api_endpoint: str, **query_params: QueryParams
132 | ) -> Generator[list[TUIEntity], None, None]:
133 | for notifications in _timeline_generator(
134 | session, api_endpoint, TypeAdapter(list[Notification]), **query_params
135 | ):
136 | yield notifications_to_entities(notifications)
137 |
138 |
139 | def home_timeline_generator(
140 | session: Session, settings: AuthSettings
141 | ) -> Generator[list[TUIEntity], None, None]:
142 | return status_timeline_generator(
143 | session, f"{settings.instance_url}/api/v1/timelines/home"
144 | )
145 |
146 |
147 | def local_timeline_generator(
148 | session: Session, settings: AuthSettings
149 | ) -> Generator[list[TUIEntity], None, None]:
150 | return status_timeline_generator(
151 | session, f"{settings.instance_url}/api/v1/timelines/public", local=True
152 | )
153 |
154 |
155 | def global_timeline_generator(
156 | session: Session, settings: AuthSettings
157 | ) -> Generator[list[TUIEntity], None, None]:
158 | return status_timeline_generator(
159 | session, f"{settings.instance_url}/api/v1/timelines/public", remote=True
160 | )
161 |
162 |
163 | def personal_timeline_generator(
164 | session: Session, settings: AuthSettings
165 | ) -> Generator[list[TUIEntity], None, None]:
166 | return status_timeline_generator(
167 | session, f"{settings.instance_url}/api/v1/accounts/{settings.id}/statuses"
168 | )
169 |
170 |
171 | def bookmarks_timeline_generator(
172 | session: Session, settings: AuthSettings
173 | ) -> Generator[list[TUIEntity], None, None]:
174 | return status_timeline_generator(
175 | session, f"{settings.instance_url}/api/v1/bookmarks"
176 | )
177 |
178 |
179 | def get_notifications_timeline(
180 | config: Config,
181 | ) -> Callable[[Session, AuthSettings], Generator[list[TUIEntity], None, None]]:
182 | def notifications_timeline_generator(
183 | session: Session, settings: AuthSettings
184 | ) -> Generator[list[TUIEntity], None, None]:
185 | params: dict[str, QueryParams] = {
186 | "types[]": config.notifications.show,
187 | "limit": 20,
188 | }
189 | return notification_timeline_generator(
190 | session, f"{settings.instance_url}/api/v1/notifications", **params
191 | )
192 |
193 | return notifications_timeline_generator
194 |
195 |
196 | def thread_fetcher(
197 | session: Session, settings: AuthSettings, status: Status
198 | ) -> Callable[..., list[TUIEntity]]:
199 | def fetch_thread() -> list[TUIEntity]:
200 | resp = session.get(
201 | f"{settings.instance_url}/api/v1/statuses/{status.id}/context"
202 | )
203 | resp_json = resp.json()
204 | context = Context.model_validate(resp_json)
205 | return context_to_entities(context, status)
206 |
207 | return fetch_thread
208 |
209 |
210 | def favourite_status(
211 | session: Session, settings: AuthSettings, status: Status
212 | ) -> Status:
213 | endpoint = "favourite" if not status.favourited else "unfavourite"
214 | resp = session.post(
215 | f"{settings.instance_url}/api/v1/statuses/{status.id}/{endpoint}"
216 | )
217 | return Status.model_validate(resp.json())
218 |
219 |
220 | def reblog_status(session: Session, settings: AuthSettings, status: Status) -> Status:
221 | endpoint = "reblog" if not status.reblogged else "unreblog"
222 | resp = session.post(
223 | f"{settings.instance_url}/api/v1/statuses/{status.id}/{endpoint}"
224 | )
225 | return Status.model_validate(resp.json())
226 |
227 |
228 | def post_status(
229 | content: str,
230 | session: Session,
231 | settings: AuthSettings,
232 | in_reply_to_id: str | None = None,
233 | visibility: str = "public",
234 | ) -> Status:
235 | resp = session.post(
236 | f"{settings.instance_url}/api/v1/statuses",
237 | data={
238 | "status": content,
239 | "in_reply_to_id": in_reply_to_id,
240 | "visibility": visibility,
241 | },
242 | )
243 | resp_json = resp.json()
244 | return Status.model_validate(resp_json)
245 |
--------------------------------------------------------------------------------
/fediboat/cli.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import webbrowser
3 | from pathlib import Path
4 |
5 | import click
6 | from requests import Session
7 | from textual.app import App
8 |
9 | from fediboat.api.timelines import get_timelines, handle_request_errors
10 | from fediboat.screens import StatusContent, TimelineScreen
11 | from fediboat.settings import (
12 | AuthSettings,
13 | LoadSettingsError,
14 | create_auth_settings,
15 | load_settings,
16 | )
17 |
18 | from .api.auth import (
19 | APIError,
20 | auth,
21 | create_app,
22 | get_headers,
23 | verify_credentials,
24 | )
25 |
26 |
27 | class FediboatApp(App):
28 | """Fediboat - Mastodon TUI client"""
29 |
30 | def __init__(self, timeline: TimelineScreen):
31 | self.timeline = timeline
32 | super().__init__()
33 |
34 | def on_mount(self) -> None:
35 | self.title = "Fediboat"
36 | self.install_screen(StatusContent(), name="status")
37 | self.push_screen(self.timeline)
38 |
39 |
40 | @click.group(help="Fediboat - Mastodon TUI client with a Newsboat-like interface")
41 | @click.option(
42 | "-a",
43 | "--auth",
44 | default="~/.config/fediboat/auth.json",
45 | type=Path,
46 | show_default=True,
47 | )
48 | @click.option(
49 | "-c",
50 | "--config",
51 | default="~/.config/fediboat/config.toml",
52 | type=Path,
53 | show_default=True,
54 | )
55 | @click.pass_context
56 | def cli(ctx, auth: Path, config: Path):
57 | ctx.ensure_object(dict)
58 | ctx.obj["AUTH_SETTINGS"] = auth
59 | ctx.obj["CONFIG"] = config
60 |
61 |
62 | @cli.command()
63 | @click.pass_context
64 | def tui(ctx):
65 | auth_settings_file = ctx.obj["AUTH_SETTINGS"].expanduser()
66 | config_file = ctx.obj["CONFIG"].expanduser()
67 | try:
68 | settings = load_settings(auth_settings_file, config_file)
69 | except LoadSettingsError:
70 | click.secho("Error: Run the 'fediboat login' command first", err=True, fg="red")
71 | sys.exit(1)
72 |
73 | session = Session()
74 | session.headers.update(get_headers(settings.auth.access_token))
75 | session.hooks["response"].append(handle_request_errors)
76 |
77 | timeline = TimelineScreen(get_timelines(settings.config), settings, session)
78 | app = FediboatApp(timeline)
79 | app.run()
80 |
81 |
82 | def _login_account() -> AuthSettings:
83 | instance_url = click.prompt(
84 | "Instance url",
85 | default="https://mastodon.social",
86 | )
87 | app = create_app(instance_url)
88 | webbrowser.open(
89 | f"{instance_url}/oauth/authorize"
90 | f"?client_id={app['client_id']}&scope=read+write+follow"
91 | f"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code"
92 | )
93 |
94 | authz_code = click.prompt("Code")
95 | access_token = auth(
96 | instance_url, app["client_id"], app["client_secret"], authz_code
97 | )
98 | user = verify_credentials(instance_url, access_token)
99 |
100 | instance_domain = instance_url.replace("https://", "")
101 | full_username = f"{user['acct']}@{instance_domain}"
102 |
103 | auth_settings = AuthSettings(
104 | id=user["id"],
105 | instance_url=instance_url,
106 | instance_domain=instance_domain,
107 | full_username=full_username,
108 | access_token=access_token,
109 | client_id=app["client_id"],
110 | client_secret=app["client_secret"],
111 | )
112 | return auth_settings
113 |
114 |
115 | @cli.command()
116 | @click.pass_context
117 | def login(ctx):
118 | auth_settings_file = ctx.obj["AUTH_SETTINGS"].expanduser()
119 | config_file = ctx.obj["CONFIG"].expanduser()
120 |
121 | try:
122 | auth_settings = load_settings(auth_settings_file, config_file).auth
123 | verify_credentials(
124 | auth_settings.instance_url,
125 | auth_settings.access_token,
126 | )
127 | except LoadSettingsError:
128 | auth_settings = _login_account()
129 | create_auth_settings(
130 | auth_settings_file,
131 | auth_settings,
132 | )
133 | except APIError as e:
134 | click.secho(f"Error: {e}", err=True, fg="red")
135 | sys.exit(1)
136 |
137 | click.secho("Logged in successfully!", fg="green")
138 |
--------------------------------------------------------------------------------
/fediboat/entities.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from enum import StrEnum, auto
3 | from typing import Optional, Protocol
4 |
5 | from pydantic import BaseModel
6 |
7 |
8 | class EntityProtocol(Protocol):
9 | id: str
10 |
11 |
12 | class TUIEntity(BaseModel):
13 | status: "Status | None"
14 | author: str
15 | notification_type: "NotificationTypeEnum | None" = None
16 |
17 |
18 | class MediaAttachment(BaseModel):
19 | id: str
20 | type: str
21 | url: str
22 | preview_url: Optional[str] = None
23 | remote_url: Optional[str] = None
24 | meta: Optional[dict] = None
25 | description: Optional[str] = None
26 | blurhash: Optional[str] = None
27 |
28 |
29 | class Application(BaseModel):
30 | name: str
31 | website: Optional[str] = None
32 |
33 |
34 | class StatusMention(BaseModel):
35 | id: str
36 | username: str
37 | url: str
38 | acct: str
39 |
40 |
41 | class StatusTag(BaseModel):
42 | name: str
43 | url: str
44 |
45 |
46 | class CustomEmoji(BaseModel):
47 | shortcode: str
48 | url: str
49 | static_url: str
50 | visible_in_picker: bool
51 | category: Optional[str] = None
52 |
53 |
54 | class PollOption(BaseModel):
55 | title: str
56 | votes_count: Optional[int] = None
57 |
58 |
59 | class Poll(BaseModel):
60 | id: str
61 | expires_at: Optional[datetime]
62 | expired: bool
63 | multiple: bool
64 | votes_count: int
65 | voters_count: Optional[int] = None
66 | options: list[PollOption]
67 | emojis: list[CustomEmoji]
68 | voted: Optional[bool] = None
69 | own_votes: Optional[list[int]] = None
70 |
71 |
72 | class PreviewCard(BaseModel):
73 | url: str
74 | title: str
75 | description: str
76 | type: str
77 | author_name: str
78 | author_url: str
79 | provider_name: str
80 | provider_url: str
81 | html: str
82 | width: int
83 | height: int
84 | image: Optional[str] = None
85 | embed_url: str
86 | blurhash: Optional[str] = None
87 |
88 |
89 | class FilterKeyword(BaseModel):
90 | id: str
91 | keyword: str
92 | whole_word: bool
93 |
94 |
95 | class FilterStatus(BaseModel):
96 | id: str
97 | status_id: str
98 |
99 |
100 | class Filter(BaseModel):
101 | id: str
102 | title: str
103 | context: list[str]
104 | expires_at: Optional[datetime] = None
105 | filter_action: str
106 | keywords: list[FilterKeyword]
107 | statuses: list[FilterStatus]
108 |
109 |
110 | class FilterResult(BaseModel):
111 | filter: Filter
112 | keyword_matches: Optional[list[str]] = None
113 | status_matches: Optional[list[str]] = None
114 |
115 |
116 | class Field(BaseModel):
117 | name: str
118 | value: str
119 | verified_at: Optional[datetime] = None
120 |
121 |
122 | class Account(BaseModel):
123 | id: str
124 | username: str
125 | acct: str
126 | url: str
127 | display_name: str
128 | note: str
129 | avatar: str
130 | avatar_static: str
131 | header: str
132 | header_static: str
133 | locked: bool
134 | fields: list[Field]
135 | emojis: list[CustomEmoji]
136 | bot: bool
137 | group: bool
138 | discoverable: bool | None = None
139 | noindex: Optional[bool] = None
140 | moved: Optional["Account"] = None
141 | suspended: Optional[bool] = None
142 | limited: Optional[bool] = None
143 | created_at: datetime
144 | last_status_at: Optional[datetime] = None
145 | statuses_count: int
146 | followers_count: int
147 | following_count: int
148 | source: Optional[dict] = None
149 |
150 |
151 | class Status(BaseModel):
152 | id: str
153 | uri: str
154 | created_at: datetime
155 | account: Account
156 | content: str
157 | visibility: str
158 | sensitive: bool
159 | spoiler_text: str
160 | media_attachments: list[MediaAttachment]
161 | application: Optional[Application] = None
162 | mentions: list[StatusMention]
163 | tags: list[StatusTag]
164 | emojis: list[CustomEmoji]
165 | reblogs_count: int
166 | favourites_count: int
167 | replies_count: int
168 | url: Optional[str] = None
169 | in_reply_to_id: Optional[str] = None
170 | in_reply_to_account_id: Optional[str] = None
171 | reblog: Optional["Status"] = None
172 | poll: Optional[Poll] = None
173 | card: Optional[PreviewCard] = None
174 | language: Optional[str] = None
175 | text: Optional[str] = None
176 | edited_at: Optional[datetime] = None
177 | favourited: Optional[bool] = None
178 | reblogged: Optional[bool] = None
179 | muted: Optional[bool] = None
180 | bookmarked: Optional[bool] = None
181 | pinned: Optional[bool] = None
182 | filtered: Optional[list[FilterResult]] = None
183 |
184 |
185 | class Context(BaseModel):
186 | ancestors: list[Status]
187 | descendants: list[Status]
188 |
189 |
190 | class Report(BaseModel):
191 | id: str
192 | action_taken: bool
193 | action_taken_at: Optional[datetime] = None
194 | category: str
195 | comment: str
196 | forwarded: bool
197 | created_at: datetime
198 | status_ids: Optional[list[str]] = None
199 | rule_ids: Optional[list[str]] = None
200 | target_account: Account
201 |
202 |
203 | class NotificationTypeEnum(StrEnum):
204 | reply = auto()
205 | favourite = auto()
206 | mention = auto()
207 | reblog = auto()
208 | follow = auto()
209 | follow_request = auto()
210 | moderation_warning = auto()
211 | severed_relationships = auto()
212 | status = auto()
213 | poll = auto()
214 | update = auto()
215 | admin_sign_up = "admin.sign_up"
216 | admin_report = "admin.report"
217 |
218 |
219 | class Notification(BaseModel):
220 | id: str
221 | type: NotificationTypeEnum
222 | created_at: datetime
223 | account: Account
224 | status: Optional[Status] = None
225 | report: Optional[Report] = None
226 |
--------------------------------------------------------------------------------
/fediboat/screens.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import tempfile
3 | from collections.abc import Callable
4 | from dataclasses import dataclass
5 |
6 | from requests import Session
7 | from rich.text import Text
8 | from textual import events, log, on
9 | from textual.app import ComposeResult
10 | from textual.containers import Grid
11 | from textual.screen import ModalScreen, Screen
12 | from textual.widgets import (
13 | DataTable,
14 | Footer,
15 | Header,
16 | Input,
17 | Label,
18 | Markdown,
19 | )
20 |
21 | from fediboat.api.auth import APIError
22 | from fediboat.api.timelines import (
23 | TimelineCallable,
24 | favourite_status,
25 | post_status,
26 | reblog_status,
27 | thread_fetcher,
28 | )
29 | from fediboat.entities import NotificationTypeEnum, TUIEntity
30 | from fediboat.settings import (
31 | Settings,
32 | )
33 |
34 |
35 | class ErrorMessage(ModalScreen):
36 | BINDINGS = [("escape", "app.pop_screen"), ("q", "app.pop_screen", "Quit")]
37 |
38 | def __init__(self, message: str):
39 | self.message = message
40 | super().__init__()
41 |
42 | def compose(self) -> ComposeResult:
43 | yield Grid(Label(self.message, id="message"), id="dialog")
44 | yield Footer()
45 |
46 |
47 | class Jump(ModalScreen[int]):
48 | BINDINGS = [("escape", "app.pop_screen")]
49 |
50 | def __init__(self, character: str):
51 | self.character = character
52 | super().__init__()
53 |
54 | def compose(self) -> ComposeResult:
55 | yield Input(self.character, select_on_focus=False, type="integer")
56 |
57 | @on(Input.Submitted)
58 | def submit(self) -> None:
59 | self.dismiss(int(self.query_one(Input).value))
60 |
61 |
62 | class StatusContent(Screen):
63 | BINDINGS = [("q", "app.pop_screen", "Go back")]
64 |
65 | def __init__(self, content: str | None = None):
66 | self.content = content
67 | super().__init__()
68 |
69 | def compose(self) -> ComposeResult:
70 | yield Markdown(self.content, id="md")
71 | yield Header()
72 | yield Footer()
73 |
74 |
75 | class SwitchTimeline(ModalScreen[str]):
76 | BINDINGS = [
77 | ("h", "switch('Home')", "Home"),
78 | ("l", "switch('Local')", "Local"),
79 | ("n", "switch('Notifications')", "Notifications"),
80 | ("p", "switch('Personal')", "Personal"),
81 | ("b", "switch('Bookmarks')", "Bookmarks"),
82 | # TODO: ("c", "switch('')", "Conversations"),
83 | # ("s", "switch('')", "Lists"),
84 | ("g", "switch('Global')", "Global"),
85 | ]
86 |
87 | def compose(self) -> ComposeResult:
88 | yield Footer()
89 |
90 | def on_key(self, event: events.Key):
91 | if self.active_bindings.get(event.key) is None:
92 | self.dismiss()
93 |
94 | def action_switch(self, timeline_name: str):
95 | self.dismiss(timeline_name)
96 |
97 |
98 | @dataclass
99 | class TableRow:
100 | id: str
101 | created_at: str = ""
102 | author: str = ""
103 | content: str = ""
104 | is_reply: str = ""
105 | notification_type: Text | None = None
106 | favourited: Text | None = None
107 | reblogged: Text | None = None
108 |
109 |
110 | class TimelineScreen(Screen):
111 | BINDINGS = [
112 | ("r", "update_timeline_new", "Refresh"),
113 | ("g", "switch_timeline", "Switch timeline"),
114 | ("t", "open_thread", "Open thread"),
115 | ("p", "post_status", "Post"),
116 | ("f", "favourite_status", "Favourite"),
117 | ("b", "reblog_status", "Boost"),
118 | ("R", "reply", "Reply"),
119 | ("j", "cursor_down"),
120 | ("k", "cursor_up"),
121 | ("l", "select_row"),
122 | ("ctrl+u", "scroll_up"),
123 | ("ctrl+d", "scroll_down"),
124 | ("q", "exit", "Quit"),
125 | ]
126 |
127 | CSS_PATH = "timeline.tcss"
128 |
129 | def __init__(
130 | self,
131 | timelines: dict[str, TimelineCallable],
132 | settings: Settings,
133 | session: Session,
134 | fetch_thread: Callable[..., list[TUIEntity]] | None = None,
135 | current_timeline_name: str = "Home",
136 | refresh_at_start: bool = True,
137 | ):
138 | self.timelines = timelines
139 | self.current_timeline_name = current_timeline_name
140 |
141 | self.settings = settings
142 | self.config = settings.config
143 | self.session = session
144 | self.fetch_thread = fetch_thread
145 |
146 | self.current_timeline = timelines[current_timeline_name](session, settings.auth)
147 | self.entities: list[TUIEntity] = []
148 | self.refresh_at_start = refresh_at_start
149 | super().__init__()
150 |
151 | def on_mount(self) -> None:
152 | timeline = self.query_one(DataTable)
153 | self.timeline_table = timeline
154 |
155 | timeline.cursor_background_priority = "renderable"
156 | timeline.add_columns("id", "date")
157 | timeline.add_column("user", width=25)
158 | timeline.add_column("title", width=50)
159 | timeline.add_column("is_reply", width=1)
160 | timeline.add_column("favourited", width=1, key="favourited")
161 | timeline.add_column("reblogged", width=1, key="reblogged")
162 | timeline.add_column("notification_type", width=1)
163 | if self.refresh_at_start:
164 | self.action_update_timeline_new()
165 |
166 | def compose(self) -> ComposeResult:
167 | yield DataTable(id="timeline", cursor_type="row", show_header=False)
168 | yield Header()
169 | yield Footer()
170 |
171 | def action_update_timeline_new(self) -> None:
172 | try:
173 | if self.fetch_thread is not None:
174 | self.entities = self.fetch_thread()
175 | else:
176 | self.current_timeline = self.timelines[self.current_timeline_name](
177 | self.session, self.settings.auth
178 | )
179 | self.entities = next(self.current_timeline)
180 | except APIError as e:
181 | self.log_error_message(str(e))
182 | return
183 | self.add_rows()
184 |
185 | def action_update_timeline_old(self) -> None:
186 | if self.fetch_thread is not None:
187 | return
188 |
189 | try:
190 | new_entities = next(self.current_timeline)
191 | except APIError as e:
192 | self.log_error_message(str(e))
193 | return
194 | except StopIteration:
195 | return
196 |
197 | self.entities.extend(new_entities)
198 | self.add_rows()
199 |
200 | def action_switch_timeline(self) -> None:
201 | def switch_timeline(timeline_name: str | None):
202 | if timeline_name is None:
203 | return
204 |
205 | if len(self.app.screen_stack) > 2:
206 | for _ in self.app.screen_stack[2:]:
207 | self.app.pop_screen()
208 |
209 | self.current_timeline_name = timeline_name
210 | self.action_update_timeline_new()
211 |
212 | self.app.push_screen(SwitchTimeline(), switch_timeline)
213 |
214 | def action_favourite_status(self) -> None:
215 | row_index = self.timeline_table.cursor_row
216 | selected_entity = self.entities[row_index]
217 | if selected_entity.status is None:
218 | return
219 |
220 | try:
221 | status = favourite_status(
222 | self.session, self.settings.auth, selected_entity.status
223 | )
224 | except APIError as e:
225 | self.log_error_message(str(e))
226 | return
227 |
228 | selected_entity.status.favourited = status.favourited
229 | favourited = ""
230 | if status.favourited:
231 | favourited = Text(
232 | *self.config.notifications.signs.get(
233 | NotificationTypeEnum.favourite, ("", "")
234 | )
235 | )
236 | self.timeline_table.update_cell(
237 | row_key=str(row_index),
238 | column_key="favourited",
239 | value=favourited,
240 | )
241 |
242 | def action_reblog_status(self) -> None:
243 | row_index = self.timeline_table.cursor_row
244 | selected_entity = self.entities[row_index]
245 | if selected_entity.status is None:
246 | return
247 |
248 | try:
249 | status = reblog_status(
250 | self.session, self.settings.auth, selected_entity.status
251 | )
252 | except APIError as e:
253 | self.log_error_message(str(e))
254 | return
255 |
256 | selected_entity.status.reblogged = status.reblogged
257 | reblogged = ""
258 | if status.reblogged:
259 | reblogged = Text(
260 | *self.config.notifications.signs.get(
261 | NotificationTypeEnum.reblog, ("", "")
262 | )
263 | )
264 | self.timeline_table.update_cell(
265 | row_key=str(row_index),
266 | column_key="reblogged",
267 | value=reblogged,
268 | )
269 |
270 | def action_open_thread(self) -> None:
271 | if len(self.entities) == 0:
272 | return
273 |
274 | row_index = self.timeline_table.cursor_row
275 | selected_entity = self.entities[row_index]
276 | if selected_entity.status is None:
277 | return
278 |
279 | try:
280 | fetch_thread = thread_fetcher(
281 | self.session, self.settings.auth, selected_entity.status
282 | )
283 | except APIError as e:
284 | self.log_error_message(str(e))
285 | return
286 |
287 | self.app.push_screen(
288 | TimelineScreen(
289 | self.timelines,
290 | self.settings,
291 | self.session,
292 | fetch_thread,
293 | self.current_timeline_name,
294 | )
295 | )
296 |
297 | def action_post_status(
298 | self,
299 | in_reply_to_id: str | None = None,
300 | mentions: str | None = None,
301 | visibility: str = "public",
302 | ) -> None:
303 | with self.app.suspend(), tempfile.NamedTemporaryFile() as tmp:
304 | if mentions is not None:
305 | tmp.write(mentions.encode("utf-8"))
306 | tmp.seek(0)
307 | subprocess.run([self.config.editor, tmp.name])
308 | content = tmp.read().decode("utf-8")
309 |
310 | if not content or content == mentions:
311 | return
312 |
313 | try:
314 | post_status(
315 | content,
316 | self.session,
317 | self.settings.auth,
318 | in_reply_to_id,
319 | visibility,
320 | )
321 | except APIError as e:
322 | self.log_error_message(str(e))
323 | return
324 |
325 | def action_reply(self):
326 | if len(self.entities) == 0:
327 | return
328 |
329 | selected_entity = self.entities[self.timeline_table.cursor_row]
330 | if selected_entity.status is None:
331 | return
332 |
333 | status_acct = selected_entity.status.account.acct
334 | user_acct = self.settings.auth.full_username.split("@")[0]
335 | mentions = ""
336 | for mention in selected_entity.status.mentions:
337 | if mention.acct != user_acct:
338 | mentions += f"@{mention.acct} "
339 |
340 | if status_acct not in mentions and status_acct != user_acct:
341 | mentions = f"@{status_acct} {mentions}"
342 | self.action_post_status(
343 | selected_entity.status.id, mentions, selected_entity.status.visibility
344 | )
345 |
346 | def add_rows(self) -> None:
347 | self.timeline_table.clear()
348 | for row_index, entity in enumerate(self.entities):
349 | row = TableRow(str(row_index + 1), author=entity.author)
350 | if entity.status is not None:
351 | row.created_at = entity.status.created_at.astimezone().strftime(
352 | "%b %d %H:%M"
353 | )
354 | row.content = " ".join(
355 | line.strip() for line in entity.status.content[:50].splitlines()
356 | )
357 | row.is_reply = "↵" if entity.status.in_reply_to_id else ""
358 |
359 | if entity.status.favourited:
360 | row.favourited = Text(
361 | *self.config.notifications.signs.get(
362 | NotificationTypeEnum.favourite, ("", "")
363 | )
364 | )
365 | if entity.status.reblogged:
366 | row.reblogged = Text(
367 | *self.config.notifications.signs.get(
368 | NotificationTypeEnum.reblog, ("", "")
369 | )
370 | )
371 |
372 | if entity.notification_type is not None:
373 | row.notification_type = Text(
374 | *self.config.notifications.signs.get(
375 | entity.notification_type, ("", "")
376 | )
377 | )
378 |
379 | self.timeline_table.add_row(
380 | Text(row.id, "#708090"),
381 | Text(row.created_at, "#B0C4DE"),
382 | Text(row.author, "#DDA0DD"),
383 | Text(row.content, "#F5DEB3"),
384 | Text(row.is_reply, "#87CEFA"),
385 | row.favourited,
386 | row.reblogged,
387 | row.notification_type,
388 | key=str(row_index),
389 | )
390 |
391 | def log_error_message(self, message: str) -> None:
392 | log(message)
393 | self.app.push_screen(ErrorMessage(message))
394 |
395 | def on_data_table_row_selected(self, row_selected: DataTable.RowSelected) -> None:
396 | if len(self.entities) == 0:
397 | return
398 |
399 | selected_entity = self.entities[row_selected.cursor_row]
400 | if selected_entity.status is None:
401 | return
402 |
403 | markdown = selected_entity.status.content
404 | self.app.push_screen(StatusContent(markdown))
405 |
406 | def on_key(self, event: events.Key):
407 | if event.character is None or not event.character.isdigit():
408 | return
409 |
410 | def jump_to_row(index: int | None):
411 | if index is not None:
412 | index -= 1
413 | self.timeline_table.move_cursor(row=index)
414 |
415 | self.app.push_screen(Jump(event.character), jump_to_row)
416 |
417 | def action_exit(self) -> None:
418 | if len(self.app.screen_stack) > 2:
419 | self.app.pop_screen() # If one or more threads are open
420 | else:
421 | self.app.exit()
422 |
423 | def action_scroll_down(self) -> None:
424 | half_timeline_height = round(
425 | self.timeline_table.scrollable_content_region.height / 2
426 | )
427 | self.timeline_table.scroll_relative(y=half_timeline_height, animate=False)
428 |
429 | def action_scroll_up(self) -> None:
430 | half_timeline_height = round(
431 | self.timeline_table.scrollable_content_region.height / 2
432 | )
433 | self.timeline_table.scroll_relative(y=-half_timeline_height, animate=False)
434 |
435 | def action_cursor_up(self) -> None:
436 | self.timeline_table.action_cursor_up()
437 |
438 | def action_cursor_down(self) -> None:
439 | if self.timeline_table.cursor_row == self.timeline_table.row_count - 1:
440 | old_row_index = self.timeline_table.cursor_row
441 | self.action_update_timeline_old()
442 | self.timeline_table.move_cursor(row=old_row_index)
443 |
444 | self.timeline_table.action_cursor_down()
445 |
446 | def action_select_row(self) -> None:
447 | self.timeline_table.action_select_cursor()
448 |
--------------------------------------------------------------------------------
/fediboat/settings.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 | from pathlib import Path
3 |
4 | import tomllib
5 | from pydantic import BaseModel
6 |
7 | from fediboat.entities import NotificationTypeEnum
8 |
9 |
10 | class AppSettings(BaseModel):
11 | client_id: str
12 | client_secret: str
13 |
14 |
15 | class UserSettings(BaseModel):
16 | id: str
17 | instance: str
18 | access_token: str
19 |
20 |
21 | class AuthSettingsJson(BaseModel):
22 | """Used to validate json file structure"""
23 |
24 | current: str
25 | apps: dict[str, AppSettings]
26 | users: dict[str, UserSettings]
27 |
28 |
29 | class AuthSettings(BaseModel):
30 | """Settings for the current active user"""
31 |
32 | id: str
33 | instance_url: str
34 | instance_domain: str
35 | full_username: str
36 | access_token: str
37 |
38 | client_id: str
39 | client_secret: str
40 |
41 |
42 | class NotificationsConfig(BaseModel):
43 | show: list[NotificationTypeEnum] = [
44 | NotificationTypeEnum.favourite,
45 | NotificationTypeEnum.mention,
46 | NotificationTypeEnum.reblog,
47 | NotificationTypeEnum.follow,
48 | ]
49 | signs: dict[NotificationTypeEnum, tuple[str, str]] = {}
50 |
51 |
52 | class Config(BaseModel):
53 | editor: str = "vim"
54 | notifications: NotificationsConfig = NotificationsConfig()
55 |
56 |
57 | @dataclass
58 | class Settings:
59 | auth: AuthSettings
60 | config: Config
61 |
62 |
63 | class LoadSettingsError(Exception):
64 | pass
65 |
66 |
67 | def _load_auth_settings(auth_settings_file: Path) -> AuthSettings:
68 | auth_settings_raw_json = auth_settings_file.read_text()
69 | auth_settings_json = AuthSettingsJson.model_validate_json(auth_settings_raw_json)
70 |
71 | user_data = auth_settings_json.users[auth_settings_json.current]
72 | app = auth_settings_json.apps[user_data.instance]
73 | instance_url = "https://" + user_data.instance
74 |
75 | return AuthSettings(
76 | id=user_data.id,
77 | instance_url=instance_url,
78 | instance_domain=user_data.instance,
79 | full_username=auth_settings_json.current,
80 | access_token=user_data.access_token,
81 | client_id=app.client_id,
82 | client_secret=app.client_secret,
83 | )
84 |
85 |
86 | def create_auth_settings(auth_settings_file: Path, auth_settings: AuthSettings) -> None:
87 | auth_settings_file.parent.mkdir(parents=True, exist_ok=True)
88 | auth_settings_json = AuthSettingsJson(
89 | current=auth_settings.full_username,
90 | apps={
91 | auth_settings.instance_domain: AppSettings(
92 | client_id=auth_settings.client_id,
93 | client_secret=auth_settings.client_secret,
94 | ),
95 | },
96 | users={
97 | auth_settings.full_username: UserSettings(
98 | id=auth_settings.id,
99 | instance=auth_settings.instance_domain,
100 | access_token=auth_settings.access_token,
101 | ),
102 | },
103 | )
104 | auth_settings_raw_json = auth_settings_json.model_dump_json(indent=4)
105 | auth_settings_file.write_text(auth_settings_raw_json)
106 |
107 |
108 | def _load_config(config_file: Path) -> Config:
109 | if not (config_file.exists() and config_file.is_file()):
110 | return Config()
111 |
112 | with open(config_file, "rb") as f:
113 | config_toml = tomllib.load(f)
114 | config = Config.model_validate(config_toml)
115 | default_signs: dict[NotificationTypeEnum, tuple[str, str]] = {
116 | NotificationTypeEnum.favourite: ("★", "#FFD32C"),
117 | NotificationTypeEnum.mention: ("@", "#82C8E5"),
118 | NotificationTypeEnum.reblog: ("⮂", "#79BD9A"),
119 | NotificationTypeEnum.follow: ("+", ""),
120 | NotificationTypeEnum.follow_request: ("r", ""),
121 | NotificationTypeEnum.moderation_warning: ("w", "#C04657"),
122 | }
123 |
124 | config.notifications.signs = {**default_signs, **config.notifications.signs}
125 | return config
126 |
127 |
128 | def load_settings(auth_settings_file: Path, config_file: Path) -> Settings:
129 | if not (auth_settings_file.exists() and auth_settings_file.is_file()):
130 | raise LoadSettingsError(f"{auth_settings_file} does not exist!")
131 |
132 | auth_settings = _load_auth_settings(auth_settings_file)
133 | config = _load_config(config_file)
134 | return Settings(auth_settings, config)
135 |
--------------------------------------------------------------------------------
/fediboat/timeline.tcss:
--------------------------------------------------------------------------------
1 | Screen {
2 | align: center top;
3 | }
4 |
5 | StatusContent {
6 | align: center top;
7 | }
8 |
9 | #md {
10 | align: center middle;
11 | width: 60%;
12 | max-width: 50%;
13 | min-width: 90%;
14 | margin: 1 0;
15 | }
16 |
17 | ErrorMessage {
18 | align: center middle;
19 | }
20 |
21 | #dialog {
22 | grid-size: 2;
23 | grid-gutter: 1 2;
24 | grid-rows: 1fr 3;
25 | padding: 0 1;
26 | width: 60;
27 | height: 11;
28 | border: thick $background 80%;
29 | background: $surface;
30 | }
31 |
32 | #message {
33 | column-span: 2;
34 | height: 1fr;
35 | width: 1fr;
36 | content-align: center middle;
37 | }
38 |
39 | #timeline {
40 | width: auto;
41 | overflow-x: hidden;
42 | scrollbar-size-vertical: 0;
43 | }
44 |
45 | DataTable > .datatable--cursor {
46 | background: #8FBC8F;
47 | color: $text;
48 | }
49 |
50 |
51 | Jump {
52 | align: left bottom;
53 | }
54 |
55 | SwitchTimeline {
56 | layout: vertical;
57 | overflow-y: auto;
58 | background: $background 0%;
59 | }
60 |
61 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=64", "setuptools-scm>=8"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "fediboat"
7 | dynamic = ["version"]
8 | authors = [
9 | { name="LoRiot", email="lo_riot@riseup.net" },
10 | ]
11 | description = "Fediboat - Mastodon TUI client with a Newsboat-like interface."
12 | readme = "README.md"
13 | requires-python = ">=3.8"
14 | classifiers = [
15 | "Programming Language :: Python :: 3",
16 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
17 | "Operating System :: POSIX :: Linux",
18 | ]
19 | dependencies = [
20 | "textual~=1.0.0",
21 | "beautifulsoup4>=4.12.3,<5.0",
22 | "requests>=2.32.3,<3.0",
23 | "click~=8.1",
24 | "pydantic>=2.10.4,<3.0",
25 | ]
26 |
27 | [tool.setuptools_scm]
28 |
29 | [project.urls]
30 | Homepage = "https://github.com/Lo-Riot/fediboat"
31 | Issues = "https://github.com/Lo-Riot/fediboat/issues"
32 |
33 | [project.scripts]
34 | fediboat = "fediboat.cli:cli"
35 |
36 | [tool.setuptools]
37 | packages=[
38 | "fediboat",
39 | "fediboat.api"
40 | ]
41 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | asyncio_default_fixture_loop_scope = module
3 | asyncio_mode = auto
4 | filterwarnings =
5 | ignore::bs4.MarkupResemblesLocatorWarning
6 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import json
2 | from unittest.mock import MagicMock
3 |
4 | import pytest
5 | from pydantic import TypeAdapter
6 | from requests import Session
7 |
8 | from fediboat.api.timelines import (
9 | context_to_entities,
10 | notifications_to_entities,
11 | statuses_to_entities,
12 | )
13 | from fediboat.entities import Context, Notification, Status
14 | from fediboat.settings import AuthSettings
15 | from tests.test_api import ExpectedResponse, ExpectedThreadResponse, ResponseData
16 |
17 |
18 | @pytest.fixture(scope="session")
19 | def settings() -> AuthSettings:
20 | return AuthSettings(
21 | id="123456",
22 | instance_url="http://localhost",
23 | instance_domain="localhost",
24 | full_username="test_user@localhost",
25 | access_token="123",
26 | client_id="1234",
27 | client_secret="12345",
28 | )
29 |
30 |
31 | @pytest.fixture(scope="module")
32 | def session() -> MagicMock:
33 | response_mock = MagicMock()
34 | get_request_mock = MagicMock(return_value=response_mock)
35 | session_mock = MagicMock(spec_set=Session, get=get_request_mock)
36 | return session_mock
37 |
38 |
39 | @pytest.fixture(scope="session")
40 | def statuses_validator() -> TypeAdapter[list[Status]]:
41 | return TypeAdapter(list[Status])
42 |
43 |
44 | @pytest.fixture(scope="session")
45 | def notifications_validator() -> TypeAdapter[list[Notification]]:
46 | return TypeAdapter(list[Notification])
47 |
48 |
49 | @pytest.fixture(scope="session")
50 | def expected_statuses(
51 | statuses_validator: TypeAdapter[list[Status]],
52 | ) -> ExpectedResponse:
53 | with open("tests/data/statuses.json") as f:
54 | new_json = json.load(f)
55 | new_statuses = statuses_validator.validate_python(new_json)
56 | new_entities = statuses_to_entities(new_statuses)
57 |
58 | with open("tests/data/old_statuses.json") as f:
59 | old_json = json.load(f)
60 | old_statuses = statuses_validator.validate_python(old_json)
61 | old_entities = statuses_to_entities(old_statuses)
62 |
63 | return ExpectedResponse(
64 | ResponseData(new_json, new_entities),
65 | ResponseData(old_json, old_entities),
66 | )
67 |
68 |
69 | @pytest.fixture(scope="session")
70 | def expected_notifications(
71 | notifications_validator: TypeAdapter[list[Notification]],
72 | ) -> ExpectedResponse:
73 | with open("tests/data/notifications.json") as f:
74 | new_json = json.load(f)
75 | new_notifications = notifications_validator.validate_python(new_json)
76 | new_entities = notifications_to_entities(new_notifications)
77 |
78 | with open("tests/data/old_notifications.json") as f:
79 | old_json = json.load(f)
80 | old_notifications = notifications_validator.validate_python(old_json)
81 | old_entities = notifications_to_entities(old_notifications)
82 |
83 | return ExpectedResponse(
84 | ResponseData(new_json, new_entities),
85 | ResponseData(old_json, old_entities),
86 | )
87 |
88 |
89 | @pytest.fixture(scope="session")
90 | def expected_thread() -> ExpectedThreadResponse:
91 | with open("tests/data/thread_status.json") as f:
92 | thread_status = Status.model_validate_json(f.read())
93 |
94 | with open("tests/data/new_thread_statuses.json") as f:
95 | new_json = json.load(f)
96 | new_context = Context.model_validate(new_json)
97 | new_entities = context_to_entities(new_context, thread_status)
98 |
99 | with open("tests/data/old_thread_statuses.json") as f:
100 | old_json = json.load(f)
101 | old_context = Context.model_validate(old_json)
102 | old_entities = context_to_entities(old_context, thread_status)
103 |
104 | return ExpectedThreadResponse(
105 | ResponseData(
106 | new_json,
107 | new_entities,
108 | ),
109 | ResponseData(
110 | old_json,
111 | old_entities,
112 | ),
113 | thread_status,
114 | )
115 |
--------------------------------------------------------------------------------
/tests/data/new_thread_statuses.json:
--------------------------------------------------------------------------------
1 | {
2 | "ancestors": [
3 | {
4 | "id": "10987654321",
5 | "created_at": "2024-12-01T15:04:05.000Z",
6 | "in_reply_to_id": null,
7 | "in_reply_to_account_id": null,
8 | "sensitive": false,
9 | "spoiler_text": "",
10 | "visibility": "public",
11 | "language": "en",
12 | "uri": "https://example.com/users/user/statuses/10987654321",
13 | "url": "https://example.com/@user/10987654321",
14 | "replies_count": 2,
15 | "reblogs_count": 0,
16 | "favourites_count": 5,
17 | "edited_at": null,
18 | "content": "This is the root status in the thread.
",
19 | "reblog": null,
20 | "account": {
21 | "id": "12345",
22 | "username": "user",
23 | "acct": "user@example.com",
24 | "display_name": "User Name",
25 | "locked": false,
26 | "bot": false,
27 | "discoverable": true,
28 | "group": false,
29 | "created_at": "2023-01-01T12:00:00.000Z",
30 | "note": "Hello, I am a user!
",
31 | "url": "https://example.com/@user",
32 | "avatar": "https://example.com/avatar.jpg",
33 | "avatar_static": "https://example.com/avatar.jpg",
34 | "header": "https://example.com/header.jpg",
35 | "header_static": "https://example.com/header.jpg",
36 | "followers_count": 100,
37 | "following_count": 50,
38 | "statuses_count": 10,
39 | "last_status_at": "2024-12-01",
40 | "emojis": [],
41 | "fields": []
42 | },
43 | "media_attachments": [],
44 | "mentions": [],
45 | "tags": [],
46 | "emojis": [],
47 | "card": null,
48 | "poll": null
49 | }
50 | ],
51 | "descendants": [
52 | {
53 | "id": "10987654322",
54 | "created_at": "2024-12-01T15:10:00.000Z",
55 | "in_reply_to_id": "10987654321",
56 | "in_reply_to_account_id": "12345",
57 | "sensitive": false,
58 | "spoiler_text": "",
59 | "visibility": "public",
60 | "language": "en",
61 | "uri": "https://example.com/users/another_user/statuses/10987654322",
62 | "url": "https://example.com/@another_user/10987654322",
63 | "replies_count": 1,
64 | "reblogs_count": 0,
65 | "favourites_count": 2,
66 | "edited_at": null,
67 | "content": "This is a reply to the root status.
",
68 | "reblog": null,
69 | "account": {
70 | "id": "54321",
71 | "username": "another_user",
72 | "acct": "another_user@example.com",
73 | "display_name": "Another User",
74 | "locked": false,
75 | "bot": false,
76 | "discoverable": true,
77 | "group": false,
78 | "created_at": "2023-02-01T12:00:00.000Z",
79 | "note": "Hello, I am another user!
",
80 | "url": "https://example.com/@another_user",
81 | "avatar": "https://example.com/another_avatar.jpg",
82 | "avatar_static": "https://example.com/another_avatar.jpg",
83 | "header": "https://example.com/another_header.jpg",
84 | "header_static": "https://example.com/another_header.jpg",
85 | "followers_count": 50,
86 | "following_count": 20,
87 | "statuses_count": 5,
88 | "last_status_at": "2024-12-01",
89 | "emojis": [],
90 | "fields": []
91 | },
92 | "media_attachments": [],
93 | "mentions": [
94 | {
95 | "id": "12345",
96 | "username": "user",
97 | "url": "https://example.com/@user",
98 | "acct": "user@example.com"
99 | }
100 | ],
101 | "tags": [],
102 | "emojis": [],
103 | "card": null,
104 | "poll": null
105 | },
106 | {
107 | "id": "10987654323",
108 | "created_at": "2024-12-01T15:20:00.000Z",
109 | "in_reply_to_id": "10987654322",
110 | "in_reply_to_account_id": "54321",
111 | "sensitive": false,
112 | "spoiler_text": "",
113 | "visibility": "public",
114 | "language": "en",
115 | "uri": "https://example.com/users/yet_another_user/statuses/10987654323",
116 | "url": "https://example.com/@yet_another_user/10987654323",
117 | "replies_count": 0,
118 | "reblogs_count": 0,
119 | "favourites_count": 1,
120 | "edited_at": null,
121 | "content": "This is a reply to another user's reply.
",
122 | "reblog": null,
123 | "account": {
124 | "id": "67890",
125 | "username": "yet_another_user",
126 | "acct": "yet_another_user@example.com",
127 | "display_name": "Yet Another User",
128 | "locked": false,
129 | "bot": false,
130 | "discoverable": true,
131 | "group": false,
132 | "created_at": "2023-03-01T12:00:00.000Z",
133 | "note": "Hello, I am yet another user!
",
134 | "url": "https://example.com/@yet_another_user",
135 | "avatar": "https://example.com/yet_another_avatar.jpg",
136 | "avatar_static": "https://example.com/yet_another_avatar.jpg",
137 | "header": "https://example.com/yet_another_header.jpg",
138 | "header_static": "https://example.com/yet_another_header.jpg",
139 | "followers_count": 30,
140 | "following_count": 10,
141 | "statuses_count": 3,
142 | "last_status_at": "2024-12-01",
143 | "emojis": [],
144 | "fields": []
145 | },
146 | "media_attachments": [],
147 | "mentions": [
148 | {
149 | "id": "54321",
150 | "username": "another_user",
151 | "url": "https://example.com/@another_user",
152 | "acct": "another_user@example.com"
153 | }
154 | ],
155 | "tags": [],
156 | "emojis": [],
157 | "card": null,
158 | "poll": null
159 | }
160 | ]
161 | }
162 |
--------------------------------------------------------------------------------
/tests/data/notifications.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "34975861",
4 | "type": "mention",
5 | "created_at": "2019-11-23T07:49:02.064Z",
6 | "account":
7 | {
8 | "id": "23634",
9 | "username": "noiob",
10 | "acct": "noiob@awoo.space",
11 | "display_name": "ikea shark fan account",
12 | "locked": false,
13 | "bot": false,
14 | "group": false,
15 | "created_at": "2017-02-08T02:00:53.274Z",
16 | "note": ":ms_rainbow_flag: :ms_bisexual_flagweb: :ms_nonbinary_flag: #awoo#admin#bi#nonbinary#games@dzuk
",
17 | "url": "https://awoo.space/@noiob",
18 | "avatar": "https://files.mastodon.social/accounts/avatars/000/023/634/original/6ca8804dc46800ad.png",
19 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/023/634/original/6ca8804dc46800ad.png",
20 | "header": "https://files.mastodon.social/accounts/headers/000/023/634/original/256eb8d7ac40f49a.png",
21 | "header_static": "https://files.mastodon.social/accounts/headers/000/023/634/original/256eb8d7ac40f49a.png",
22 | "followers_count": 547,
23 | "following_count": 404,
24 | "statuses_count": 28468,
25 | "last_status_at": "2019-11-17",
26 | "emojis": [
27 | {
28 | "shortcode": "ms_rainbow_flag",
29 | "url": "https://files.mastodon.social/custom_emojis/images/000/028/691/original/6de008d6281f4f59.png",
30 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/028/691/static/6de008d6281f4f59.png",
31 | "visible_in_picker": true
32 | },
33 | {
34 | "shortcode": "ms_bisexual_flag",
35 | "url": "https://files.mastodon.social/custom_emojis/images/000/050/744/original/02f94a5fca7eaf78.png",
36 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/050/744/static/02f94a5fca7eaf78.png",
37 | "visible_in_picker": true
38 | },
39 | {
40 | "shortcode": "ms_nonbinary_flag",
41 | "url": "https://files.mastodon.social/custom_emojis/images/000/105/099/original/8106088bd4782072.png",
42 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/105/099/static/8106088bd4782072.png",
43 | "visible_in_picker": true
44 | }
45 | ],
46 | "fields": [
47 | {
48 | "name": "Pronouns",
49 | "value": "they/them",
50 | "verified_at": null
51 | },
52 | {
53 | "name": "Alt",
54 | "value": "@noiob",
55 | "verified_at": null
56 | },
57 | {
58 | "name": "Bots",
59 | "value": "@darksouls, @nierautomata, @fedi, code for @awoobot",
60 | "verified_at": null
61 | },
62 | {
63 | "name": "Website",
64 | "value": "http://shork.xyz"I lost my inheritance with one wrong digit on my sort code"
https://www.theguardian.com/money/2019/dec/07/i-lost-my-193000-inheritance-with-one-wrong-digit-on-my-sort-code",
88 | "reblog": null,
89 | "application": {
90 | "name": "Web",
91 | "website": null
92 | },
93 | "account": {
94 | "id": "1",
95 | "username": "Gargron",
96 | "acct": "Gargron",
97 | "display_name": "Eugen",
98 | "locked": false,
99 | "bot": false,
100 | "discoverable": true,
101 | "group": false,
102 | "created_at": "2016-03-16T14:34:26.392Z",
103 | "note": "Developer of Mastodon and administrator of mastodon.social. I post service announcements, development updates, and personal stuff.
",
104 | "url": "https://mastodon.social/@Gargron",
105 | "avatar": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
106 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
107 | "header": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
108 | "header_static": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
109 | "followers_count": 322930,
110 | "following_count": 459,
111 | "statuses_count": 61323,
112 | "last_status_at": "2019-12-10T08:14:44.811Z",
113 | "emojis": [],
114 | "fields": [
115 | {
116 | "name": "Patreon",
117 | "value": "https://www.patreon.com/mastodonhttps://zeonfederated.com:ms_rainbow_flag: :ms_bisexual_flagweb: :ms_nonbinary_flag: #awoo#admin#bi#nonbinary#games@dzuk
",
17 | "url": "https://awoo.space/@noiob",
18 | "avatar": "https://files.mastodon.social/accounts/avatars/000/023/634/original/6ca8804dc46800ad.png",
19 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/023/634/original/6ca8804dc46800ad.png",
20 | "header": "https://files.mastodon.social/accounts/headers/000/023/634/original/256eb8d7ac40f49a.png",
21 | "header_static": "https://files.mastodon.social/accounts/headers/000/023/634/original/256eb8d7ac40f49a.png",
22 | "followers_count": 547,
23 | "following_count": 404,
24 | "statuses_count": 28468,
25 | "last_status_at": "2019-11-17",
26 | "emojis": [
27 | {
28 | "shortcode": "ms_rainbow_flag",
29 | "url": "https://files.mastodon.social/custom_emojis/images/000/028/691/original/6de008d6281f4f59.png",
30 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/028/691/static/6de008d6281f4f59.png",
31 | "visible_in_picker": true
32 | },
33 | {
34 | "shortcode": "ms_bisexual_flag",
35 | "url": "https://files.mastodon.social/custom_emojis/images/000/050/744/original/02f94a5fca7eaf78.png",
36 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/050/744/static/02f94a5fca7eaf78.png",
37 | "visible_in_picker": true
38 | },
39 | {
40 | "shortcode": "ms_nonbinary_flag",
41 | "url": "https://files.mastodon.social/custom_emojis/images/000/105/099/original/8106088bd4782072.png",
42 | "static_url": "https://files.mastodon.social/custom_emojis/images/000/105/099/static/8106088bd4782072.png",
43 | "visible_in_picker": true
44 | }
45 | ],
46 | "fields": [
47 | {
48 | "name": "Pronouns",
49 | "value": "they/them",
50 | "verified_at": null
51 | },
52 | {
53 | "name": "Alt",
54 | "value": "@noiob",
55 | "verified_at": null
56 | },
57 | {
58 | "name": "Bots",
59 | "value": "@darksouls, @nierautomata, @fedi, code for @awoobot",
60 | "verified_at": null
61 | },
62 | {
63 | "name": "Website",
64 | "value": "http://shork.xyz"I lost my inheritance with one wrong digit on my sort code"https://www.theguardian.com/money/2019/dec/07/i-lost-my-193000-inheritance-with-one-wrong-digit-on-my-sort-code",
88 | "reblog": null,
89 | "application": {
90 | "name": "Web",
91 | "website": null
92 | },
93 | "account": {
94 | "id": "1",
95 | "username": "Gargron",
96 | "acct": "Gargron",
97 | "display_name": "Eugen",
98 | "locked": false,
99 | "bot": false,
100 | "discoverable": true,
101 | "group": false,
102 | "created_at": "2016-03-16T14:34:26.392Z",
103 | "note": "Developer of Mastodon and administrator of mastodon.social. I post service announcements, development updates, and personal stuff.
",
104 | "url": "https://mastodon.social/@Gargron",
105 | "avatar": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
106 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
107 | "header": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
108 | "header_static": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
109 | "followers_count": 322930,
110 | "following_count": 459,
111 | "statuses_count": 61323,
112 | "last_status_at": "2019-12-10T08:14:44.811Z",
113 | "emojis": [],
114 | "fields": [
115 | {
116 | "name": "Patreon",
117 | "value": "https://www.patreon.com/mastodonhttps://zeonfederated.com"I lost my inheritance with one wrong digit on my sort code"
https://www.theguardian.com/money/2019/dec/07/i-lost-my-193000-inheritance-with-one-wrong-digit-on-my-sort-code",
21 | "reblog": null,
22 | "application": {
23 | "name": "Web",
24 | "website": null
25 | },
26 | "account": {
27 | "id": "1",
28 | "username": "Gargron",
29 | "acct": "Gargron",
30 | "display_name": "Eugen",
31 | "locked": false,
32 | "bot": false,
33 | "discoverable": true,
34 | "group": false,
35 | "created_at": "2016-03-16T14:34:26.392Z",
36 | "note": "Developer of Mastodon and administrator of mastodon.social. I post service announcements, development updates, and personal stuff.
",
37 | "url": "https://mastodon.social/@Gargron",
38 | "avatar": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
39 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
40 | "header": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
41 | "header_static": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
42 | "followers_count": 322930,
43 | "following_count": 459,
44 | "statuses_count": 61323,
45 | "last_status_at": "2019-12-10T08:14:44.811Z",
46 | "emojis": [],
47 | "fields": [
48 | {
49 | "name": "Patreon",
50 | "value": "https://www.patreon.com/mastodonhttps://zeonfederated.comThis is the root status in the thread.
",
19 | "reblog": null,
20 | "account": {
21 | "id": "12345",
22 | "username": "user",
23 | "acct": "user@example.com",
24 | "display_name": "User Name",
25 | "locked": false,
26 | "bot": false,
27 | "discoverable": true,
28 | "group": false,
29 | "created_at": "2023-01-01T12:00:00.000Z",
30 | "note": "Hello, I am a user!
",
31 | "url": "https://example.com/@user",
32 | "avatar": "https://example.com/avatar.jpg",
33 | "avatar_static": "https://example.com/avatar.jpg",
34 | "header": "https://example.com/header.jpg",
35 | "header_static": "https://example.com/header.jpg",
36 | "followers_count": 100,
37 | "following_count": 50,
38 | "statuses_count": 10,
39 | "last_status_at": "2024-12-01",
40 | "emojis": [],
41 | "fields": []
42 | },
43 | "media_attachments": [],
44 | "mentions": [],
45 | "tags": [],
46 | "emojis": [],
47 | "card": null,
48 | "poll": null
49 | }
50 | ],
51 | "descendants": [
52 | {
53 | "id": "10987654322",
54 | "created_at": "2024-12-01T15:10:00.000Z",
55 | "in_reply_to_id": "10987654321",
56 | "in_reply_to_account_id": "12345",
57 | "sensitive": false,
58 | "spoiler_text": "",
59 | "visibility": "public",
60 | "language": "en",
61 | "uri": "https://example.com/users/another_user/statuses/10987654322",
62 | "url": "https://example.com/@another_user/10987654322",
63 | "replies_count": 0,
64 | "reblogs_count": 0,
65 | "favourites_count": 2,
66 | "edited_at": null,
67 | "content": "This is a reply to the root status.
",
68 | "reblog": null,
69 | "account": {
70 | "id": "54321",
71 | "username": "another_user",
72 | "acct": "another_user@example.com",
73 | "display_name": "Another User",
74 | "locked": false,
75 | "bot": false,
76 | "discoverable": true,
77 | "group": false,
78 | "created_at": "2023-02-01T12:00:00.000Z",
79 | "note": "Hello, I am another user!
",
80 | "url": "https://example.com/@another_user",
81 | "avatar": "https://example.com/another_avatar.jpg",
82 | "avatar_static": "https://example.com/another_avatar.jpg",
83 | "header": "https://example.com/another_header.jpg",
84 | "header_static": "https://example.com/another_header.jpg",
85 | "followers_count": 50,
86 | "following_count": 20,
87 | "statuses_count": 5,
88 | "last_status_at": "2024-12-01",
89 | "emojis": [],
90 | "fields": []
91 | },
92 | "media_attachments": [],
93 | "mentions": [
94 | {
95 | "id": "12345",
96 | "username": "user",
97 | "url": "https://example.com/@user",
98 | "acct": "user@example.com"
99 | }
100 | ],
101 | "tags": [],
102 | "emojis": [],
103 | "card": null,
104 | "poll": null
105 | }
106 | ]
107 | }
108 |
--------------------------------------------------------------------------------
/tests/data/statuses.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": "103270115826048975",
4 | "created_at": "2019-12-08T03:48:33.901Z",
5 | "in_reply_to_id": null,
6 | "in_reply_to_account_id": null,
7 | "sensitive": false,
8 | "spoiler_text": "",
9 | "visibility": "public",
10 | "language": "en",
11 | "uri": "https://mastodon.social/users/Gargron/statuses/103270115826048975",
12 | "url": "https://mastodon.social/@Gargron/103270115826048975",
13 | "replies_count": 5,
14 | "reblogs_count": 6,
15 | "favourites_count": 11,
16 | "favourited": false,
17 | "reblogged": false,
18 | "muted": false,
19 | "bookmarked": false,
20 | "content": ""I lost my inheritance with one wrong digit on my sort code"
https://www.theguardian.com/money/2019/dec/07/i-lost-my-193000-inheritance-with-one-wrong-digit-on-my-sort-code",
21 | "reblog": null,
22 | "application": {
23 | "name": "Web",
24 | "website": null
25 | },
26 | "account": {
27 | "id": "1",
28 | "username": "Gargron",
29 | "acct": "Gargron",
30 | "display_name": "Eugen",
31 | "locked": false,
32 | "bot": false,
33 | "discoverable": true,
34 | "group": false,
35 | "created_at": "2016-03-16T14:34:26.392Z",
36 | "note": "Developer of Mastodon and administrator of mastodon.social. I post service announcements, development updates, and personal stuff.
",
37 | "url": "https://mastodon.social/@Gargron",
38 | "avatar": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
39 | "avatar_static": "https://files.mastodon.social/accounts/avatars/000/000/001/original/d96d39a0abb45b92.jpg",
40 | "header": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
41 | "header_static": "https://files.mastodon.social/accounts/headers/000/000/001/original/c91b871f294ea63e.png",
42 | "followers_count": 322930,
43 | "following_count": 459,
44 | "statuses_count": 61323,
45 | "last_status_at": "2019-12-10T08:14:44.811Z",
46 | "emojis": [],
47 | "fields": [
48 | {
49 | "name": "Patreon",
50 | "value": "https://www.patreon.com/mastodonhttps://zeonfederated.comThis is the main status for which the context is provided.
",
17 | "reblog": null,
18 | "application": {
19 | "name": "MainApp",
20 | "website": "https://mainapp.example.com"
21 | },
22 | "account": {
23 | "id": "67890",
24 | "username": "main_user",
25 | "acct": "main_user@example.com",
26 | "display_name": "Main User",
27 | "locked": false,
28 | "bot": false,
29 | "discoverable": true,
30 | "group": false,
31 | "created_at": "2023-04-01T12:00:00.000Z",
32 | "note": "This is the main user's bio.
",
33 | "url": "https://example.com/@main_user",
34 | "avatar": "https://example.com/main_avatar.jpg",
35 | "avatar_static": "https://example.com/main_avatar.jpg",
36 | "header": "https://example.com/main_header.jpg",
37 | "header_static": "https://example.com/main_header.jpg",
38 | "followers_count": 200,
39 | "following_count": 150,
40 | "statuses_count": 20,
41 | "last_status_at": "2024-12-02",
42 | "emojis": [],
43 | "fields": []
44 | },
45 | "media_attachments": [],
46 | "mentions": [
47 | {
48 | "id": "54321",
49 | "username": "another_user",
50 | "url": "https://example.com/@another_user",
51 | "acct": "another_user@example.com"
52 | }
53 | ],
54 | "tags": [
55 | {
56 | "name": "ExampleTag",
57 | "url": "https://example.com/t/ExampleTag"
58 | }
59 | ],
60 | "emojis": [],
61 | "card": null,
62 | "poll": null,
63 | "quote": null
64 | }
65 |
--------------------------------------------------------------------------------
/tests/test_api.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 | from typing import Any, Callable, Generator, NamedTuple
3 | from unittest.mock import MagicMock
4 |
5 | import pytest
6 |
7 | from fediboat.api.timelines import (
8 | notification_timeline_generator,
9 | status_timeline_generator,
10 | thread_fetcher,
11 | )
12 | from fediboat.entities import Status, TUIEntity
13 | from fediboat.settings import AuthSettings
14 |
15 |
16 | class ResponseData(NamedTuple):
17 | json: Any
18 | validated: list[TUIEntity]
19 |
20 |
21 | @dataclass
22 | class ExpectedResponse:
23 | new: ResponseData
24 | old: ResponseData
25 |
26 |
27 | @dataclass
28 | class ExpectedThreadResponse(ExpectedResponse):
29 | status: Status
30 |
31 |
32 | @pytest.mark.parametrize(
33 | "timeline_generator,expected_entities_fixture",
34 | [
35 | (status_timeline_generator, "expected_statuses"),
36 | (notification_timeline_generator, "expected_notifications"),
37 | ],
38 | )
39 | def test_timeline_api(
40 | session: MagicMock,
41 | timeline_generator: Callable[..., Generator[list[TUIEntity], None, None]],
42 | expected_entities_fixture: str,
43 | settings: AuthSettings,
44 | monkeypatch: pytest.MonkeyPatch,
45 | request: pytest.FixtureRequest,
46 | ):
47 | expected_response: ExpectedResponse = request.getfixturevalue(
48 | expected_entities_fixture
49 | )
50 | response_mock = session.get.return_value
51 | response_mock.json.return_value = expected_response.new.json
52 | timeline = timeline_generator(
53 | session, f"{settings.instance_url}/api/endpoint", limit=20
54 | )
55 |
56 | response_entities = next(timeline)
57 | session.get.assert_called_with(f"{settings.instance_url}/api/endpoint?limit=20")
58 | assert len(response_entities) == 1
59 | assert len(expected_response.new.validated) == 1
60 | assert response_entities == expected_response.new.validated
61 |
62 | response_mock.json.return_value = expected_response.old.json
63 | response_mock.links = {
64 | "next": {
65 | "url": f"{settings.instance_url}/api/endpoint?max_id=7163058",
66 | "rel": "next",
67 | }
68 | }
69 | response_entities = next(timeline)
70 | assert len(expected_response.old.validated) == 1
71 | assert response_entities == expected_response.old.validated
72 |
73 | with pytest.raises(StopIteration):
74 | response_entities = next(timeline)
75 |
76 |
77 | def test_thread_api(
78 | session: MagicMock, expected_thread: ExpectedThreadResponse, settings: AuthSettings
79 | ):
80 | response_mock = session.get.return_value
81 | response_mock.json.return_value = expected_thread.old.json
82 |
83 | fetch_thread = thread_fetcher(session, settings, expected_thread.status)
84 | statuses = fetch_thread()
85 | session.get.assert_called_with(
86 | f"{settings.instance_url}/api/v1/statuses/{expected_thread.status.id}/context"
87 | )
88 | assert statuses == expected_thread.old.validated
89 |
90 | response_mock.json.return_value = expected_thread.new.json
91 | statuses = fetch_thread()
92 | assert statuses == expected_thread.new.validated
93 |
--------------------------------------------------------------------------------
/tests/test_tui.py:
--------------------------------------------------------------------------------
1 | from unittest.mock import MagicMock
2 |
3 | import pytest
4 | from rich.text import Text
5 | from textual.widgets import DataTable
6 |
7 | from fediboat.api.timelines import get_timelines
8 | from fediboat.cli import FediboatApp
9 | from fediboat.screens import StatusContent, SwitchTimeline, TimelineScreen
10 | from fediboat.settings import AuthSettings, Config, Settings
11 | from tests.test_api import ExpectedResponse, ExpectedThreadResponse
12 |
13 | ID_COLUMN: int = 0
14 | AUTHOR_COLUMN: int = 2
15 |
16 | FIRST_ROW_INDEX: int = 0
17 | LAST_ROW_INDEX: int = 1
18 |
19 | FOOTER_MENU_KEY: str = "g"
20 | BACK_OR_EXIT_KEY: str = "q"
21 | DOWN_KEY: str = "j"
22 | OPEN_THREAD_KEY: str = "t"
23 |
24 |
25 | @pytest.fixture
26 | def app(
27 | settings: AuthSettings, session: MagicMock, expected_statuses: ExpectedResponse
28 | ) -> FediboatApp:
29 | all_settings = Settings(settings, Config())
30 | timeline = TimelineScreen(
31 | get_timelines(all_settings.config),
32 | all_settings,
33 | session,
34 | refresh_at_start=False,
35 | )
36 | return FediboatApp(timeline)
37 |
38 |
39 | @pytest.mark.parametrize(
40 | "select_timeline_key,expected_entities_fixture,timeline_name",
41 | [
42 | ("h", "expected_statuses", "Home"),
43 | ("n", "expected_notifications", "Notifications"),
44 | ],
45 | )
46 | async def test_timelines(
47 | app: FediboatApp,
48 | session: MagicMock,
49 | select_timeline_key: str,
50 | expected_entities_fixture: str,
51 | timeline_name: str,
52 | settings: AuthSettings,
53 | expected_thread: ExpectedThreadResponse,
54 | request: pytest.FixtureRequest,
55 | ):
56 | expected_response: ExpectedResponse = request.getfixturevalue(
57 | expected_entities_fixture
58 | )
59 |
60 | async with app.run_test() as pilot:
61 | assert isinstance(app.screen, TimelineScreen)
62 |
63 | await pilot.press(FOOTER_MENU_KEY)
64 | assert isinstance(app.screen, SwitchTimeline)
65 |
66 | response_mock = session.get.return_value
67 | response_mock.json.return_value = expected_response.new.json
68 | await pilot.press(select_timeline_key)
69 |
70 | timeline = app.screen.query_one(DataTable)
71 | assert timeline.row_count == 1
72 |
73 | row: list[Text] = timeline.get_row_at(FIRST_ROW_INDEX)
74 | assert row[ID_COLUMN] == Text("1")
75 | assert row[AUTHOR_COLUMN] == Text(expected_response.new.validated[0].author)
76 |
77 | await pilot.press("enter")
78 | assert len(app.screen_stack) == 3
79 | assert isinstance(app.screen, StatusContent)
80 |
81 | await pilot.press(BACK_OR_EXIT_KEY)
82 | assert len(app.screen_stack) == 2
83 | assert isinstance(app.screen, TimelineScreen)
84 |
85 | # Test updating old entities
86 | response_mock.json.return_value = expected_response.old.json
87 | await pilot.press(DOWN_KEY)
88 | assert timeline.row_count == 2
89 |
90 | assert app.screen.entities[LAST_ROW_INDEX] == expected_response.old.validated[0]
91 | row: list[Text] = timeline.get_row_at(LAST_ROW_INDEX)
92 | assert row[ID_COLUMN] == Text("2")
93 |
94 | await pilot.press(DOWN_KEY)
95 | assert timeline.row_count == 2
96 | with pytest.raises(StopIteration):
97 | next(app.screen.current_timeline)
98 |
99 | response_mock.json.return_value = expected_thread.old.json
100 | await pilot.press(OPEN_THREAD_KEY)
101 | assert len(app.screen_stack) == 3
102 |
103 | await pilot.press(BACK_OR_EXIT_KEY)
104 | assert len(app.screen_stack) == 2
105 |
--------------------------------------------------------------------------------