Compare commits

..

39 Commits

Author SHA1 Message Date
Lionel Dricot 3155585c9e introducing openk 2023-08-04 19:09:48 +02:00
Lionel Dricot 2e02d06b0e we got rid of GeminiItem 2023-08-03 23:17:12 +02:00
Lionel Dricot ed019fa04e nearly got rid of geminiitem 2023-08-03 16:54:29 +02:00
Lionel Dricot 91e8b7aa16 geminiitem got rid of get_body 2023-07-31 19:01:57 +02:00
Lionel Dricot b3051efe72 working on get_body 2023-07-31 18:53:26 +02:00
Lionel Dricot 9609a8d91f moving out the self.url thing 2023-07-31 18:37:30 +02:00
Lionel Dricot 2034821325 debug XDG folders 2023-07-31 17:56:08 +02:00
Lionel Dricot a6fee03d2b next work : reimplementing list and local files 2023-07-31 13:19:28 +02:00
Lionel Dricot 7ba6bac5a4 works at Volvo 2023-07-31 09:34:12 +02:00
Lionel Dricot 26ed1769de get_link now in ansirenderer 2023-07-30 23:35:34 +02:00
Lionel Dricot 9ee95e7a1b pictures are working 2023-07-30 23:12:01 +02:00
Lionel Dricot 7786b91993 continuing work to remove GeminiItem 2023-07-30 16:59:32 +02:00
Lionel Dricot 3051f60253 more certificate management in netcache 2023-07-28 18:31:04 +02:00
Lionel Dricot dade6a3bda migrating certificate management to netcache 2023-07-28 18:08:45 +02:00
Lionel Dricot eed83a7a95 Cleaning up GeminiItem
Work has started to remove GeminiItem completely and switch to an
{url:renderer} dictionnary. Maybe also add a tmpfile.
2023-07-22 23:32:10 +02:00
Lionel Dricot 767ab82f29 Ok, it starts to work.
Offpunk is now able to display pages, pictures and follow links. A lot
of TODO have been clearly identified. I think that the whole
GeminiItem() object will be removed and URL will be accessed directly
with a dict{url, renderer} to avoid redrawing all the time.

Next challenge: remove GeminiItems!
2023-07-22 00:27:43 +02:00
Lionel Dricot 72ea43a59c debugging offpunk 2023-07-21 18:02:05 +02:00
Lionel Dricot d95d4dc5af offpunk starts to work 2023-07-21 17:33:55 +02:00
Lionel Dricot 1a3d839ab3 renderer in ansirenderer 2023-07-21 14:22:09 +02:00
Lionel Dricot 268e50a781 ansirenderer now working both directly or from stdin 2023-07-21 11:52:39 +02:00
Lionel Dricot cd3177ac87 pour le moment incapable de décider si ansirenderer doit prendre le path du fichier ou directement le texte en input 2023-07-21 01:03:40 +02:00
Lionel Dricot ce65850987 starting to adapt offpunk 2023-07-20 01:17:34 +02:00
Lionel Dricot c7734e3a92 default to stdin 2023-07-18 23:43:45 +02:00
Lionel Dricot 0b0fcc3e42 first working pipe between netcache and ansirenderer 2023-07-18 17:40:36 +02:00
Lionel Dricot 0cd988b055 ansirenderer cli 2023-07-18 12:33:30 +02:00
Lionel Dricot 965f8916c2 --offline and --path arguments 2023-07-18 12:16:08 +02:00
Lionel Dricot 4fd8b89f49 monkey patching 2023-07-18 00:45:14 +02:00
Lionel Dricot b745b04f7a netcache now works for gemini 2023-07-18 00:39:06 +02:00
Lionel Dricot a7c8ed33d5 work in progress 2023-07-09 11:35:58 +02:00
Lionel Dricot 6d43b13520 real work has started with porting Gemini code 2023-07-09 11:16:19 +02:00
Lionel Dricot 0a385d5334 gopher,finger and spartan in netcache 2023-07-09 10:56:40 +02:00
Lionel Dricot ef808afe1d netcache now downloads http 2023-07-08 00:43:56 +02:00
Lionel Dricot 3c760c914a netcache CLI 2023-07-07 23:45:52 +02:00
Lionel Dricot 76b00b8c04 working on netcache 2023-07-04 23:20:39 +02:00
Lionel Dricot a6974bb404 first netcache 2023-07-04 16:10:20 +02:00
Lionel Dricot 644e8ba08e to the point where netcache become an evidence 2023-07-04 13:59:16 +02:00
Lionel Dricot 927017d143 introducing offutils.py 2023-07-04 13:55:01 +02:00
Lionel Dricot ea36f45d94 progress toward independance 2023-07-03 23:48:55 +02:00
Lionel Dricot 86a67d47fa experiment 2023-07-03 11:43:06 +02:00
20 changed files with 1284 additions and 2663 deletions

129
CHANGELOG
View File

@ -1,131 +1,12 @@
# Offpunk History
## 2.3 - Unreleased
- offpunk/netcache: fix IPv6 as an URL (bug #40)
- ansicat: display empty files (instead of opening them with xdg-open)
- fix escape sequence warning in python 3.12 (by Étienne Mollier) (Debian #1064209)
- ansicat : fix crash when feedparser is crashing on bad RSS
- netcache: fix spartan protocol error
- opnk: fix a crash when caching returns None
## 2.2 - February 13th 2023
- cache folder is now configurable through $OFFPUNK_CACHE_PATH environment variable (by prx)
- offpunk: adding an URL to a list now update the view mode if url already present
- netcache: solve an infinite gemini loop with code 6X (see also bug #31)
- ansicat: added support for <video> HTML-element
- ansicat: if chafa fails to load an image, fallback to timg if available
- offpunk: add list autocompletion to "tour"
- offpunk: removed "blackbox", which has not been used nor maintained
- offpunk: "gus" was broken, it is functionnal again
- opnk/offpunk: more informative prompt in less
- ansicat: added support for HTML description elements <dt> and <dd> (by Bert Livens)
- opnk: added "--mode" command-line argument (bug #39)
- offpunk: support for "preformatted" theming (bug #38)
- opnk/netcache: added "--cache-validity" command-line argument (bug #37)
- ansicat: consider files as XML, not SVG, if they dont have .svg extension
- offpunk: fix "view link" crashing with link to empty files
## 2.1 - December 15th 2023
- freshly updated gemtext/rss links are highlighted ("new_link" theme option)
- offpunk : new "copy title" and "copy link" function
- offpunk : new "view XX" feature where XX is a number to view information about a link
- ansicat: added "--mode" option
- redirections are now reflected in links and the cache (bug #28)
- ansicat: avoid a crash when urllib.parse.urljoin fails
- offpunk: Fix a crash when gus is called without parameters (Von Hohenheiden)
- ansicat: fixed a crash when parsing wrong hidden_url in gemini (bug #32)
- offpunk: offpunk --version doesnt create the cache anymore (bug #27)
- ansicat: fix a crash with HTML without title (bug #33)
- netcache: gemini socket code can crash when IPv6 is disabled (mailing-list)
## 2.0 - November 16th 2023
Changes since 1.10
- IMPORTANT: Licence has been changed to AGPL for ideological reasons
- IMPORTANT: Contact adress has been changed to offpunk2 on the same domain (because of spam)
- IMPORTANT: code has been splitted into several differents files.
- IMPORTANT: migrating from flit to hatchling (patch by Jean Abou Samra)
Major features:
- New command-line tool: "netcache"
- New command-line tool: "ansicat"
- New command-line tool: "opnk"
- "theme" command allows customization of the colours
- "--config-file" allows to start offpunk with custom config (#16)
- "view source" to view the source code of a page
- introduced the "default_protocol" options (default to gemini)
Improvments:
- Reading position is saved in less for the whole session
- Rendering is cached for the session, allowing faster browsing of a page already visited
- "redirect" supports domains starting with "*" to also block all subdomins
- "--images-mode" allow to choose at startup which images should be dowloaded (none,readable,full)
- Support for embedded multi-format rendering (such as RSS feeds with html elements)
- The cache is now automatically upgraded if needed (see .version in your cache)
- Images of html files are now downloaded with the html (slower sync but better reading experience)
- "--sync" can optionnaly take some lists as arguments, in order to make for specific sync
- initial tentative to support podcasts in RSS/Atom feeds
Other notable changes from 1.X:
- "accept_bad_ssl_certificates" now more agressive for http and really accepts them all
- Gopher-only: we dont support naming a page after the name of the incoming link
- Gemini-only: support for client generated certificates has been removed
- "file" is now marked as a dependency (thank Guillaume Loret)
## 2.0 (beta3 - final 2.0) - Released as 2.0
Changes since beta2:
- bug #25 : makes python-requests optional again
- --disable-http had no effect: reimplemented
- introduced the "default_protocol" options (default to gemini) to enter URLs without the :// part (fixes bug #21)
## 2.0-beta2 - November 8th 2023
Changes since beta1
- IMPORTANT: migrating from flit to hatchling (patch by Jean Abou Samra)
- "--sync" can optionnaly take some lists as arguments, in order to make for specific sync
- "view source" to view the source code of a page
- initial tentative to support podcasts in RSS/Atom feeds
- new PlaintextRenderer which display .txt files without any margin/color/linebreaks
- default URL blocked list is now its own file to make contributions easier
- prompt color is now part of the theme
- improves handling of base64 images
- fixes gophermap being considered as gemtext files
- fixes opening mailto links
- fixes existing non-html ressources marked a to_fetch even when not needed (simple and/or confusion)
- fixes a crash with RSSfeeds without <link> element
- fixes a crash with data:image/svg+xml links
- fixes a bug in HTML renderer where some hX element were not closed properly
- fixes input in Gemini while online
- fixes a crash with invalid URL
- fixes a crash while parsing invalid dates in RSS
- fixes hang/crash when meeting the ";" itemtype in gopher
- attempt at hiding XMLparsedAsHTMLWarning from BS4 library
- chafa now used by default everywhere if version > 1.10
- ignoring encoding error in ansicat
## 2.0-beta1 - September 05th 2023
This is an an experimental release. Bug reports and feedbacks are welcome on the offpunk-devel list.
- WARNING: pyproject.toml has not been updated and is currently non-functional. Help needed!
- IMPORTANT: Licence has been changed to AGPL for ideological reasons
- IMPORTANT: Contact adress has been changed to offpunk2 on the same domain (because of spam)
- IMPORTANT: code has been splitted into 7 differents files. Installation/packaging should be adapted.
Major features:
## 2.0 - unreleased
This is an an experimental and unstable release. Lot of breakages are expected.
Wait for 2.1 if you are not willing to do testing/bug reporting.
- New command-line tool: "netcache"
- New command-line tool: "ansicat"
- New command-line tool: "opnk"
- "theme" command allows customization of the colours
- "--config-file" allows to start offpunk with custom config (#16)
Improvments:
- Reading position is saved for the whole session
- Rendering is cached for the session, allowing faster browsing of a page already visited
- "redirect" supports domains starting with "*" to also block all subdomins
- "--images-mode" allow to choose at startup which images should be dowloaded (none,readable,full)
- Support for multi-format rendering (such as RSS feeds with html elements)
- The cache is now automatically upgraded if needed (see .version in your cache)
Other changes from 1.X:
- Images of html files are now downloaded with the html (slower sync but better reading experience)
- URL do not default anymore to "gemini://" if not protocol are indicated. (ongoing discussion in #21)
- "accept_bad_ssl_certificates" now more agressive for http and really accepts them all
- Gopher-only: we dont support naming a page after the name of the incoming link
- Gemini-only: support for client generated certificates has been removed
- "file" is now marked as a dependency (thank Guillaume Loret)
- New command-line tool: "ansirenderer"
## 1.10 - July 31st 2023
## 1.10 - unreleased
- IMPORTANT : new optional dependency : python-chardet
- IMPORTANT : Gopher directory index filename changed from "index.txt" to "gophermap". To update the cache to the new format run the `migrate-offpunk-cache` script (Sotiris Papatheodorou)
- "set accept_bad_ssl_certificates True" now also used for Gemini expired certificates

View File

@ -1,19 +0,0 @@
Offpunk Offline Gemini client
And the Offpunk tools suite: netcache, ansicat, opnk.
(C) From 2021: Ploum <offpunk2@ploum.eu>
Derived from AV-98 and Agena by Solderpunk,
(C) 2019, 2020: Solderpunk <solderpunk@sdf.org>
AV-98 received contributions from:
- danceka <hannu.hartikainen@gmail.com>
- <jprjr@tilde.club>
- <vee@vnsf.xyz>
- Klaus Alexander Seistrup <klaus@seistrup.dk>
- govynnus <govynnus@sdf.org>
- Björn Wärmedal <bjorn.warmedal@gmail.com>
- <jake@rmgr.dev>
Offpunk received contributions from:
- Maeve Sproule <code@sprock.dev>

683
LICENSE
View File

@ -1,664 +1,25 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
BSD 2-Clause License
Copyright (c) 2022, Ploum <offpunk2 at ploum.eu> and contributors.
Copyright (c) 2022, Ploum <offpunk@ploum.eu> and contributors.
All rights reserved.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -13,13 +13,13 @@ Offpunk is a fork of the original [AV-98](https://tildegit.org/solderpunk/AV-98)
## How to use
Offpunk is a set of python files. Installation is optional, you can simply git clone the project and run "./offpunk.py" or "python3 offpunk.py" in a terminal.
Offpunk is a single python file. Installation is optional, you can simply download and run "./offpunk.py" or "python3 offpunk.py" in a terminal.
You use the `go` command to visit a URL, e.g. `go gemini.circumlunar.space`. (gemini:// is assumed if no protocol is specified. Supported protocols are gemini, gopher, finger, http, https, mailto, spartan and file. Default protocol is configurable).
You use the `go` command to visit a URL, e.g. `go gemini.circumlunar.space`. (gemini:// is assumed if no protocol is specified. Supported protocols are gemini, gopher, finger, http, https, mailto, spartan and file).
Links in pages are assigned numerical indices. Just type an index to follow that link. If page is too long to fit on your screen, the content is displayed in the less pager. Type `q` to quit and go back to Offpunk prompt. Type `view` or `v` to display it again. (`view full` or `v full` allows to see the full html page instead of the article view. `v feed` try to display the linked RSS feed and `v feeds` displays a list of available feeds. This only applies to html pages. `v source` allows you to see the source code of a page and `v normal` to go back to normal view)
Links in pages are assigned numerical indices. Just type an index to follow that link. If page is too long to fit on your screen, the content is displayed in the less pager (by default). Type `q` to quit and go back to Offpunk prompt. Type `view` or `v` to display it again. (`view full` or `v full` allows to see the full html page instead of the article view. `v feed` try to display the linked RSS feed and `v feeds` displays a list of available feeds. This only applies to html pages)
Use `add` to add a page to your bookmarks and `bookmarks` or `bm` to show your bookmarks (you can create multiple bookmarks lists, edit and remove them. See the `list` manual with `help list`).
Use `add` to add a capsule to your bookmarks and `bookmarks` or `bm` to show your bookmarks (you can create multiple bookmarks lists, edit and remove them. See the `list` manual with `help list`).
Use `offline` to only browse cached content and `online` to go back online. While offline, the `reload` command will force a re-fetch during the next synchronisation.
@ -35,10 +35,6 @@ For example, running
will refresh your bookmarks if those are at least 12h old. If cache-validity is not set or set to 0, any cache is considered good and only content never cached before will be fetched. `--assume-yes` will automatically accept SSL certificates with errors instead of refusing them.
Sync can be applied to only a subset of list.
`offpunk --sync bookmarks tour to_fetch --cache-validity 3600`
Offpunk can also be configured as a browser by other tool. If you want to use offpunk directly with a given URL, simply type:
`offpunk URL`
@ -57,16 +53,19 @@ Questions can be asked on the users mailing list:
## Dependencies
Offpunk has few "strict dependencies", i.e. it should run and work without anything
Offpunk has no "strict dependencies", i.e. it should run and work without anything
else beyond the Python standard library and the "less" pager. However, it will "opportunistically
import" a few other libraries if they are available to offer an improved
experience or some other features such as HTTP/HTML or image support.
experience or some other features. Python libraries requests, bs4 and readability are required for http/html support. Images are displayed if chafa or timg are presents (python-pil is needed for chafa version before 1.10). When displaying only a picture (not inline), rendering will be pixel perfect in compatible terminals (such as Kitty) if chafa is at least version 1.8 or if timg is used.
To avoid using unstable or too recent libraries, the rule of thumb is that a library should be packaged in Debian/Ubuntu. Keep in mind that Offpunk is mainly tested will all libraries installed. If you encounter a crash without one optional dependencies, please report it. Patches and contributions to remove dependencies or support alternatives are highly appreciated.
* [List of existing Offpunk packages (Repology)](https://repology.org/project/offpunk/versions)
* PIP: [requirements file to install dependencies with pip](requirements.txt)
* Debian Unstable: [Official Package by Étienne Mollier](https://packages.debian.org/sid/offpunk)
* Ubuntu/Debian: [command to install dependencies on Ubuntu/Debian without pip](ubuntu_dependencies.txt)
* Arch: [AUR package for Arch Linux, maintained by kseistrup](https://aur.archlinux.org/packages/offpunk-git)
* [Nix](https://nixos.org/): [package](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/browsers/offpunk/default.nix), maintained by [DamienCassou](https://github.com/DamienCassou)
* Alpine Linux: [package maintained by mio](https://pkgs.alpinelinux.org/packages?name=offpunk)
* Please contribute packages for other systems, theres a [mailing-list dedicated to packaging](https://lists.sr.ht/~lioploum/offpunk-packagers).
Run command `version` in offpunk to see if you are missing some dependencies.
@ -82,22 +81,17 @@ Dependencies to enable web browsing (packagers may put those in an offpunk-web m
* [BeautifulSoup4](https://www.crummy.com/software/BeautifulSoup) and [Readability](https://github.com/buriy/python-readability) are both needed to render HTML. Without them, HTML will not be rendered or be sent to an external parser like Lynx. (apt-get install python3-bs4 python3-readability or pip3 install readability-lxml)
* [Python-feedparser](https://github.com/kurtmckee/feedparser) will allow parsing of RSS/Atom feeds and thus subscriptions to them. (apt-get install python3-feedparser)
* [Chafa](https://hpjansson.org/chafa/) allows to display pictures in your console. Install it and browse to an HTML page with picture to see the magic.
Gopher dependencies:
* [Python-chardet](https://github.com/chardet/chardet) is used to detect the character encoding on Gopher (and may be used more in the future)
Older dependencies which are only needed on older systems (where chafa < 1.10)
* [Timg](https://github.com/hzeller/timg) is a slower alternative to chafa for inline images. Might be deprecated in the future.
* [Python-pil](http://python-pillow.github.io/) is required to only display the first frame of animated gif with chafa if chafa version is lower than 1.10. Might be deprecated in the future.
* [Timg](https://github.com/hzeller/timg) is a slower alternative to chafa for inline images. But it has better rendering when displaying only the image. Install both to get the best of both world but if you need to choose one, choose Chafa.
* [Python-pil](http://python-pillow.github.io/) is required to only display the first frame of animated gif with chafa if chafa version is lower than 1.10.
Nice to have (packagers should may make those optional):
* [Xsel](http://www.vergenet.net/~conrad/software/xsel/) allows to `go` to the URL copied in the clipboard without having to paste it (both X and traditional clipboards are supported). Also needed to use the `copy` command. (apt-get install xsel)
* [Python-setproctitle](https://github.com/dvarrazzo/py-setproctitle) will change the process name from "python" to "offpunk". Useful to kill it without killing every python service.
* [Python-chardet](https://github.com/chardet/chardet) is used to detect the character encoding on Gopher (and may be used more in the future)
## Features
* Browse https/gemini/gopher without leaving your keyboard and without distractions
* Customize your experience with the `theme` command.
* Browse https/gemini/gopher/spartan without leaving your keyboard and without distractions
* Built-in documentation: type `help` to get the list of command or a specific help about a command.
* Offline mode to browse cached content without a connection. Requested elements are automatically fetched during the next synchronization and are added to your tour.
* HTML pages are prettified to focus on content. Read without being disturbed or see the full page with `view full`.
@ -108,15 +102,16 @@ Nice to have (packagers should may make those optional):
* Ability to specify external handler programs for different MIME types (use `handler`)
* Enhanced privacy with `redirect` which allows to block a http domain or to redirect all request to a privacy friendly frontent (such as nitter for twitter).
* Non-interactive cache-building with configurable depth through the --sync command. The cache can easily be used by other software.
* `netcache`, a standalone CLI tool to retrieve the cached version of a network ressource.
* `ansicat`, a standalone CLI tool to render HTML/Gemtext/image in a terminal.
* `opnk`, a standalone CLI tool to open any kind of ressources (local or network) and display it in your terminal or, if not possible, fallback to `xdg-open`.
* IPv6 support
* Supports any character encoding recognised by Python
* Cryptography : TOFU or CA server certificate validation
* Cryptography : Extensive client certificate support if an `openssl` binary is available
## RC files
You can use an RC file to automatically run any sequence of valid Offpunk
commands upon start up. This can be used to make settings controlled with the
`set`, `handler` or `themes` commands persistent. You can also put a `go` command in
`set` or `handler` commanders persistent. You can also put a `go` command in
your RC file to visit a "homepage" automatically on startup, or to pre-prepare
a `tour` of your favourite Gemini sites or `offline` to go offline by default.
@ -126,7 +121,5 @@ The RC file should be called `offpunkrc` and goes in $XDG_CONFIG_DIR/offpunk (or
The offline content is stored in ~/.cache/offpunk/ as plain .gmi/.html files. The structure of the Gemini-space is tentatively recreated. One key element of the design is to avoid any database. The cache can thus be modified by hand, content can be removed, used or added by software other than offpunk.
The cache can be accessed/built with the `netcache` tool. See `netcache -h` for more informations.
Theres no feature to automatically trim the cache. But any part of the cache can safely be removed manually as there are no databases or complex synchronisation.
Theres no feature to automatically trim the cache. But part of the cache can safely be removed manually.

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/bin/bash
XDG_DATA_HOME="~/debug/data" XDG_CONFIG_HOME="~/debug/config" XDG_CACHE_HOME="~/debug/cache" python offpunk.py

View File

@ -1,74 +0,0 @@
.Dd August 27, 2023
.Dt ANSICAT 1
.Os
.
.Sh NAME
.Nm ansicat
.Nd terminal gemini gemtext renderer for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Fl \-format Ar RENDERER
.Op Fl \-mime Ar MIME
.Op Fl \-url Ar URL ...
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Ansicat is the rendering engine of the browser
.Xr offpunk 1 .
It will render nicely on the terminal any gemtext,
html,
gopher,
and a few other formats.
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar INPUT
path to the text to render.
It defaults to the standard input.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
show a help message and exit.
.It Fl \-format Ar RENDERER
renderer to use.
Available renderers are
.Ic auto ,
.Ic gemtext ,
.Ic html ,
.Ic feed ,
.Ic gopher ,
.Ic image ,
and
.Ic folder .
The
.Ic auto
renderer will heuristically guess the format,
either thanks to the MIME type,
or from the file being rendered itself.
.It Fl \-mime Ar MIME
MIME type of the content to parse.
.It Fl \-mode Ar MODE
MODE to use to render to choose between normal (default), full or source
.It Fl \-url Ar URL ...
original URL of the content.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr offpunk 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -1,74 +0,0 @@
.Dd August 27, 2023
.Dt NETCACHE 1
.Os
.
.Sh NAME
.Nm netcache
.Nd local Internet cache handler for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Fl \-path
.Op Fl \-offline
.Op Fl \-max\-size Ar MAX_SIZE
.Op Fl \-timeout Ar TIMEOUT
.Op Ar URL ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Netcache is the download and cache management engine of the browser
.Xr offpunk 1 .
It allows one to fetch a link and get its content,
writing the content through the local cache for ulterior reference.
Netcache can be forced into offline mode,
in order to only fetch resources from the local cache,
otherwise it would always refresh it from the version available online.
It is also useful for mapping a given URL to its location in the cache,
independently of whether it has been downloaded first.
.Pp
Default cache path is
.Pa ~/.cache/offpunk .
Set
.Ev OFFPUNK_CACHE_PATH
environment variable to use another location.
.Bd -literal
OFFPUNK_CACHE_PATH=/home/ploum/custom-cache netcache.py gemini://some.url
.Ed
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar URL
download the URL and output the content.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
show a help message and exit.
.It Fl \-path
output the path to the cache instead of the content of the URL.
.It Fl \-max-size Ar MAX_SIZE
cancel download of items above that size.
The value is expressed in megabytes.
.It Fl \-timeout Ar TIMEOUT
time to wait before cancelling connection.
The value is expressed in seconds.
.It Fl \-cache-validity CACHE_VALIDITY
Maximum age (in second) of the cached version before redownloading a new version.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr offpunk 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

View File

@ -77,10 +77,6 @@ display available features and dependancies then quit
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr opnk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh HISTORY
@ -90,4 +86,4 @@ is a fork of the original AV-98 by
and was originally called AV-98-offline as an experimental branch.
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu
.An Lionel Dricot (Ploum) Aq Mt offpunk@ploum.eu

View File

@ -1,57 +0,0 @@
.Dd August 27, 2023
.Dt OPNK 1
.Os
.
.Sh NAME
.Nm opnk
.Nd universal open (like a punk) for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
Opnk is the "universal open (like a punk)".
Opnk is a tool that will try to render any file or URL in the terminal,
using
.Xr netcache 1
and
.Xr ansicat 1 ,
and put them in
.Xr less 1 .
If that doesnt work,
it will fallback to
.Xr xdg-open 1 .
.Pp
.Xr Offpunk 1
is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It Ar INPUT
path to the file or URL to open.
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
Show a help message and exit
.It Fl \-mode Ar MODE
MODE to use to render to choose between normal (default), full or source
.It Fl \-cache-validity CACHE_VALIDITY
Maximum age (in second) of the cached version before redownloading a new version.
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr offpunk 1 ,
.Lk https://sr.ht/~lioploum/offpunk/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu

20
netcache_migration.py → migrate-offpunk-cache Normal file → Executable file
View File

@ -18,14 +18,30 @@ import os
import os.path
def upgrade_to_1(cache_dir: str) -> None:
def v1_10_0(cache_dir: str) -> None:
"""
Rename index.txt to gophermap in the Gopher protocol cache.
"""
print("Upgrading cache to version 1: migrating index.txt to gophermap")
for root, _, files in os.walk(os.path.join(cache_dir, 'gopher')):
for f in files:
if f == 'index.txt':
src = os.path.join(root, f)
dst = os.path.join(root, 'gophermap')
os.rename(src, dst)
if __name__ == '__main__':
# Compute the default offpunk cache directory.
xdg_cache_home = os.environ.get('XDG_CACHE_HOME')
if xdg_cache_home:
default_cache_dir = os.path.join(xdg_cache_home, 'offpunk')
else:
default_cache_dir = os.path.join(os.path.expanduser('~'), '.cache/offpunk')
# Parse command line arguments.
parser = argparse.ArgumentParser(
description='Migrate the offpunk cache to a newer version.')
parser.add_argument('cache_dir', metavar='CACHE_DIR', nargs='?',
default=default_cache_dir, help='the path to the cache')
args = parser.parse_args()
# Run the cache migration functions from the oldest to the newest version.
v1_10_0(args.cache_dir)

View File

@ -1,8 +1,9 @@
#!/usr/bin/env python3
#!/bin/python
import os
import sys
import urllib.parse
import argparse
import requests
import codecs
import getpass
import socket
@ -12,10 +13,6 @@ import datetime
import hashlib
import sqlite3
from ssl import CertificateError
import ansicat
import offutils
from offutils import xdg
import time
try:
import chardet
_HAS_CHARDET = True
@ -27,13 +24,20 @@ try:
from cryptography.hazmat.backends import default_backend
_HAS_CRYPTOGRAPHY = True
_BACKEND = default_backend()
except(ModuleNotFoundError,ImportError):
except ModuleNotFoundError:
_HAS_CRYPTOGRAPHY = False
try:
import requests
_DO_HTTP = True
except (ModuleNotFoundError,ImportError):
_DO_HTTP = False
_home = os.path.expanduser('~')
cache_home = os.environ.get('XDG_CACHE_HOME') or\
os.path.join(_home,'.cache')
#_CACHE_PATH = os.path.join(cache_home,"offpunk/")
#Debug (TODO: get path from offpunk):
_CACHE_PATH = "/home/ploum/dev/netcache/"
_DATA_DIR = "/home/ploum/dev/netcache/"
_CONFIG_DIR = "/home/ploum/dev/netcache/"
if not os.path.exists(_CACHE_PATH):
print("Creating cache directory {}".format(_CACHE_PATH))
os.makedirs(_CACHE_PATH)
# This list is also used as a list of supported protocols
standard_ports = {
@ -84,12 +88,13 @@ def normalize_url(url):
def cache_last_modified(url):
if not url:
return None
path = get_cache_path(url)
if path and os.path.isfile(path):
if path:
return os.path.getmtime(path)
elif self.local:
return 0
else:
print("ERROR :NOCACHE in cache_last_modified")
return None
def is_cache_valid(url,validity=0):
@ -97,9 +102,10 @@ def is_cache_valid(url,validity=0):
# a cache to be valid (in seconds)
# If 0, then any cache is considered as valid
# (use validity = 1 if you want to refresh everything)
if offutils.is_local(url):
return True
cache = get_cache_path(url)
# TODO FIXME : detect if we are local
#if self.local:
# return os.path.exists(cache)
if cache :
# If path is too long, we always return True to avoid
# fetching it.
@ -121,15 +127,12 @@ def is_cache_valid(url,validity=0):
#Theres not even a cache!
return False
def get_cache_path(url,add_index=True):
def get_cache_path(url):
# Sometimes, cache_path became a folder! (which happens for index.html/index.gmi)
# In that case, we need to reconstruct it
# if add_index=False, we dont add that "index.gmi" at the ends of the cache_path
#First, we parse the URL
if not url:
return None
parsed = urllib.parse.urlparse(url)
if url[0] == "/" or url.startswith("./") or os.path.exists(url):
if url[0] == "/" or url.startswith("./"):
scheme = "file"
elif parsed.scheme:
scheme = parsed.scheme
@ -141,11 +144,11 @@ def get_cache_path(url,add_index=True):
port = None
# file:// is 7 char
if url.startswith("file://"):
path = url[7:]
path = self.url[7:]
elif scheme == "mailto":
path = parsed.path
elif url.startswith("list://"):
listdir = os.path.join(xdg("data"),"lists")
listdir = os.path.join(_DATA_DIR,"lists")
listname = url[7:].lstrip("/")
if listname in [""]:
name = "My Lists"
@ -174,7 +177,7 @@ def get_cache_path(url,add_index=True):
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9","g","I","s",";"):
elif itemtype in ("9","g","I","s"):
mime = "binary"
else:
mime = "text/gopher"
@ -190,12 +193,12 @@ def get_cache_path(url,add_index=True):
# Now, we have a partial path. Lets make it full path.
if local:
cache_path = path
elif scheme and host:
cache_path = os.path.expanduser(xdg("cache") + scheme + "/" + host + path)
else:
cache_path = os.path.expanduser(_CACHE_PATH + scheme + "/" + host + path)
#Theres an OSlimitation of 260 characters per path.
#We will thus cut the path enough to add the index afterward
cache_path = cache_path[:249]
# this is a gross hack to give a name to
# FIXME : this is a gross hack to give a name to
# index files. This will break if the index is not
# index.gmi. I dont know how to know the real name
# of the file. But first, we need to ensure that the domain name
@ -213,17 +216,13 @@ def get_cache_path(url,add_index=True):
cache_path += "/"
if not url.endswith("/"):
url += "/"
if add_index and cache_path.endswith("/"):
if cache_path.endswith("/"):
cache_path += index
#sometimes, the index itself is a dir
#like when folder/index.gmi?param has been created
#and we try to access folder
if add_index and os.path.isdir(cache_path):
if os.path.isdir(cache_path):
cache_path += "/" + index
else:
#URL is missing either a supported scheme or a valid host
#print("Error: %s is not a supported url"%url)
return None
if len(cache_path) > 259:
print("Path is too long. This is an OS limitation.\n\n")
print(url)
@ -268,7 +267,7 @@ def set_error(url,err):
cache = get_cache_path(url)
if is_cache_valid(url):
os.utime(cache)
elif cache:
else:
cache_dir = os.path.dirname(cache)
root_dir = cache_dir
while not os.path.exists(root_dir):
@ -277,35 +276,44 @@ def set_error(url,err):
os.remove(root_dir)
os.makedirs(cache_dir,exist_ok=True)
if os.path.isdir(cache_dir):
with open(cache, "w") as c:
c.write(str(datetime.datetime.now())+"\n")
c.write("ERROR while caching %s\n\n" %url)
c.write("*****\n\n")
c.write(str(type(err)) + " = " + str(err))
with open(cache, "w") as cache:
cache.write(str(datetime.datetime.now())+"\n")
cache.write("ERROR while caching %s\n\n" %url)
cache.write("*****\n\n")
cache.write(str(type(err)) + " = " + str(err))
#cache.write("\n" + str(err.with_traceback(None)))
c.write("\n*****\n\n")
c.write("If you believe this error was temporary, type ""reload"".\n")
c.write("The ressource will be tentatively fetched during next sync.\n")
c.close()
cache.write("\n*****\n\n")
cache.write("If you believe this error was temporary, type ""reload"".\n")
cache.write("The ressource will be tentatively fetched during next sync.\n")
cache.close()
return cache
def _fetch_http(url,max_size=None,timeout=DEFAULT_TIMEOUT,accept_bad_ssl_certificates=False,**kwargs):
if not _DO_HTTP: return None
def _fetch_http(url,max_size=None,timeout=DEFAULT_TIMEOUT,**kwargs):
def too_large_error(url,length,max_size):
err = "Size of %s is %s Mo\n"%(url,length)
err += "Offpunk only download automatically content under %s Mo\n" %(max_size/1000000)
err += "To retrieve this content anyway, type 'reload'."
return set_error(url,err)
if accept_bad_ssl_certificates:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'
requests.packages.urllib3.disable_warnings()
verify=False
else:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=2'
verify=True
header = {}
header["User-Agent"] = "Netcache"
with requests.get(url,verify=verify,headers=header, stream=True,timeout=DEFAULT_TIMEOUT) as response:
parsed = urllib.parse.urlparse(url)
# Code to translate URLs to better frontends (think twitter.com -> nitter)
#if options["redirects"]:
# netloc = parsed.netloc
# if netloc.startswith("www."):
# netloc = netloc[4:]
# if netloc in self.redirects:
# if self.redirects[netloc] == "blocked":
# text = "This website has been blocked.\n"
# text += "Use the redirect command to unblock it."
# gi.write_body(text,"text/gemini")
# return gi
# else:
# parsed = parsed._replace(netloc = self.redirects[netloc])
url = urllib.parse.urlunparse(parsed)
with requests.get(url,headers=header, stream=True,timeout=DEFAULT_TIMEOUT) as response:
#print("This is header for %s"%gi.url)
#print(response.headers)
if "content-type" in response.headers:
mime = response.headers['content-type']
else:
@ -356,6 +364,7 @@ def _fetch_gopher(url,timeout=DEFAULT_TIMEOUT,**kwargs):
addresses = socket.getaddrinfo(host, port, family=0,type=socket.SOCK_STREAM)
s = socket.create_connection((host,port))
for address in addresses:
self._debug("Connecting to: " + str(address[4]))
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
try:
@ -369,11 +378,10 @@ def _fetch_gopher(url,timeout=DEFAULT_TIMEOUT,**kwargs):
request = selector
request += "\r\n"
s.sendall(request.encode("UTF-8"))
response1 = s.makefile("rb")
response = response1.read()
response = s.makefile("rb").read()
# Transcode response into UTF-8
#if itemtype in ("0","1","h"):
if not itemtype in ("9","g","I","s",";"):
if not itemtype in ("9","g","I","s"):
# Try most common encodings
for encoding in ("UTF-8", "ISO-8859-1"):
try:
@ -394,7 +402,7 @@ def _fetch_gopher(url,timeout=DEFAULT_TIMEOUT,**kwargs):
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9","g","I","s",";"):
elif itemtype in ("9","g","I","s"):
mime = None
else:
# by default, we should consider Gopher
@ -449,6 +457,151 @@ def _fetch_spartan(url,**kwargs):
cache = _fetch_spartan(redirect_url)
return cache
def _activate_client_cert(certfile, keyfile):
#TODO
#self.client_certs["active"] = (certfile, keyfile)
#self.active_cert_domains = []
#self.prompt = self.cert_prompt + "+" + os.path.basename(certfile).replace('.crt','') + "> " + "\001\x1b[0m\002"
pass
def _deactivate_client_cert():
#TODO
# if self.active_is_transient:
# for filename in self.client_certs["active"]:
# os.remove(filename)
# for domain in self.active_cert_domains:
# self.client_certs.pop(domain)
# self.client_certs["active"] = None
# self.active_cert_domains = []
# self.prompt = self.no_cert_prompt
# self.active_is_transient = False
pass
def _choose_client_cert():
"""
Interactively select a previously generated client certificate and
activate it.
"""
certdir = os.path.join(_CONFIG_DIR, "client_certs")
certs = glob.glob(os.path.join(certdir, "*.crt"))
if len(certs) == 0:
print("There are no previously generated certificates.")
return
certdir = {}
for n, cert in enumerate(certs):
certdir[str(n+1)] = (cert, os.path.splitext(cert)[0] + ".key")
print("{}. {}".format(n+1, os.path.splitext(os.path.basename(cert))[0]))
choice = input("> ").strip()
if choice in certdir:
certfile, keyfile = certdir[choice]
_activate_client_cert(certfile, keyfile)
else:
print("What?")
def _load_client_cert(self):
"""
Interactively load a TLS client certificate from the filesystem in PEM
format.
"""
print("Loading client certificate file, in PEM format (blank line to cancel)")
certfile = input("Certfile path: ").strip()
if not certfile:
print("Aborting.")
return
certfile = os.path.expanduser(certfile)
if not os.path.isfile(certfile):
print("Certificate file {} does not exist.".format(certfile))
return
print("Loading private key file, in PEM format (blank line to cancel)")
keyfile = input("Keyfile path: ").strip()
if not keyfile:
print("Aborting.")
return
keyfile = os.path.expanduser(keyfile)
if not os.path.isfile(keyfile):
print("Private key file {} does not exist.".format(keyfile))
return
_activate_client_cert(certfile, keyfile)
def _generate_client_cert(certdir, basename, transient=False):
"""
Use `openssl` binary to generate a client certificate (which may be
transient or persistent) and save the certificate and private key to the
specified directory with the specified basename.
"""
if not os.path.exists(certdir):
os.makedirs(certdir)
certfile = os.path.join(certdir, basename+".crt")
keyfile = os.path.join(certdir, basename+".key")
cmd = "openssl req -x509 -newkey rsa:2048 -days {} -nodes -keyout {} -out {}".format(1 if transient else 365, keyfile, certfile)
if transient:
cmd += " -subj '/CN={}'".format(basename)
os.system(cmd)
_activate_client_cert(certfile, keyfile)
def _generate_transient_cert_cert():
"""
Use `openssl` command to generate a new transient client certificate
with 24 hours of validity.
"""
certdir = os.path.join(_CONFIG_DIR, "transient_certs")
name = str(uuid.uuid4())
_generate_client_cert(certdir, name, transient=True)
#TODO
#self.active_is_transient = True
#self.transient_certs_created.append(name)
def _generate_persistent_client_cert():
"""
Interactively use `openssl` command to generate a new persistent client
certificate with one year of validity.
"""
certdir = os.path.join(_CONFIG_DIR, "client_certs")
print("What do you want to name this new certificate?")
print("Answering `mycert` will create `{0}/mycert.crt` and `{0}/mycert.key`".format(certdir))
name = input("> ")
if not name.strip():
print("Aborting.")
return
_generate_client_cert(certdir, name)
def _handle_cert_request(meta):
print("SERVER SAYS: ", meta)
# Present different messages for different 6x statuses, but
# handle them the same.
if status in ("64", "65"):
print("The server rejected your certificate because it is either expired or not yet valid.")
elif status == "63":
print("The server did not accept your certificate.")
print("You may need to e.g. coordinate with the admin to get your certificate fingerprint whitelisted.")
else:
print("The site {} is requesting a client certificate.".format(gi.host))
print("This will allow the site to recognise you across requests.")
# Give the user choices
print("What do you want to do?")
print("1. Give up.")
print("2. Generate a new transient certificate.")
print("3. Generate a new persistent certificate.")
print("4. Load a previously generated persistent.")
print("5. Load certificate from an external file.")
if self.sync_only:
choice = 1
else:
choice = input("> ").strip()
if choice == "2":
self._generate_transient_cert_cert()
elif choice == "3":
self._generate_persistent_client_cert()
elif choice == "4":
self._choose_client_cert()
elif choice == "5":
self._load_client_cert()
else:
print("Giving up.")
raise UserAbortException()
def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=None):
"""
Validate a TLS certificate in TOFU mode.
@ -500,7 +653,7 @@ def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=Non
sha.update(cert)
fingerprint = sha.hexdigest()
db_path = os.path.join(xdg("config"), "tofu.db")
db_path = os.path.join(_CONFIG_DIR, "tofu.db")
db_conn = sqlite3.connect(db_path)
db_cur = db_conn.cursor()
@ -530,7 +683,7 @@ def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=Non
db_conn.commit()
break
else:
certdir = os.path.join(xdg("config"), "cert_cache")
certdir = os.path.join(_CONFIG_DIR, "cert_cache")
with open(os.path.join(certdir, most_frequent_cert+".crt"), "rb") as fp:
previous_cert = fp.read()
if _HAS_CRYPTOGRAPHY:
@ -558,10 +711,10 @@ def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=Non
else:
choice = input("Accept this new certificate? Y/N ").strip().lower()
if choice in ("y", "yes"):
db_cur.execute("""INSERT INTO cert_cache
VALUES (?, ?, ?, ?, ?, ?)""",
(host, address, fingerprint, now, now, 1))
db_conn.commit()
self.db_cur.execute("""INSERT INTO cert_cache
VALUES (?, ?, ?, ?, ?, ?)""",
(host, address, fingerprint, now, now, 1))
self.db_conn.commit()
with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
fp.write(cert)
else:
@ -573,21 +726,51 @@ def _validate_cert(address, host, cert,accept_bad_ssl=False,automatic_choice=Non
VALUES (?, ?, ?, ?, ?, ?)""",
(host, address, fingerprint, now, now, 1))
db_conn.commit()
certdir = os.path.join(xdg("config"), "cert_cache")
certdir = os.path.join(_CONFIG_DIR, "cert_cache")
if not os.path.exists(certdir):
os.makedirs(certdir)
with open(os.path.join(certdir, fingerprint+".crt"), "wb") as fp:
fp.write(cert)
def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_certificates=False,\
**kwargs):
def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,**kwargs):
cache = None
newurl = url
url_parts = urllib.parse.urlparse(url)
host = url_parts.hostname
port = url_parts.port or standard_ports["gemini"]
path = url_parts.path or "/"
query = url_parts.query
# Be careful with client certificates!
# Are we crossing a domain boundary?
# TODO :code should be adapted to netcache
# if self.active_cert_domains and host not in self.active_cert_domains:
# if self.active_is_transient:
# print("Permanently delete currently active transient certificate?")
# resp = input("Y/N? ")
# if resp.strip().lower() in ("y", "yes"):
# print("Destroying certificate.")
# self._deactivate_client_cert()
# else:
# print("Staying here.")
# raise UserAbortException()
# else:
# print("PRIVACY ALERT: Deactivate client cert before connecting to a new domain?")
# resp = input("Y/N? ")
# if resp.strip().lower() in ("n", "no"):
# print("Keeping certificate active for {}".format(host))
# else:
# print("Deactivating certificate.")
# self._deactivate_client_cert()
#
# # Suggest reactivating previous certs
# if not self.client_certs["active"] and host in self.client_certs:
# print("PRIVACY ALERT: Reactivate previously used client cert for {}?".format(host))
# resp = input("Y/N? ")
# if resp.strip().lower() in ("y", "yes"):
# self._activate_client_cert(*self.client_certs[host])
# else:
# print("Remaining unidentified.")
# self.client_certs.pop(host)
# In AV-98, this was the _send_request method
#Send a selector to a given host and port.
#Returns the resolved address and binary file with the reply."""
@ -631,13 +814,20 @@ def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_ce
except ssl.SSLError:
# Rely on the server to only support sensible things, I guess...
pass
#TODO: certificate handling to refactor
# # Load client certificate if needed
# if self.client_certs["active"]:
# certfile, keyfile = self.client_certs["active"]
# context.load_cert_chain(certfile, keyfile)
# Connect to remote host by any address possible
err = None
for address in addresses:
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
s = context.wrap_socket(s, server_hostname = host)
try:
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
s = context.wrap_socket(s, server_hostname = host)
s.connect(address[4])
break
except OSError as e:
@ -650,15 +840,16 @@ def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_ce
# Do TOFU
cert = s.getpeercert(binary_form=True)
# TODO: another cert handling to refactor
# Remember that we showed the current cert to this domain...
#TODO : accept badssl and automatic choice
_validate_cert(address[4][0], host, cert,automatic_choice="y")
# if self.client_certs["active"]:
# self.active_cert_domains.append(host)
# self.client_certs[host] = self.client_certs["active"]
# Send request and wrap response in a file descriptor
url = urllib.parse.urlparse(url)
new_netloc = host
#Handle IPV6 hostname
if ":" in new_netloc:
new_netloc = "[" + new_netloc + "]"
if port != standard_ports["gemini"]:
new_netloc += ":" + str(port)
url = urllib.parse.urlunparse(url._replace(netloc=new_netloc))
@ -687,17 +878,12 @@ def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_ce
# Handle non-SUCCESS headers, which don't have a response body
# Inputs
if status.startswith("1"):
if interactive:
print(meta)
if status == "11":
user_input = getpass.getpass("> ")
else:
#TODO:FIXME we should not ask for user input while non-interactive
user_input = input("> ")
newurl = url.split("?")[0]
return _fetch_gemini(newurl+"?"+user_input)
print(meta)
if status == "11":
user_input = getpass.getpass("> ")
else:
return None,None
user_input = input("> ")
return _fetch_gemini(query(user_input))
# Redirects
elif status.startswith("3"):
newurl = urllib.parse.urljoin(url,meta)
@ -734,13 +920,13 @@ def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_ce
raise RuntimeError(meta)
# Client cert
elif status.startswith("6"):
error = "Handling certificates for status 6X are not supported by offpunk\n"
error += "See bug #31 for discussion about the problem"
raise RuntimeError(error)
_handle_cert_request(meta)
_fetch_gemini(url)
# Invalid status
elif not status.startswith("2"):
raise RuntimeError("Server returned undefined status code %s!" % status)
# If we're here, this must be a success and there's a response body
print("status :%s"%status)
assert status.startswith("2")
mime = meta
# Read the response body over the network
@ -767,47 +953,32 @@ def _fetch_gemini(url,timeout=DEFAULT_TIMEOUT,interactive=True,accept_bad_ssl_ce
else:
body = fbody
cache = write_body(url,body,mime)
return cache,newurl
return cache
def fetch(url,offline=False,download_image_first=True,images_mode="readable",validity=0,**kwargs):
def fetch(url,**kwargs):
url = normalize_url(url)
newurl = url
path=None
print_error = "print_error" in kwargs.keys() and kwargs["print_error"]
#Firt, we look if we have a valid cache, even if offline
#If we are offline, any cache is better than nothing
if is_cache_valid(url,validity=validity) or (offline and is_cache_valid(url,validity=0)):
if kwargs["offline"] and is_cache_valid(url):
path = get_cache_path(url)
#if the cache is a folder, we should add a "/" at the end of the URL
if not url.endswith("/") and os.path.isdir(get_cache_path(url,add_index=False)) :
newurl = url+"/"
elif offline and is_cache_valid(url,validity=0):
path = get_cache_path(url)
elif "://" in url and not offline:
elif "://" in url and not kwargs["offline"]:
try:
scheme = url.split("://")[0]
if scheme not in standard_ports:
if print_error:
print("%s is not a supported protocol"%scheme)
path = None
print("%s is not a supported protocol"%scheme)
elif scheme in ("http","https"):
if _DO_HTTP:
path=_fetch_http(url,**kwargs)
else:
print("HTTP requires python-requests")
path=_fetch_http(url,**kwargs)
elif scheme == "gopher":
path=_fetch_gopher(url,**kwargs)
elif scheme == "finger":
path=_fetch_finger(url,**kwargs)
elif scheme == "gemini":
path,newurl=_fetch_gemini(url,**kwargs)
elif scheme == "spartan":
path,newurl=_fetch_spartan(url,**kwargs)
path=_fetch_gemini(url,**kwargs)
else:
print("scheme %s not implemented yet"%scheme)
print("scheme %s not implemented yet")
except UserAbortException:
return None, newurl
return
except Exception as err:
cache = set_error(url, err)
# Print an error message
@ -830,13 +1001,13 @@ def fetch(url,offline=False,download_image_first=True,images_mode="readable",val
print("""ERROR5: Trying to create a directory which already exists
in the cache : """)
print(err)
elif _DO_HTTP and isinstance(err,requests.exceptions.SSLError):
elif isinstance(err,requests.exceptions.SSLError):
if print_error:
print("""ERROR6: Bad SSL certificate:\n""")
print(err)
print("""\n If you know what you are doing, you can try to accept bad certificates with the following command:\n""")
print("""set accept_bad_ssl_certificates True""")
elif _DO_HTTP and isinstance(err,requests.exceptions.ConnectionError):
elif isinstance(err,requests.exceptions.ConnectionError):
if print_error:
print("""ERROR7: Cannot connect to URL:\n""")
print(str(err))
@ -846,35 +1017,16 @@ def fetch(url,offline=False,download_image_first=True,images_mode="readable",val
print("ERROR4: " + str(type(err)) + " : " + str(err))
#print("\n" + str(err.with_traceback(None)))
print(traceback.format_exc())
return cache, newurl
# We download images contained in the document (from full mode)
if not offline and download_image_first and images_mode:
renderer = ansicat.renderer_from_file(path,newurl)
if renderer:
for image in renderer.get_images(mode=images_mode):
#Image should exist, should be an url (not a data image)
#and should not be already cached
if image and not image.startswith("data:image/") and not is_cache_valid(image):
width = offutils.term_width() - 1
toprint = "Downloading %s" %image
toprint = toprint[:width]
toprint += " "*(width-len(toprint))
print(toprint,end="\r")
#d_i_f and images_mode are False/None to avoid recursive downloading
#if that ever happen
fetch(image,offline=offline,download_image_first=False,\
images_mode=None,validity=0,**kwargs)
return path, newurl
return cache
else:
print("Not cached URL or not supported format (TODO)")
return path
def main():
descri="Netcache is a command-line tool to retrieve, cache and access networked content.\n\
By default, netcache will returns a cached version of a given URL, downloading it \
only if not existing. A validity duration, in seconds, can also be given so that \
netcache downloads the content only if the existing cache is older than the validity."
# Parse arguments
parser = argparse.ArgumentParser(prog="netcache",description=descri)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--path", action="store_true",
help="return path to the cache instead of the content of the cache")
parser.add_argument("--offline", action="store_true",
@ -883,12 +1035,11 @@ def main():
help="Cancel download of items above that size (value in Mb).")
parser.add_argument("--timeout", type=int,
help="Time to wait before cancelling connection (in second).")
parser.add_argument("--cache-validity",type=int, default=0,
help="maximum age, in second, of the cached version before \
redownloading a new version")
# No argument: write help
parser.add_argument('url', metavar='URL', nargs='*',
help='download URL and returns the content or the path to a cached version')
# arg = URL: download and returns cached URI
# --cache-validity : do not download if cache is valid
# --validity : returns the date of the cached version, Null if no version
# --force-download : download and replace cache, even if valid
args = parser.parse_args()
@ -899,8 +1050,8 @@ def main():
if args.offline:
path = get_cache_path(u)
else:
path,url = fetch(u,max_size=args.max_size,timeout=args.timeout,\
validity=args.cache_validity)
print("Download URL: %s" %u)
path = fetch(u,max_size=args.max_size,timeout=args.timeout)
if args.path:
print(path)
else:

View File

@ -1,33 +0,0 @@
# The following are the default redirections from Offpunk
# Those are by default because they should make sens with offpunk
redirects = {
"*twitter.com" : "nitter.net",
"youtube.com" : "yewtu.be",
"youtu.be" : "yewtu.be",
"*reddit.com" : "teddit.net",
"*medium.com" : "scribe.rip",
}
#following are blocked URLs. Visiting them with offpunk doesnt make sense.
#Blocking them will save a lot of bandwith
blocked = {
"*facebook.com",
"*facebook.net",
"*fbcdn.net",
"*linkedin.com",
"*licdn.com",
"*admanager.google.com",
"*google-health-ads.blogspot.com",
"*firebase.google.com",
"*google-webfonts-helper.herokuapp.com",
"*tiktok.com" ,
"*doubleclick.net",
"*google-analytics.com" ,
"*ads.yahoo.com",
"*advertising.amazon.com",
"*advertising.theguardian.com",
"*advertise.newrepublic.com",
}

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
#!/bin/python
colors = {
"bold" : ["1","22"],
"faint" : ["2","22"],
"italic" : ["3","23"],
"underline": ["4","24"],
"black" : ["30","39"],
"red" : ["31","39"],
"green" : ["32","39"],
"yellow" : ["33","39"],
"blue" : ["34","39"],
"purple" : ["35","39"],
"cyan" : ["36","39"],
"white" : ["37","39"],
"background_black" : ["40","49"],
"background_red" : ["41","49"],
"background_green" : ["42","49"],
"background_yellow" : ["43","49"],
"background_blue" : ["44","49"],
"background_purple" : ["45","49"],
"background_cyan" : ["46","49"],
"background_white" : ["47","49"],
"bright_black" : ["90","39"],
"bright_red" : ["91","39"],
"bright_green" : ["92","39"],
"bright_yellow" : ["93","39"],
"bright_blue" : ["94","39"],
"bright_purple" : ["95","39"],
"bright_cyan" : ["96","39"],
"bright_white" : ["97","39"],
}
offpunk1 = {
"window_title" : ["red","bold"],
"window_subtitle" : ["red","faint"],
"title" : ["blue","bold","underline"],
"subtitle" : ["blue"],
"subsubtitle" : ["blue","faint"], #fallback to subtitle if none
"link" : ["blue","faint"],
"new_link": ["bold"],
"oneline_link": [], #for gopher/gemini. fallback to link if none
"image_link" : ["yellow","faint"],
"preformatted": ["faint"],
"blockquote" : ["italic"],
"prompt_on" : ["green"],
"prompt_off" : ["green"],
}
default = offpunk1

View File

@ -11,153 +11,17 @@ import io
import subprocess
import shutil
import shlex
import urllib.parse
import urllib.parse
import netcache_migration
import netcache
CACHE_VERSION = 1
# We upgrade the cache only once at startup, hence the UPGRADED variable
# This is only to avoid unecessary checks each time the cache is accessed
UPGRADED=False
def upgrade_cache(cache_folder):
#Lets read current version of the cache
version_path = cache_folder + ".version"
current_version = 0
if os.path.exists(version_path):
current_str = None
with open(version_path) as f:
current_str = f.read()
f.close()
try:
current_version = int(current_str)
except:
current_version = 0
#Now, lets upgrade the cache if needed
while current_version < CACHE_VERSION:
current_version += 1
upgrade_func = getattr(netcache_migration,"upgrade_to_"+str(current_version))
upgrade_func(cache_folder)
with open(version_path,"w") as f:
f.write(str(current_version))
f.close()
UPGRADED=True
#get xdg folder. Folder should be "cache", "data" or "config"
def xdg(folder="cache"):
## Config directories
## We implement our own python-xdg to avoid conflict with existing libraries.
_home = os.path.expanduser('~')
data_home = os.environ.get('XDG_DATA_HOME') or \
os.path.join(_home,'.local','share')
config_home = os.environ.get('XDG_CONFIG_HOME') or \
os.path.join(_home,'.config')
_CONFIG_DIR = os.path.join(os.path.expanduser(config_home),"offpunk/")
_DATA_DIR = os.path.join(os.path.expanduser(data_home),"offpunk/")
_old_config = os.path.expanduser("~/.offpunk/")
## Look for pre-existing config directory, if any
if os.path.exists(_old_config):
_CONFIG_DIR = _old_config
#if no XDG .local/share and not XDG .config, we use the old config
if not os.path.exists(data_home) and os.path.exists(_old_config):
_DATA_DIR = _CONFIG_DIR
## get _CACHE_PATH from OFFPUNK_CACHE_PATH environment variable
# if OFFPUNK_CACHE_PATH empty, set default to ~/.cache/offpunk
cache_home = os.environ.get('XDG_CACHE_HOME') or\
os.path.join(_home,'.cache')
_CACHE_PATH = os.environ.get('OFFPUNK_CACHE_PATH', \
os.path.join(os.path.expanduser(cache_home),"offpunk/"))
#Check that the cache path ends with "/"
if not _CACHE_PATH.endswith("/"):
_CACHE_PATH += "/"
os.makedirs(_CACHE_PATH,exist_ok=True)
if folder == "cache" and not UPGRADED:
upgrade_cache(_CACHE_PATH)
if folder == "cache":
return _CACHE_PATH
elif folder == "config":
return _CONFIG_DIR
elif folder == "data":
return _DATA_DIR
else:
print("No XDG folder for %s. Check your code."%folder)
return None
#An IPV6 URL should be put between []
#We try to detect them has location with more than 2 ":"
def fix_ipv6_url(url):
if not url or url.startswith("mailto"):
return url
if "://" in url:
schema, schemaless = url.split("://",maxsplit=1)
else:
schema, schemaless = None, url
if "/" in schemaless:
netloc, rest = schemaless.split("/",1)
if netloc.count(":") > 2 and "[" not in netloc and "]" not in netloc:
schemaless = "[" + netloc + "]" + "/" + rest
elif schemaless.count(":") > 2 and "[" not in schemaless and "]" not in schemaless:
schemaless = "[" + schemaless + "]/"
if schema:
return schema + "://" + schemaless
return schemaless
# Cheap and cheerful URL detector
def looks_like_url(word):
try:
if not word.strip():
return False
url = fix_ipv6_url(word).strip()
parsed = urllib.parse.urlparse(url)
#sometimes, urllib crashed only when requesting the port
port = parsed.port
scheme = word.split("://")[0]
mailto = word.startswith("mailto:")
start = scheme in netcache.standard_ports
local = scheme in ["file","list"]
if mailto:
return "@" in word
elif not local:
if start:
#IPv4
if "." in word or "localhost" in word:
return True
#IPv6
elif "[" in word and ":" in word and "]" in word:
return True
else: return False
else: return False
return start and ("." in word or "localhost" in word or ":" in word)
else:
return "/" in word
except ValueError:
return False
## Those two functions add/remove the mode to the
# URLs. This is a gross hack to remember the mode
def mode_url(url,mode):
if mode and mode!= "readable" and "##offpunk=" not in url:
url += "##offpunk_mode=" + mode
return url
def unmode_url(url):
mode = None
splitted = url.split("##offpunk_mode=")
if len(splitted) > 1:
url = splitted[0]
mode = splitted[1]
return [url,mode]
# In terms of arguments, this can take an input file/string to be passed to
# stdin, a parameter to do (well-escaped) "%" replacement on the command, a
# flag requesting that the output go directly to the stdout, and a list of
# additional environment variables to set.
def run(cmd, *, input=None, parameter=None, direct_output=False, env={}):
#print("running %s"%cmd)
if parameter:
cmd = cmd % shlex.quote(parameter)
#following requires python 3.9 (but is more elegant/explicit):
# env = dict(os.environ) | env
e = os.environ
e.update(env)
if isinstance(input, io.IOBase):
@ -178,49 +42,16 @@ def run(cmd, *, input=None, parameter=None, direct_output=False, env={}):
global TERM_WIDTH
TERM_WIDTH = 72
TERM_WIDTH = 80
#if absolute, returns the real terminal width, not the text width
def term_width(new_width=None,absolute=False):
def term_width(new_width=None):
if new_width:
global TERM_WIDTH
TERM_WIDTH = new_width
cur = shutil.get_terminal_size()[0]
if absolute:
return cur
width = TERM_WIDTH
cur = shutil.get_terminal_size()[0]
if cur < width:
width = cur
return width
def is_local(url):
if not url: return True
elif "://" in url:
scheme,path = url.split("://",maxsplit=1)
return scheme in ["file","mail","list","mailto"]
else:
return True
# This method return the image URL or invent it if its a base64 inline image
# It returns [url,image_data] where image_data is None for normal image
def looks_like_base64(src,baseurl):
imgdata = None
imgname = src
if src and src.startswith("data:image/"):
if ";base64," in src:
splitted = src.split(";base64,")
#splitted[0] is something like data:image/jpg
if "/" in splitted[0]:
extension = splitted[0].split("/")[1]
else:
extension = "data"
imgdata = splitted[1]
imgname = imgdata[:20] + "." + extension
imgurl = urllib.parse.urljoin(baseurl, imgname)
else:
#We cant handle other data:image such as svg for now
imgurl = None
else:
imgurl = urllib.parse.urljoin(baseurl, imgname)
return imgurl,imgdata

291
opnk.py Executable file → Normal file
View File

@ -1,300 +1,39 @@
#!/usr/bin/env python3
#!/bin/python
#opnk stand for "Open like a PuNK".
#It will open any file or URL and display it nicely in less.
#If not possible, it will fallback to xdg-open
#URL are retrieved through netcache
import os
import sys
import tempfile
import argparse
import netcache
import ansicat
import offutils
import shutil
import time
import fnmatch
from offutils import run,term_width,mode_url,unmode_url,is_local
_HAS_XDGOPEN = shutil.which('xdg-open')
_GREP = "grep --color=auto"
less_version = 0
if not shutil.which("less"):
print("Please install the pager \"less\" to run Offpunk.")
print("If you wish to use another pager, send me an email!")
print("(Im really curious to hear about people not having \"less\" on their system.)")
sys.exit()
output = run("less --version")
# We get less Version (which is the only integer on the first line)
words = output.split("\n")[0].split()
less_version = 0
for w in words:
if w.isdigit():
less_version = int(w)
# restoring position only works for version of less > 572
if less_version >= 572:
_LESS_RESTORE_POSITION = True
else:
_LESS_RESTORE_POSITION = False
#_DEFAULT_LESS = "less -EXFRfM -PMurl\ lines\ \%lt-\%lb/\%L\ \%Pb\%$ %s"
# -E : quit when reaching end of file (to behave like "cat")
# -F : quit if content fits the screen (behave like "cat")
# -X : does not clear the screen
# -R : interpret ANSI colors correctly
# -f : suppress warning for some contents
# -M : long prompt (to have info about where you are in the file)
# -W : hilite the new first line after a page skip (space)
# -i : ignore case in search
# -S : do not wrap long lines. Wrapping is done by offpunk, longlines
# are there on purpose (surch in asciiart)
#--incsearch : incremental search starting rev581
def less_cmd(file, histfile=None,cat=False,grep=None):
less_prompt = "page %%d/%%D- lines %%lb/%%L - %%Pb\\%%"
if less_version >= 581:
less_base = "less --incsearch --save-marks -~ -XRfWiS -P \"%s\""%less_prompt
elif less_version >= 572:
less_base = "less --save-marks -XRfMWiS"
else:
less_base = "less -XRfMWiS"
_DEFAULT_LESS = less_base + " \"+''\" %s"
_DEFAULT_CAT = less_base + " -EF %s"
if histfile:
env = {"LESSHISTFILE": histfile}
else:
env = {}
if cat:
cmd_str = _DEFAULT_CAT
elif grep:
grep_cmd = _GREP
#case insensitive for lowercase search
if grep.islower():
grep_cmd += " -i"
cmd_str = _DEFAULT_CAT + "|" + grep_cmd + " %s"%grep
else:
cmd_str = _DEFAULT_LESS
run(cmd_str, parameter=file, direct_output=True, env=env)
class opencache():
def __init__(self):
# We have a cache of the rendering of file and, for each one,
# a less_histfile containing the current position in the file
self.temp_files = {}
self.less_histfile = {}
# This dictionary contains an url -> ansirenderer mapping. This allows
# to reuse a renderer when visiting several times the same URL during
# the same session
# We save the time at which the renderer was created in renderer_time
# This way, we can invalidate the renderer if a new version of the source
# has been downloaded
self.rendererdic = {}
self.renderer_time = {}
self.mime_handlers = {}
self.last_mode = {}
self.last_width = term_width(absolute=True)
def _get_handler_cmd(self, mimetype):
# Now look for a handler for this mimetype
# Consider exact matches before wildcard matches
exact_matches = []
wildcard_matches = []
for handled_mime, cmd_str in self.mime_handlers.items():
if "*" in handled_mime:
wildcard_matches.append((handled_mime, cmd_str))
else:
exact_matches.append((handled_mime, cmd_str))
for handled_mime, cmd_str in exact_matches + wildcard_matches:
if fnmatch.fnmatch(mimetype, handled_mime):
break
else:
# Use "xdg-open" as a last resort.
if _HAS_XDGOPEN:
cmd_str = "xdg-open %s"
else:
cmd_str = "echo \"Cant find how to open \"%s"
print("Please install xdg-open (usually from xdg-util package)")
return cmd_str
# Return the handler for a specific mimetype.
# Return the whole dic if no specific mime provided
def get_handlers(self,mime=None):
if mime and mime in self.mime_handlers.keys():
return self.mime_handlers[mime]
elif mime:
return None
else:
return self.mime_handlers
def set_handler(self,mime,handler):
previous = None
if mime in self.mime_handlers.keys():
previous = self.mime_handlers[mime]
self.mime_handlers[mime] = handler
if "%s" not in handler:
print("WARNING: this handler has no %%s, no filename will be provided to the command")
if previous:
print("Previous handler was %s"%previous)
def get_renderer(self,inpath,mode=None,theme=None):
# We remove the ##offpunk_mode= from the URL
# If mode is already set, we dont use the part from the URL
inpath,newmode = unmode_url(inpath)
if not mode: mode = newmode
# If we still doesnt have a mode, we see if we used one before
if not mode and inpath in self.last_mode.keys():
mode = self.last_mode[inpath]
elif not mode:
#default mode is readable
mode = "readable"
renderer = None
path = netcache.get_cache_path(inpath)
if path:
usecache = inpath in self.rendererdic.keys() and not is_local(inpath)
#Screen size may have changed
width = term_width(absolute=True)
if usecache and self.last_width != width:
self.cleanup()
usecache = False
self.last_width = width
if usecache:
if inpath in self.renderer_time.keys():
last_downloaded = netcache.cache_last_modified(inpath)
last_cached = self.renderer_time[inpath]
if last_cached and last_downloaded:
usecache = last_cached > last_downloaded
else:
usecache = False
else:
usecache = False
if not usecache:
renderer = ansicat.renderer_from_file(path,url=inpath,theme=theme)
if renderer:
self.rendererdic[inpath] = renderer
self.renderer_time[inpath] = int(time.time())
else:
renderer = self.rendererdic[inpath]
return renderer
def get_temp_filename(self,url):
if url in self.temp_files.keys():
return self.temp_files[url]
else:
return None
def opnk(self,inpath,mode=None,terminal=True,grep=None,theme=None,**kwargs):
#Return True if inpath opened in Terminal
# False otherwise
# also returns the url in case it has been modified
def opnk(inpath,terminal=True):
#if terminal = False, we dont try to open in the terminal,
#we immediately fallback to xdg-open.
#netcache currently provide the path if its a file.
if not offutils.is_local(inpath):
kwargs["images_mode"] = mode
cachepath,inpath = netcache.fetch(inpath,**kwargs)
if not cachepath:
return False, inpath
# folowing line is for :// which are locals (file,list)
elif "://" in inpath:
cachepath,inpath = netcache.fetch(inpath,**kwargs)
elif inpath.startswith("mailto:"):
cachepath = inpath
elif os.path.exists(inpath):
cachepath = inpath
else:
print("%s does not exist"%inpath)
return False, inpath
renderer = self.get_renderer(inpath,mode=mode,theme=theme)
if renderer and mode:
renderer.set_mode(mode)
self.last_mode[inpath] = mode
if not mode and inpath in self.last_mode.keys():
mode = self.last_mode[inpath]
renderer.set_mode(mode)
#we use the full moded url as key for the dictionary
key = mode_url(inpath,mode)
if terminal and renderer:
#If this is an image and we have chafa/timg, we
#dont use less, we call it directly
if renderer.has_direct_display():
renderer.display(mode=mode,directdisplay=True)
return True, inpath
else:
body = renderer.display(mode=mode)
#Should we use the cache? only if it is not local and theres a cache
usecache = key in self.temp_files and not is_local(inpath)
if usecache:
#and the cache is still valid!
last_downloaded = netcache.cache_last_modified(inpath)
last_cached = os.path.getmtime(self.temp_files[key])
if last_downloaded > last_cached:
usecache = False
self.temp_files.pop(key)
self.less_histfile.pop(key)
# We actually put the body in a tmpfile before giving it to less
if not usecache:
tmpf = tempfile.NamedTemporaryFile("w", encoding="UTF-8", delete=False)
self.temp_files[key] = tmpf.name
tmpf.write(body)
tmpf.close()
if key not in self.less_histfile:
firsttime = True
tmpf = tempfile.NamedTemporaryFile("w", encoding="UTF-8", delete=False)
self.less_histfile[key] = tmpf.name
else:
#We dont want to restore positions in lists
firsttime = is_local(inpath)
less_cmd(self.temp_files[key], histfile=self.less_histfile[key],cat=firsttime,grep=grep)
return True, inpath
#maybe, we have no renderer. Or we want to skip it.
else:
mimetype = ansicat.get_mime(cachepath)
if mimetype == "mailto":
mail = inpath[7:]
resp = input("Send an email to %s Y/N? " %mail)
if resp.strip().lower() in ("y", "yes"):
if _HAS_XDGOPEN :
run("xdg-open mailto:%s", parameter=mail,direct_output=True)
else:
print("Cannot find a mail client to send mail to %s" %inpath)
print("Please install xdg-open (usually from xdg-util package)")
return False, inpath
else:
cmd_str = self._get_handler_cmd(mimetype)
try:
run(cmd_str, parameter=netcache.get_cache_path(inpath), direct_output=True)
except FileNotFoundError:
print("Handler program %s not found!" % shlex.split(cmd_str)[0])
print("You can use the ! command to specify another handler program or pipeline.")
return False, inpath
#may this should be migrated here.
path = netcache.get_cache_path(inpath)
#TODO: migrate here ansirenderer display
1. À partir du path, tenter le ansirenderer
2. Sauver le rendu dans self.temp_files[mode] (donc le mode doit être passé à opnk)
3. Sauver le renderer dans self.rendererdic
3. Donner à less
4. sinon, donner à xdg-open
#We remove the renderers from the cache and we also delete temp files
def cleanup(self):
while len(self.temp_files) > 0:
os.remove(self.temp_files.popitem()[1])
while len(self.less_histfile) > 0:
os.remove(self.less_histfile.popitem()[1])
self.last_width = None
self.rendererdic = {}
self.renderer_time = {}
self.last_mode = {}
def main():
descri = "opnk is an universal open command tool that will try to display any file \
in the pager less after rendering its content with ansicat. If that fails, \
opnk will fallback to opening the file with xdg-open. If given an URL as input \
instead of a path, opnk will rely on netcache to get the networked content."
parser = argparse.ArgumentParser(prog="opnk",description=descri)
parser.add_argument("--mode", metavar="MODE",
help="Which mode should be used to render: normal (default), full or source.\
With HTML, the normal mode try to extract the article.")
parser.add_argument("content",metavar="INPUT", nargs="*",
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("content",metavar="INPUT", nargs="*", type=argparse.FileType("r"),
default=sys.stdin, help="Path to the file or URL to open")
parser.add_argument("--cache-validity",type=int, default=0,
help="maximum age, in second, of the cached version before \
redownloading a new version")
args = parser.parse_args()
cache = opencache()
for f in args.content:
cache.opnk(f,mode=args.mode,validity=args.cache_validity)
cache.opnk(f)
if __name__ == "__main__":
main()

View File

@ -1,21 +1,21 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"
[project]
name = "offpunk"
authors = [
{name = "Solderpunk", email = "solderpunk@sdf.org"},
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
{name = "Lionel Dricot (Ploum)", email = "offpunk@ploum.eu"},
]
maintainers = [
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
{name = "Lionel Dricot (Ploum)", email = "offpunk@ploum.eu"},
]
readme = "README.md"
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Communications",
@ -35,6 +35,7 @@ html = ["bs4", "readability-lxml"]
http = ["requests"]
process-title = ["setproctitle"]
rss = ["feedparser"]
timg = ["timg>=1.3.2"]
[project.urls]
Homepage = "https://sr.ht/~lioploum/offpunk/"
@ -43,16 +44,6 @@ Source = "https://git.sr.ht/~lioploum/offpunk"
[project.scripts]
offpunk = "offpunk:main"
netcache = "netcache:main"
ansicat = "ansicat:main"
opnk = "opnk:main"
[tool.hatch.version]
path = "offpunk.py" # read __version__
[tool.hatch.build.targets.wheel]
only-include = [
"ansicat.py", "netcache_migration.py", "netcache.py",
"offblocklist.py", "offpunk.py", "offthemes.py",
"offutils.py", "opnk.py",
]
[tool.flit.sdist]
include = ["doc/", "man/", "CHANGELOG"]

View File

@ -7,4 +7,3 @@ readability-lxml
pillow
setproctitle
timg
file

View File

@ -1 +1 @@
sudo apt install less file xdg-utils xsel chafa timg python3-cryptography python3-requests python3-feedparser python3-bs4 python3-readability python3-pil python3-setproctitle python3-chardet file
sudo apt install less file xdg-utils xsel chafa timg python3-cryptography python3-requests python3-feedparser python3-bs4 python3-readability python3-pil python3-setproctitle python3-chardet