pax_global_header 0000666 0000000 0000000 00000000064 14775435273 0014533 g ustar 00root root 0000000 0000000 52 comment=efedc1cc850c17450022cba4762e7d0aa361157b
offpunk-v2.7.1/ 0000775 0000000 0000000 00000000000 14775435273 0013400 5 ustar 00root root 0000000 0000000 offpunk-v2.7.1/.build.yml 0000664 0000000 0000000 00000002221 14775435273 0015275 0 ustar 00root root 0000000 0000000 image: alpine/latest
oauth: pages.sr.ht/PAGES:RW
packages:
- hut
- uv
secrets: # see https://builds.sr.ht/secrets
- c4b4edb9-6d07-45fe-ac31-5d3ac6a27a8a #~/.pypi-credentials mode 700
environment:
site1: offpunk.net
site2: xkcdpunk.net
tasks:
# The following, contributed by Anna Cybertailor, will automatically
# upload the package to pypi if it is a release
- publish-pypi: |
if [[ ${GIT_REF} != refs/tags/* ]]; then
echo "Current commit is not a tag; not building anything"
exit 0
fi
rm -rf dist
uv build
~/.pypi-credentials
uv publish dist/*
- package-gemini: |
cp -r offpunk/tutorial public_gemini
cd public_gemini
ln -s ../offpunk/screenshots .
tar -cvzh . > ../capsule.tar.gz
- deploy-gemini: |
hut pages publish capsule.tar.gz -p GEMINI -d $site1
hut pages publish capsule.tar.gz -p GEMINI -d $site2
- package-html: |
mkdir public_html
cd offpunk/tutorial
python make_website.py
cd ../../public_html
ln -s ../offpunk/screenshots .
tar -cvzh . > ../site.tar.gz
- deploy-html: |
hut pages publish site.tar.gz -d $site1
hut pages publish site.tar.gz -d $site2
offpunk-v2.7.1/.gitignore 0000664 0000000 0000000 00000002451 14775435273 0015372 0 ustar 00root root 0000000 0000000 # ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
offpunk-v2.7.1/CHANGELOG 0000664 0000000 0000000 00000060516 14775435273 0014622 0 ustar 00root root 0000000 0000000 # Offpunk History
## 2.7.1 - April 9th 2025 - The "2.7 was not (completely) a joke" release
See 2.7 changelog. This was "real" release ;-)
- Reverted the tutorial back to Offpunk. The name was a joke but the rest of the release is real.
- added "application/xhtml+xml" mimetype to be rendered as html
- according to html spec,
content should be parsed as HTML.
## 2.7 - April 1st 2025 - XKCDpunk release
APRIL FOOL: Offpunk is now renamed to XKCDpunk. See
https://ploum.net/2025-04-01-xkcdpunk.html
- Introducing command "xkcd" to display a given xkcd comic.
- (April fool) Switching website from offpunk.net to xkcdpunk.net
- blocklist: marked x.com, twitter.com and youtube.com as blocked to save bandwith until we have a viable option to use them with offpunk. We plan to block everything but xkcd.com.
CHANGES:
- "shell" (or "!") now works even without content (so you can run it on startup)
- offpunk: improved "version" to help debugging on the mailing-list
FIXES:
- "reload" on a too large content will actually fetch it
- Consider mimetype "message/news" as "gemtext" because file is sometimes confused. (reported by JMCS)
- ignore annoying warnings for LibreSSL users (by Anna cyberTailor)
- ansicat: workaround what seems to be a BS4 bug where elements after a were ignored
- offpunk: be more explicit about how to unblock a blocked URL
- ansicat: if a file identified as html starts with "260 char) instead of raising an useless error
## 2.6 - February 24th 2025
FOR PACKAGERS: dependency to python-pil (or pillow) has been dropped
- NEW BEHAVIOUR: not rendered ressources (like PDF) are not opened automatically.
The user is prompted to type "open" to see the ressource. This allows the ressource
to be part of history, be bookmarked, etc…
Offpunk:
- new "--command" command-line argument to immediately launch one or multiple commands
- "add" now accepts link number as a second argument (suggested by JMCS)
- "url" now accepts link number as an argument (suggested by JMCS)
- "url" can be piped to any shell command: "url|" or "url 121|" (suggestion of Stephen)
Ansicat and rendering:
- new "preformat_wrap" option available to wrap even
- PlainText rendering has been vastly improved with wrap, margin and link detection
- fix wrong wraping in gophermap (patch by JMCS)
Opnk and opening files:
note: "opnk" will be renamed "openk" in 3.0
- "opnk" now supports following link like in "opnk $URL XX" where XX is a link number.
- "opnk" is now reading the offpunrc file to use predefined handlers
- "handler" with now automatically add "%s" at the end of the command if not present
- "handler" now supports file exension or full mimetype
Deprecation and removal:
- removed support for chafa < 1.10, as announced in 2.4. python-pil is not used anymore.
- removed the "cat" command as it has no purpose (you can use "!cat" instead) and there was a potential crash (reported by Stephen)
- new "feed" command to replace the "view feed" (which is deprecated)
## 2.5 - January 30th 2025
- "abbrevs" has been replaced by "alias"
- "alias" now allows custom command to be aliased
- PEP8-ification by Vincent Jousse
- changing "datetime.UTC" to "datetime.timezone.utc" for retrocompatibility with python < 3.11
- checking if "grep" supports "--color=auto" to supports OpenBSD (reported by Dylan D’Silva)
## 2.4 - November 21st 2024
NEW WEBSITE: Official homepage is now https://offpunk.net (or gemini://offpunk.net). Sources are in the /tutorial/ folder and contributions are welcome.
NEW FEATURE: This release includes work by Bert Livens to add gemini client-side certificates (see "help certs"). This means you can browse gemini capsule while being identified (such as astrobotany)
- Deprecation warning if using Chafa < 1.10
- introducing the "tutorial" command (which is only a link to offpunk.net for now)
- netcache: use client-certificate when going to a url like gemini://username@site.net (by Bert Livens)
- offpunk/netcache: added the "cert" command to list and create client certificates (Bert Livens)
- "open" now accept integer as parameters to open links (suggested by Matthieu Rakotojaona)
- fix cache not being properly accessed when server redirect to same host with standard port (gemini.ucant.org)
- fix crash when expired certificate due to not_valid_after deprecation
- fix crash in netcache when a port cannot be parsed in the URL
- fix parameter "interactive=False" not being sent to gemini redirections
- fix problem with non-integer version of less (Patch by Peter Cock)
- Gopher: hide lines starting with TAB (drkhsh.at), reported by Dylan D’Silva
## 2.3 - June 29th 2024
- Wayland clipboard support through wl-clipboard (new suggested dependency)
- Xclip clipboard support (in case xsel is missing)
- 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
- ansicat: remove the treshold argument when launching chafa (strange artifacts with new version)
- netcache: moved the certificate cache to the filesystem instead of a database (by Bert Livens)
## 2.2 - February 13th 2024
- 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 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 and (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 don’t 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 doesn’t 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 don’t 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 RSS feeds without 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:
- 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 don’t 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)
## 1.10 - July 31st 2023
- 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
- Add missing chardet module (Sotiris Papatheodorou)
- Fix merging dictionaries with common keys (Sotiris Papatheodorou)
- Fix Gopher requests (rewrite URL parsing code per RFC 4266)
## 1.9.2 - March 13th 2023
- Switch from setup.py to flit (Anna cybertailor Vyalkova)
- Bump requirements to python >= 3.7 (Anna cybertailor Vyalkova)
## 1.9.1 - March 8th 2023
- Fixed crash with archive without GI (thanks Étienne Mollier)
## 1.9 - March 8th 2023
This is a bug-fixing release.
- We now have a man page thanks to phoebos!
- ".." as abbreviation to "up" (by Sotiris Papatheodorou)
- Fix support for UTF-8 domains in Gemini (Maeve Sproule, fixes #5)
- Assume UTF-8 when the header answer with an unknown encoding
- Default handlers have been removed (not everybody use feh and zathura)
- Fix a crash when subscribing without GI (reported by sodimel on linuxfr)
- Fix a crash when trying to access a link without GI (Ben Winston)
- Fix a crash when rss items don’t have a title (eg: Mastodon rss)
- Fix a crash with badly formatted links in gopher ( #7 by xiu)
- Fix a crash were some HTML content is seen a bytes instead of a string
- Fix a crash when displaying embedded CDATA html in feed. But #10 is still open.
- Fix error handling assuming that requests is installed
- Ugly fix for a rare certificate bug (fix #11)
- Improve compatibility with python prior 3.9 by replacing a dict union
## 1.8 - December 11th 2022
- Official URL is now https://sr.ht/~lioploum/offpunk/
- SECURITY: Avoid passing improperly-escaped paths to shell (fixes notabug #9) (by Maeve Sproule)
- Add support for the finger protocol (by Sotiris Papatheodorou)
- "restricted" mode has been removed because unmaintained (code cleanup)
- "set accept_bad_ssl_certificates True" allows to lower HTTPS SSL requirements (also with --assume-yes)
- Accept "localhost" as a valid URL
- Better feedback when --sync an URL which is streaming
- Removed cgi dependency (soon deprecated)
- Fix: crash with some svg data:image (which are now ignored)
- Fix images from "full" mode not being downloaded
- Fix a crash when ls on empty page (thanks Marty Oehme)
- Fix: A variable was not initialised without python-cryptography
- Fix: "cp raw" was not accessing the temp_file correctly
- Fix: ANSI handling off arrows in readline (by Ben Winston)
## 1.7.1 - November 15th 2022
- Correcting a stupid crash in search (thanks kelbot for the report)
## 1.7 - November 15th 2022
- New "search" command which uses kennedy.gemi.dev by default.
- New "wikipedia" command, which uses vault.transjovian.org by default.
- Aliases "wen", "wfr" and "wes" for Wikipedia in English, French and Spanish.
- Autocompletion for the list/add/move commands (that’s incredibly useful!)
- If a link is found in plain text in a gopher/gemini page, it is now
added to the list of links for that page. Useful for gopher.
- Create system lists when needed to avoid failure on clean system
- Solve a crash when parsing wrong URL (related to bug #9 )
- Solve a crash when loading webpages with empty links
- Solve a crash when trying to load a wrong URL into tour
=> gemini://ploum.be/2022-11-15-offpunk17-sourcehut.gmi
## 1.6 - October 12th 2022
- Support for base64 encoded pictures in HTML pages (opening them full screen only works offline)
- A list can be added to a tour with "tour $LIST_NAME".
- Check for timg > 1.3.2 to avoid dealing with old versions (bug reported by Valvin)
- Redirect are now honoured also when --sync (bug #15, thanks kelbot)
- RSS feeds are now automatically downloaded with a webpage (bug #14)
- Solved the bug where an invalid URL would break correspondance between url and numbers
- Considers .xml files as feed by default to avoid false-detection as SVG
- Replaced default libreddit.com redirection to teddit.net (bug #12 by kelbot)
- The "beta" option has been removed as it is not used (update your config if needed)
## 1.5 - August 4th 2022
- Removed optional dependency to ripgrep. "grep --color=auto" is good enough.
- "open url" to open current URL in a browser with xdg-open
- "redirect" now replaces "set redirects" to improve discoverability
- "redirect" now allows urls to be blocked. By default, facebook.com and google-analytics.com are blocked
- Fixed a bug when trying to download base64 image
=> gemini://rawtext.club/~ploum/2022-08-04-offpunk15.gmi
## 1.4 - April 25th 2022
- Making python-readability optional
- Removing "next" and "previous" which are quite confusing and not obvious
- Archiving now works regardless of the view you are in.
- Fixing a crash when accessing an empty html page
- Not trying to display non-image files to avoid errors. (this requires "file")
## 1.3 - April 2th 2022
- Removed dependency to python-magic. File is now used directly (and should be on every system).
- Removed dependency to python-editor. If no $VISUAL or $EDITOR, please use "set editor" in Offpunk.
- Images are now downloaded before displaying an HTML page (can be disabled with "set download_images_first False")
- Introduced "set redirects" which redirects twitter,youtube,medium,reddit to alternative frontends.
- New behaviour for "find" (or "/") which is to grep through current page (ripgrep used if detected)
- Default width set to 80 as many gopherholes and gemini capsules have it hardcoded
- Streaming URL without valid content-length are now closed after 5Mo of download (thanks to Eoin Carney for reporting the issue)
- Gif animations are now displayed once when viewed (instead of a still frame).
- Restored some AV-98 certificate validation code that was lost I don’t know how.
- Improved clarity of dependencies in "version"
- Fixed a crash when the cache is already a dir inside a dir.
- Fixed a crash when manually entering an unknown gopher URL while offline
- Fixed an error with older less version
- Fixed bookmarks not being automatically created at first "add"
- Call to shell commands has been refactorised to improve compatibility with python 3.6 (with testing from Pelle Nilsson)
- requirements.txt has been contributed by Toby Kurien. Thanks!
=> gemini://rawtext.club/~ploum/2022-04-02-offpunk13.gmi
## 1.2 - March 24th 2022
Very experimental release:
- Completely rewritten the HMTL, Gemtext and Gopher renderer. Tests needed!
- Removed dependancy to ansiwrap. We don’t use it anymore (which is an important achievement)
- Lists are now accessed via the protocol "list://".
- "view full" can now be bookmarked/synchronized as a separate entity.
- "view normal" introduced to get back to the normal view.
Small improvements:
- Limit width of --sync output
- Solved list names becoming very long in the history
- Fixed a crash when trying to save a folder
=> gemini://rawtext.club/~ploum/2022-03-24-ansi_html.gmi
## 1.1 - March 18th 2022
- Perfect rendering of pictures with chafa 1.8+ and compatible terminal (Kitty)
- timg is supported as an alternative to chafa (with a little glitch)
- "cp cache" put the path of the cached content in clipboard
- "cp url X" will copy the URL of link X (suggested by Eoin Carney)
- "fold" has been removed as it doesn’t work well and can be replaced with "!fold".
- Improved clipboard URL detection an fixed crash when binary in clipboard
- HTML: renderering of has been improved
- HTML: links in titles were previously missed
- Fixed crash when chafa is not installed (Thanks Xavier Hinault for the report)
- Fixed crash when python-readability not installed (Thanks Nic for the report)
- Fixed some gif not being displayed
- Fixed some URL being wronlgy interpreted as IPv6
## 1.0 - March 14th 2022
- Default width is now the standard 72
- Content and pictures now centered for more elegant reading
- "less" has been renamed "view"
- "view feed" and "view feeds" to see the first/all feeds on a HTML page
- "view full" has been improved by dropping inline CSS and JS.
- "up" can now take integer as argument to go up multiple steps.
- Fixed a crash when accessing links in list (thanks Matthieu Talbot for the report)
- Fixed a crash in "info" due to a typo in a variable name rarely accessed.
- Removed dependancy to python-xdg by implementing the logic (which saved lines of code!)
- python-pil is only needed if chafa < 1.10
=> gemini://rawtext.club/~ploum/2022-03-14-offpunk_and_cyberpunk.gmi
## 0.9 - March 05th 2022
- Initial Spartan protocol support
- Http links with content above 20Mo are not downloaded during sync (except when explicitely requested)
- Improving subscriptions with more feedback and better detection
- Avoid deprecated SSL methods (thanks Phoebos for the report)
- Links in to_fetch are fetched, no matter the cache
- Fixed multiple crashes
=> gemini://rawtext.club/~ploum/2022-03-05-offpunk09.gmi
## 0.4 - Feb 21st 2022
UPGRADE: Users who subscribed to pages before 0.4 should run once the command "list subscribe subscribed". Without that, the subscribed list will be seen as a normal list by sync.
- New list command : "list freeze" and "list suscribe"
- Pictures are now displayed directely in terminal (suggested by kelbot)
- "open" command to open current page/image/file with external handler.
- "set width XX" now works to set the max width. If smaller, terminal width is used (thanks kelbot for reporting the bug)
- RSS feeds are now rendered as Gemlogs to improve consistency while browsing
- "subscribe" will detect feeds in html pages if any
- "less" will restore previous position in a page (requires less 572+)
- Improved syncing performances and multiple bug/crash fixes.
- "version" will now display info about your system installation
- "info" command will display technical information about current page
- "sync" allows you to do the sync from within Offpunk
=> gemini://rawtext.club/~ploum/2022-02-21-offpunk04.gmi
## 0.3 - Feb 11th 2022
New Features:
- Gopher supported natively (early version, might have many bugs)
- support for RSS and Atom feed (you can subscribe to them)
- "less full" allows to see the full html page instead of only the article view
(also works with feeds to see descriptions of each post instead of a simple list)
- Option --depth to customize your sync. Be warned, more than 1 is crazy.
- Option --disable-http to allows deep syncing of gemini-only ressources
- Vastly improved HTML rendering with support for images (you need the binary "chafa" on your system)
Other Small Improvements:
- Disabled https_everywhere by default (caching problems and some websites not supporting it)
- Modified --sync logic to make it more intuitive (thanks Bjorn Westergard)
- Caching more problems to avoid refetch
- Offpunk has now an User-Agent when http browsing to avoid being blocked as a bot
- Changed XDG logic to improve compatibility (thanks Klaus Alexander)
=> gemini://rawtext.club/~ploum/2022-02-11-offpunk03.gmi
## 0.2 - Jan 31st 2022
- config directories have been moved to follow the XDG specifications
- support for http, https and mailto links (https_everywhere is enabled by default, see "set" command)
- support for HTML pages, rendered as articles
- Mutiple bookmarks lists and management of them through commands list, add, archive, move
- Subscriptions have been moved to a separate list with the subscribe command
- History is persistent and saved to disk
- Copy command allows to copy content or url into buffer
- Search as been renamed find, in the hope of implementing a real search in the future
- --fetch-later allows to mark a content to be fetched from other software.
- --assume-yes allows to choose the default answer to certificates warnings during --sync.
=> gemini://rawtext.club/~ploum/2022-01-31-offpunk02.gmi Announcing Offpunk 0.2
## 0.1 - Jan 3rd 2022
- initial release as an independant software from AV-98 (thanks solderpunk)
- Including contributions published by Bjorn on Notabug (thanks ew0k)
- less used by default for all content with custom options
- online/offline mode
- content is cached for offline use
- bookmarks are cached and subscribed through the --sync option
- tour is persistent and saved to disk
- reload while offline mark the content to be fetched during next --sync
=> gemini://rawtext.club/~ploum/2022-01-03-offpunk.gmi Announce of Offpunk 0.1
offpunk-v2.7.1/CONTRIBUTORS 0000664 0000000 0000000 00000001063 14775435273 0015260 0 ustar 00root root 0000000 0000000 Offpunk Offline Gemini client
And the Offpunk tools suite: netcache, ansicat, opnk.
(C) From 2021: Ploum
Derived from AV-98 and Agena by Solderpunk,
(C) 2019, 2020: Solderpunk
AV-98 received contributions from:
- danceka
-
-
- Klaus Alexander Seistrup
- govynnus
- Björn Wärmedal
-
Offpunk received contributions from:
- Maeve Sproule
offpunk-v2.7.1/LICENSE 0000664 0000000 0000000 00000103464 14775435273 0014415 0 ustar 00root root 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2022, Ploum and contributors.
All rights reserved.
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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
.
offpunk-v2.7.1/README.md 0000664 0000000 0000000 00000020253 14775435273 0014661 0 ustar 00root root 0000000 0000000 # OFFPUNK
A command-line and offline-first smolnet browser/feed reader for Gemini, Gopher, Spartan and Web by [Ploum](https://ploum.net).
The goal of Offpunk is to be able to synchronise your content once (a day, a week, a month) and then browse/organise it while staying disconnected.
Official page : [Offpunk.net](https://offpunk.net)
Development (repository/mailing lists) : [sr.ht](https://sr.ht/~lioploum/offpunk/)


Offpunk is a fork of the original [AV-98](https://tildegit.org/solderpunk/AV-98) by Solderpunk and was originally called AV-98-offline as an experimental branch.
## 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. You can also a packaged version:
- [List of existing Offpunk packages (Repology)](https://repology.org/project/offpunk/versions)
- Please contribute packages for other systems, there’s a [mailing-list dedicated to packaging](https://lists.sr.ht/~lioploum/offpunk-packagers).
To get started, launch offpunk then type "tutorial".
You can also consults it online: [Offpunk tutorial](https://offpunk.net/firststeps.html)
At any point, you can use "help" to get the list of commands and "help command" to get a small help about "command".
## More
Important news and releases will be announced on the [offpunk-devel mailing list](https://lists.sr.ht/~lioploum/offpunk-devel)
Questions can be asked on [the users mailing](list https://lists.sr.ht/~lioploum/offpunk-users)
## Dependencies
Offpunk has few "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.
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.
- PIP: [requirements file to install dependencies with pip](requirements.txt)
- Ubuntu/Debian: [command to install dependencies on Ubuntu/Debian without pip](ubuntu_dependencies.txt)
Run command `version` in offpunk to see if you are missing some dependencies.
Mandatory or highly recommended (packagers should probably make those mandatory):
- [less](http://www.greenwoodsoftware.com/less/): mandatory but is probably already on your system
- [file](https://www.darwinsys.com/file/) is used to get the MIME type of cached objects. Should already be on your system.
- [xdg-utils](https://www.freedesktop.org/wiki/Software/xdg-utils/) provides xdg-open which is highly recommended to open files without a renderer or a handler. It is also used for mailto: command.
- The [cryptography library](https://pypi.org/project/cryptography/) will provide a better and slightly more secure experience when using the default TOFU certificate validation mode and is recommended (apt-get install python3-cryptography).
Dependencies to enable web browsing (packagers may put those in an offpunk-web meta-package but it is recommended to have it for a better offpunk experience)
- [Python-requests](http://python-requests.org) is needed to handle http/https requests natively (apt-get install python3-requests). Without it, http links will be opened in an external browser
- [BeautifulSoup4](https://www.crummy.com/software/BeautifulSoup) is needed to render HTML. Without it, HTML will not be rendered or be sent to an external parser like Lynx. (apt-get install python3-bs4)
- [Readability](https://github.com/buriy/python-readability) is highly suggested to trim useless part of most html pages (apt-get install 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)
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). Xclip can be used too.
- [Wl-clipboard](https://github.com/bugaevc/wl-clipboard) allows the same feature than xsel but under Wayland
- [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.
## Features
- Browse https/gemini/gopher without leaving your keyboard and without distractions
- Customize your experience with the `theme` command.
- 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`.
- RSS/Atom feeds are automatically discovered by `subscribe` and rendered as gemlogs. They can be explored with `view feed` and `view feeds`.
- Support "subscriptions" to a page. New content seen in subscribed pages are automatically added to your next tour.
- Complex bookmarks management through multiple lists, built-in edition, subscribing/freezing lists and archiving content.
- Advanced navigation tools like `tour` and `mark` (as per VF-1). Unlike AV-98, tour is saved on disk accross sessions.
- 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`.
## 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
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.
The RC file should be called `offpunkrc` and goes in $XDG_CONFIG_DIR/offpunk (or .config/offpunk or .offpunk if xdg not available). In that file, simply write one command per line, just like you would type them in offpunk.
## Cache design
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.
There’s 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.
## Tests
Be sure to install the dev requirements (`pytest` and `pytest-mock`) with:
pip install -r requirements-dev.txt
And then run the test suite using `pytest`.
offpunk-v2.7.1/TODO 0000664 0000000 0000000 00000002446 14775435273 0014076 0 ustar 00root root 0000000 0000000 TODO
# Godo first contributions
## Cache Triming (Good first-contribution - medium level)
We need work on a model that keep the cache within certain limit by removing older, inaccessed elements which are not linked to anything in lists.
This is a good first-contribution issue as the cache-triming script should be completely independant and interact little with existing code.
## HTML rendering (Good first-contribution - advanced level)
Better rendering of tables using ASCII tables.
This is a good first-contribution for someone interested in HTML parsing/rendering and ready to dig into ansicat. While quite complex, the issue will have little or no interaction with code outside of the HTML rendering engine of Ansicat.
## UTF-8 in URL:
bug #42: IDN handling
https://todo.sr.ht/~lioploum/offpunk/42
# Heavy refactoring
## Refactoring of redirections is needed
bug #34: redirections are not kept while offline
https://todo.sr.ht/~lioploum/offpunk/34
bug #41: Redirects should be handled in netcache, not offpunk
https://todo.sr.ht/~lioploum/offpunk/41
## Refactoring of errors is needed
bug #30: Netcache: gemini status 4 and 5 should not emit a full traceback
https://todo.sr.ht/~lioploum/offpunk/30
bug #3: Error pages are stored in the cache
https://todo.sr.ht/~lioploum/offpunk/3
offpunk-v2.7.1/ansicat.py 0000775 0000000 0000000 00000204165 14775435273 0015407 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import argparse
import base64
import fnmatch
import html
import mimetypes
import os
import shutil
import subprocess
import sys
import textwrap
import time
import urllib
import netcache
import offthemes
from offutils import is_local, looks_like_base64, looks_like_url, run, term_width, xdg
try:
from readability import Document
_HAS_READABILITY = True
except ModuleNotFoundError:
_HAS_READABILITY = False
try:
# if bs4 version >= 4.11, we need to silent some xml warnings
import bs4
from bs4 import BeautifulSoup, Comment
version = bs4.__version__.split(".")
recent = False
if int(version[0]) > 4:
recent = True
elif int(version[0]) == 4:
recent = int(version[1]) >= 11
if recent:
# As this is only for silencing some warnings, we fail
# silently. We don’t really care
try:
import warnings
from bs4 import XMLParsedAsHTMLWarning
warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
except Exception:
pass
_HAS_SOUP = True
except ModuleNotFoundError:
_HAS_SOUP = False
_DO_HTML = _HAS_SOUP # and _HAS_READABILITY
if _DO_HTML and not _HAS_READABILITY:
print("To improve your web experience (less cruft in webpages),")
print("please install python3-readability or readability-lxml")
try:
import feedparser
_DO_FEED = True
except ModuleNotFoundError:
_DO_FEED = False
_HAS_TIMG = False
_HAS_CHAFA = False
_RENDER_IMAGE = False
# All this code to know if we render image inline or not
#Do we have chafa >= 1.10 ?
if shutil.which("chafa"):
# starting with 1.10, chafa can return only one frame
# we thus requires chafa to be at least 1.10
# output is "Chafa version M.m.p"
# check for m < 1.10
try:
output = run("chafa --version")
chafa_major, chafa_minor, _ = output.split("\n")[0].split(" ")[-1].split(".")
if int(chafa_major) >= 1 and int(chafa_minor) >= 10:
_HAS_CHAFA = True
_RENDER_IMAGE = True
except Exception:
pass
#Do we have timg?
if shutil.which("timg"):
try:
output = run("timg --version")
except subprocess.CalledProcessError:
output = False
# We don’t deal with timg before 1.3.2 (looping options)
if output and output[5:10] > "1.3.2":
_HAS_TIMG = True
_RENDER_IMAGE = True
if not _RENDER_IMAGE:
print("To render images inline, you need either chafa >= 1.10 or timg > 1.3.2")
# return ANSI text that can be show by less
def inline_image(img_file, width):
# We don’t even try displaying pictures that are not there
if not os.path.exists(img_file):
return ""
# Chafa is faster than timg inline. Let use that one by default
# But we keep a list of "inlines" (possible commands to use)
# just in case chafa fails
inlines = []
ansi_img = ""
# We avoid errors by not trying to render non-image files
if shutil.which("file"):
mime = run("file -b --mime-type %s", parameter=img_file).strip()
if "image" not in mime:
return ansi_img
if _HAS_CHAFA:
inlines.append("chafa --bg white -t 1 -s %s -f symbols --animate=off")
if _HAS_TIMG:
inlines.append("timg --frames=1 -p q -g %sx1000")
image_success = False
while not image_success and len(inlines) > 0:
cmd = inlines.pop(0) % width + " %s"
try:
ansi_img = run(cmd, parameter=img_file)
image_success = True
except Exception as err:
ansi_img = "***IMAGE ERROR***\n%s…\n…%s" % (str(err)[:50], str(err)[-50:])
return ansi_img
def terminal_image(img_file):
# This code will try chafa first and, if it fails, try timg
cmds = []
if _HAS_CHAFA:
cmds.append("chafa -C on -d 0 --bg white -w 1")
if _HAS_TIMG:
cmds.append("timg --loops=1 -C")
image_success = False
while not image_success and len(cmds) > 0:
cmd = cmds.pop(0) + " %s"
try:
run(cmd, parameter=img_file, direct_output=True)
image_success = True
except Exception as err:
print(err)
# First, we define the different content->text renderers, outside of the rest
# (They could later be factorized in other files or replaced)
class AbstractRenderer:
def __init__(self, content, url, center=True,**kwargs):
self.url = url
self.body = str(content)
# there’s one rendered text and one links table per mode
self.rendered_text = {}
self.links = {}
self.images = {}
self.title = None
self.validity = True
self.temp_files = {}
self.center = center
self.last_mode = "readable"
self.theme = offthemes.default
self.options = kwargs
# self.mime should be used only in renderer with multiple mime
self.mime = None
def display(self, mode=None, directdisplay=False):
wtitle = self.get_formatted_title()
if mode == "source":
body = self.body
else:
body = wtitle + "\n" + self.get_body(mode=mode)
if directdisplay:
print(body)
return True
else:
return body
#Return True if it should bypass less and access directly the terminal
def has_direct_display(self):
return False
#Return True if it is able to render the content.
#Return False if the content is of a format not supported by ansicat
def is_format_supported(self):
return True
def set_theme(self, theme):
if theme:
self.theme.update(theme)
def get_theme(self):
return self.theme
# This class hold an internal representation of the HTML text
class representation:
def __init__(self, width, title=None, center=True, theme={},options={}):
self.title = title
self.center = center
self.final_text = ""
self.opened = []
self.width = width
self.last_line = ""
self.last_line_colors = {}
self.last_line_center = False
self.new_paragraph = True
self.i_indent = ""
self.s_indent = ""
self.r_indent = ""
self.current_indent = ""
self.disabled_indents = None
# each color is an [open,close] pair code
self.theme = theme
self.options = options
self.colors = offthemes.colors
def _insert(self, color, open=True):
if open:
o = 0
else:
o = 1
pos = len(self.last_line)
# we remember the position where to insert color codes
if pos not in self.last_line_colors:
self.last_line_colors[pos] = []
# Two inverse code cancel each other
if [color, int(not o)] in self.last_line_colors[pos]:
self.last_line_colors[pos].remove([color, int(not o)])
else:
self.last_line_colors[pos].append([color, o]) # +color+str(o))
# Take self.last line and add ANSI codes to it before adding it to
# self.final_text.
def _endline(self):
if len(self.last_line.strip()) > 0:
for c in self.opened:
self._insert(c, open=False)
nextline = ""
added_char = 0
# we insert the color code at the saved positions
while len(self.last_line_colors) > 0:
pos, colors = self.last_line_colors.popitem()
# popitem itterates LIFO.
# So we go, backward, to the pos (starting at the end of last_line)
nextline = self.last_line[pos:] + nextline
ansicol = "\x1b["
for c, o in colors:
ansicol += self.colors[c][o] + ";"
ansicol = ansicol[:-1] + "m"
nextline = ansicol + nextline
added_char += len(ansicol)
self.last_line = self.last_line[:pos]
nextline = self.last_line + nextline
if self.last_line_center:
# we have to care about the ansi char while centering
width = term_width() + added_char
nextline = nextline.strip().center(width)
self.last_line_center = False
else:
# should we lstrip the nextline in the addition ?
# nextline.lstrip() is breaking AsciiArt and I don’t remember
# why it is there. Trying to replace it with a "rstrip"
nextline = self.current_indent + nextline.rstrip() + self.r_indent
self.current_indent = self.s_indent
self.final_text += nextline
self.last_line = ""
self.final_text += "\n"
for c in self.opened:
self._insert(c, open=True)
else:
self.last_line = ""
def center_line(self):
self.last_line_center = True
def open_theme(self, element):
if element in self.theme:
colors = self.theme[element]
for c in colors:
self.open_color(c)
return True
else:
return False
def close_theme(self, element):
if element in self.theme:
colors = self.theme[element]
for c in colors:
self.close_color(c)
def open_color(self, color):
if color in self.colors and color not in self.opened:
self._insert(color, open=True)
self.opened.append(color)
def close_color(self, color):
if color in self.colors and color in self.opened:
self._insert(color, open=False)
self.opened.remove(color)
def close_all(self):
if len(self.colors) > 0:
self.last_line += "\x1b[0m"
self.opened.clear()
def startindent(self, indent, sub=None, reverse=None):
self._endline()
self.i_indent = indent
self.current_indent = indent
if sub:
self.s_indent = sub
else:
self.s_indent = indent
if reverse:
self.r_indent = reverse
else:
self.r_indent = ""
def endindent(self):
self._endline()
self.i_indent = ""
self.s_indent = ""
self.r_indent = ""
self.current_indent = ""
def _disable_indents(self):
self.disabled_indents = []
self.disabled_indents.append(self.current_indent)
self.disabled_indents.append(self.i_indent)
self.disabled_indents.append(self.s_indent)
self.disabled_indents.append(self.r_indent)
self.endindent()
def _enable_indents(self):
if self.disabled_indents:
self.current_indent = self.disabled_indents[0]
self.i_indent = self.disabled_indents[1]
self.s_indent = self.disabled_indents[2]
self.r_indent = self.disabled_indents[3]
self.disabled_indents = None
def newline(self):
self._endline()
# A new paragraph implies 2 newlines (1 blank line between paragraphs)
# But it is only used if didn’t already started one to avoid plenty
# of blank lines. force=True allows to bypass that limit.
# new_paragraph becomes false as soon as text is entered into it
def newparagraph(self, force=False):
if force or not self.new_paragraph:
self._endline()
self.final_text += "\n"
self.new_paragraph = True
def add_space(self):
if len(self.last_line) > 0 and self.last_line[-1] != " ":
self.last_line += " "
def _title_first(self, intext=None):
if self.title:
if not self.title == intext:
self._disable_indents()
self.open_theme("title")
self.add_text(self.title)
self.close_all()
self.newparagraph()
self._enable_indents()
self.title = None
# Beware, blocks are not wrapped nor indented and left untouched!
# They are mostly useful for pictures and preformatted text.
def add_block(self, intext, theme=None):
# If necessary, we add the title before a block
self._title_first()
# we don’t want to indent blocks
self._endline()
self._disable_indents()
# we have to apply the theme for every line in the intext
# applying theme to preformatted is controversial as it could change it
if "preformat_wrap" in self.options:
preformat_wrap = self.options["preformat_wrap"]
else:
preformat_wrap = False
if theme:
block = ""
lines = intext.split("\n")
for l in lines:
self.open_theme(theme)
if preformat_wrap:
self.add_text(l)
else:
self.last_line += self.current_indent + l
self.close_theme(theme)
self._endline()
self.last_line += "\n"
# one thing is sure : we need to keep unthemed blocks for images!
else:
self.final_text += self.current_indent + intext
self.new_paragraph = False
self._endline()
self._enable_indents()
def add_text(self, intext):
self._title_first(intext=intext)
lines = []
last = self.last_line + intext
self.last_line = ""
# With the following, we basically cancel adding only spaces
# on an empty line
if len(last.strip()) > 0:
self.new_paragraph = False
else:
last = last.strip()
if len(last) > self.width:
width = self.width - len(self.current_indent) - len(self.r_indent)
spaces_left = len(last) - len(last.lstrip())
spaces_right = len(last) - len(last.rstrip())
lines = textwrap.wrap(last, width, drop_whitespace=True)
self.last_line += spaces_left * " "
while len(lines) > 1:
l = lines.pop(0)
self.last_line += l
self._endline()
if len(lines) == 1:
li = lines[0]
self.last_line += li + spaces_right * " "
else:
self.last_line = last
def get_final(self):
self.close_all()
self._endline()
# if no content, we still add the title
self._title_first()
lines = self.final_text.splitlines()
lines2 = []
termspace = shutil.get_terminal_size()[0]
# Following code instert blanck spaces to center the content
if self.center and termspace > term_width():
margin = int((termspace - term_width()) // 2)
else:
margin = 0
for l in lines:
lines2.append(margin * " " + l)
return "\n".join(lines2)
def get_subscribe_links(self):
return [[self.url, self.get_mime(), self.get_title()]]
def is_valid(self):
return self.validity
def set_mode(self, mode):
self.last_mode = mode
def get_mode(self):
return self.last_mode
def get_link(self, nb):
links = self.get_links()
if len(links) < nb:
print("Index too high! No link %s for %s" % (nb, self.url))
return None
else:
return links[nb - 1]
# get_title is about the "content title", so the title in the page itself
def get_title(self):
return "Abstract title"
def get_page_title(self):
title = self.get_title()
if not title or len(title) == 0:
title = self.get_url_title()
else:
title += " (%s)" % self.get_url_title()
return title
def get_formatted_title(self):
title = self.get_url_title()
nbr = len(self.get_links())
if is_local(self.url):
title += " (%s items)" % nbr
str_last = "local file"
else:
str_last = "last accessed on %s" % time.ctime(
netcache.cache_last_modified(self.url)
)
title += " (%s links)" % nbr
return self._window_title(title, info=str_last)
# this function is about creating a title derived from the URL
def get_url_title(self):
# small intelligence to try to find a good name for a capsule
# we try to find eithe ~username or /users/username
# else we fallback to hostname
if not self.url:
return ""
if is_local(self.url):
splitpath = self.url.split("/")
filename = splitpath[-1]
return filename
path = self.url
parsed = urllib.parse.urlparse(self.url)
red_title = parsed.hostname
if "user" in path:
i = 0
splitted = path.split("/")
while i < (len(splitted) - 1):
if splitted[i].startswith("user"):
red_title = splitted[i + 1]
i += 1
if "~" in path:
for pp in path.split("/"):
if pp.startswith("~"):
red_title = pp[1:]
return red_title
# This function return a list of URL which should be downloaded
# before displaying the page (images in HTML pages, typically)
def get_images(self, mode=None):
if not mode:
mode = self.last_mode
if mode not in self.images:
self.get_body(mode=mode)
# we also invalidate the body that was done without images
self.rendered_text.pop(mode)
if mode in self.images:
return self.images[mode]
else:
return []
# This function will give gemtext to the gemtext renderer
def prepare(self, body, mode=None):
return [[body, None]]
def _build_body_and_links(self, mode, width=None):
if not width:
width = term_width()
prepared_bodies = self.prepare(self.body, mode=mode)
self.rendered_text[mode] = ""
self.links[mode] = []
for b in prepared_bodies:
results = None
size = len(self.links[mode])
if b[1] in _FORMAT_RENDERERS:
r = _FORMAT_RENDERERS[b[1]](b[0], self.url, center=self.center)
results = r.render(b[0], width=width, mode=mode, startlinks=size)
else:
results = self.render(b[0], width=width, mode=mode, startlinks=size)
if results:
self.rendered_text[mode] += results[0] + "\n"
# we should absolutize all URLs here
for l in results[1]:
ll = l.split()[0]
try:
abs_l = urllib.parse.urljoin(self.url, ll)
self.links[mode].append(abs_l)
except Exception:
print(
"Urljoin Error: Could not make an URL out of %s and %s"
% (self.url, ll)
)
for l in self.get_subscribe_links()[1:]:
self.links[mode].append(l[0])
def get_body(self, width=None, mode=None):
if not mode:
mode = self.last_mode
if mode not in self.rendered_text:
self._build_body_and_links(mode, width)
return self.rendered_text[mode]
def get_links(self, mode=None):
if not mode:
mode = self.last_mode
if mode not in self.links:
self._build_body_and_links(mode)
return self.links[mode]
def _window_title(self, title, info=None):
title_r = self.representation(term_width(), theme=self.theme,options=self.options)
title_r.open_theme("window_title")
title_r.add_text(title)
title_r.close_theme("window_title")
if info:
title_r.open_theme("window_subtitle")
title_r.add_text(" (%s)" % info)
title_r.close_theme("window_subtitle")
return title_r.get_final()
# An instance of AbstractRenderer should have a
# self.render(body,width=,mode=,starlinks=0) method.
# It returns a tuple (rendered_body,[list of links])
# 3 modes are used : readable (by default), full and links_only (the fastest, when
# rendered content is not used, only the links are needed)
# The prepare() function is called before the rendering. It is useful if
# your renderer output in a format suitable for another existing renderer (such as gemtext)
# The prepare() function output a list of tuple. Each tuple is [output text, format] where
# format should be in _FORMAT_RENDERERS. If None, current renderer is used
# A renderer for format that are not supported
class FakeRenderer(AbstractRenderer):
def set_mime(self,mime):
self.mime = mime
def get_mime(self):
return self.mime
def get_title(self):
filename = self.url.split("/")[-1]
if not filename:
filename = self.url
return filename
def is_format_supported(self):
return False
def render(self,body,width=None,**kwargs):
gemtext = "\n"
gemtext += "File %s is of format %s.\n"%(self.get_title(),self.mime)
gemtext += "It cannot be rendered in your terminal.\n"
gemtext += "Use \"open\" to open the file using an external handler"
r = self.representation(width, theme=self.theme,options=self.options)
for line in gemtext.splitlines():
r.newline()
if len(line.strip()) == 0:
r.newparagraph(force=True)
else:
r.add_text(line.rstrip())
return r.get_final(), []
class PlaintextRenderer(AbstractRenderer):
def get_mime(self):
return "text/plain"
def get_title(self):
if self.title:
return self.title
elif self.body:
lines = self.body.splitlines()
if len(lines) > 0:
# If not title found, we take the first 50 char
# of the first line
title_line = lines[0].strip()
if len(title_line) > 50:
title_line = title_line[:49] + "…"
self.title = title_line
return self.title
else:
self.title = "Empty Page"
return self.title
else:
return "(unknown)"
def render(self, gemtext, width=None, mode=None, startlinks=0):
r = self.representation(width, theme=self.theme,options=self.options)
links = []
for line in gemtext.splitlines():
r.newline()
if len(line.strip()) == 0:
r.newparagraph(force=True)
else:
if "://" in line:
words = line.split()
for w in words:
if "://" in w and looks_like_url(w):
links.append(w)
r.add_text(line)
return r.get_final(), links
# Gemtext Rendering Engine
class GemtextRenderer(AbstractRenderer):
def get_mime(self):
return "text/gemini"
def get_title(self):
if self.title:
return self.title
elif self.body:
lines = self.body.splitlines()
for line in lines:
if line.startswith("#"):
self.title = line.strip("#").strip()
return self.title
if len(lines) > 0:
# If not title found, we take the first 50 char
# of the first line
title_line = lines[0].strip()
if len(title_line) > 50:
title_line = title_line[:49] + "…"
self.title = title_line
return self.title
else:
self.title = "Empty Page"
return self.title
else:
return "(unknown)"
# render_gemtext
def render(self, gemtext, width=None, mode=None, startlinks=0):
if not width:
width = term_width()
r = self.representation(width, theme=self.theme,options=self.options)
links = []
hidden_links = []
preformatted = False
def format_link(url, index, name=None):
if "://" in url:
protocol, adress = url.split("://", maxsplit=1)
protocol = " %s" % protocol
else:
adress = url
protocol = ""
if "gemini" in protocol or "list" in protocol:
protocol = ""
if not name:
name = adress
line = "[%d%s] %s" % (index, protocol, name)
return line
for line in gemtext.splitlines():
r.newline()
if line.startswith("```"):
preformatted = not preformatted
if preformatted:
r.open_theme("preformatted")
else:
r.close_theme("preformatted")
elif preformatted:
# infinite line to not wrap preformated
r.add_block(line + "\n", theme="preformatted")
elif len(line.strip()) == 0:
r.newparagraph(force=True)
elif line.startswith("=>"):
strippedline = line[2:].strip()
if strippedline:
links.append(strippedline)
splitted = strippedline.split(maxsplit=1)
url = splitted[0]
name = None
if len(splitted) > 1:
name = splitted[1]
link = format_link(url, len(links) + startlinks, name=name)
# If the link point to a page that has been cached less than
# 600 seconds after this page, we consider it as a new_link
current_modif = netcache.cache_last_modified(self.url)
link_modif = netcache.cache_last_modified(url)
if (
current_modif
and link_modif
and current_modif - link_modif < 600
and r.open_theme("new_link")
):
theme = "new_link"
elif r.open_theme("oneline_link"):
theme = "oneline_link"
else:
theme = "link"
r.open_theme("link")
startpos = link.find("] ") + 2
r.startindent("", sub=startpos * " ")
r.add_text(link)
r.close_theme(theme)
r.endindent()
elif line.startswith("* "):
line = line[1:].lstrip("\t ")
r.startindent("• ", sub=" ")
r.add_text(line)
r.endindent()
elif line.startswith(">"):
line = line[1:].lstrip("\t ")
r.startindent("> ")
r.open_theme("blockquote")
r.add_text(line)
r.close_theme("blockquote")
r.endindent()
elif line.startswith("###"):
line = line[3:].lstrip("\t ")
if r.open_theme("subsubtitle"):
theme = "subsubtitle"
else:
r.open_theme("subtitle")
theme = "subtitle"
r.add_text(line)
r.close_theme(theme)
elif line.startswith("##"):
line = line[2:].lstrip("\t ")
r.open_theme("subtitle")
r.add_text(line)
r.close_theme("subtitle")
elif line.startswith("#"):
line = line[1:].lstrip("\t ")
if not self.title:
self.title = line
r.open_theme("title")
r.add_text(line)
r.close_theme("title")
else:
if "://" in line:
words = line.split()
for w in words:
if "://" in w and looks_like_url(w):
hidden_links.append(w)
r.add_text(line.rstrip())
links += hidden_links
return r.get_final(), links
class EmptyRenderer(GemtextRenderer):
def get_mime(self):
return "text/empty"
def prepare(self, body, mode=None):
text = "(empty file)"
return [[text, "GemtextRenderer"]]
class GopherRenderer(AbstractRenderer):
def get_mime(self):
return "text/gopher"
def get_title(self):
if not self.title:
self.title = ""
if self.body:
firstline = self.body.splitlines()[0]
firstline = firstline.split("\t")[0]
if firstline.startswith("i"):
firstline = firstline[1:]
self.title = firstline
return self.title
# menu_or_text
def render(self, body, width=None, mode=None, startlinks=0):
if not width:
width = term_width()
try:
render, links = self._render_goph(
body, width=width, mode=mode, startlinks=startlinks
)
except Exception as err:
print("Error rendering Gopher ", err)
r = self.representation(width, theme=self.theme,options=self.options)
r.add_block(body)
render = r.get_final()
links = []
return render, links
def _render_goph(self, body, width=None, mode=None, startlinks=0):
if not width:
width = term_width()
# This was copied straight from Agena (then later adapted)
links = []
r = self.representation(width, theme=self.theme,options=self.options)
for line in self.body.split("\n"):
r.newline()
if line.startswith("i"):
towrap = line[1:].split("\t")[0]
if len(towrap.strip()) > 0:
r.add_block(towrap+"\n")
else:
r.newparagraph()
elif line.strip() not in [".", ""]:
parts = line.split("\t")
parts[-1] = parts[-1].strip()
if parts[-1] == "+":
parts = parts[:-1]
if len(parts) == 4:
name, path, host, port = parts
# If line starts with TAB, there’s no name.
# We thus hide this line
if name:
itemtype = name[0]
name = name[1:]
if port == "70":
port = ""
else:
port = ":%s" % port
if itemtype == "h" and path.startswith("URL:"):
url = path[4:]
else:
url = "gopher://%s%s/%s%s" % (host, port, itemtype, path)
url = url.replace(" ", "%20")
linkline = url + " " + name
links.append(linkline)
number = len(links) + startlinks
towrap = "[%s] " % str(number) + name
r.add_text(towrap)
else:
r.add_text(line)
return r.get_final(), links
class FolderRenderer(GemtextRenderer):
# it was initialized with:
# self.renderer = FolderRenderer("",self.get_cache_path(),datadir=xdg("data"))
def __init__(self, content, url, center=True, datadir=None):
GemtextRenderer.__init__(self, content, url, center)
self.datadir = datadir
def get_mime(self):
return "Directory"
def prepare(self, body, mode=None):
def get_first_line(l):
path = os.path.join(listdir, l + ".gmi")
with open(path) as f:
first_line = f.readline().strip()
f.close()
if first_line.startswith("#"):
return first_line
else:
return None
def write_list(l):
body = ""
for li in l:
#making sure we don’t write ".gmi"
if l != "":
path = "list:///%s" % li
r = renderer_from_file(netcache.get_cache_path(path))
size = len(r.get_links())
body += "=> %s %s (%s items)\n" % (str(path), li, size)
return body
listdir = os.path.join(self.datadir, "lists")
self.title = "My lists"
lists = []
if os.path.exists(listdir):
listfiles = os.listdir(listdir)
if len(listfiles) > 0:
for l in listfiles:
# removing the .gmi at the end of the name
lists.append(l[:-4])
if len(lists) > 0:
body = ""
my_lists = []
system_lists = []
subscriptions = []
frozen = []
lists.sort()
for l in lists:
# we don’t do anything with home which is ".gmi" thus ""
if l in ["history", "to_fetch", "archives", "tour"]:
system_lists.append(l)
elif l != "":
first_line = get_first_line(l)
if first_line and "#subscribed" in first_line:
subscriptions.append(l)
elif first_line and "#frozen" in first_line:
frozen.append(l)
else:
my_lists.append(l)
if len(my_lists) > 0:
body += "\n## Bookmarks Lists (updated during sync)\n"
body += write_list(my_lists)
if len(subscriptions) > 0:
body += "\n## Subscriptions (new links in those are added to tour)\n"
body += write_list(subscriptions)
if len(frozen) > 0:
body += "\n## Frozen (fetched but never updated)\n"
body += write_list(frozen)
if len(system_lists) > 0:
body += "\n## System Lists\n"
body += write_list(system_lists)
return [[body, None]]
class FeedRenderer(GemtextRenderer):
def get_mime(self):
return "application/rss+xml"
def is_valid(self):
if _DO_FEED:
try:
parsed = feedparser.parse(self.body)
except Exception:
parsed = False
else:
return False
if not parsed:
return False
elif parsed.bozo:
return False
else:
# If no content, then fallback to HTML
return len(parsed.entries) > 0
def get_title(self):
if not self.title:
self.get_body()
return self.title
def prepare(self, content, mode=None, width=None):
if not mode:
mode = self.last_mode
if not width:
width = term_width()
self.title = "RSS/Atom feed"
toreturn = []
page = ""
if _DO_FEED:
parsed = feedparser.parse(content)
else:
page += "Please install python-feedparser to handle RSS/Atom feeds\n"
self.validity = False
return page
if parsed.bozo:
page += "Invalid RSS feed\n\n"
page += str(parsed.bozo_exception)
self.validity = False
else:
if "title" in parsed.feed:
t = parsed.feed.title
else:
t = "Unknown"
self.title = "%s (XML feed)" % t
title = "# %s" % self.title
page += title + "\n"
if "updated" in parsed.feed:
page += "Last updated on %s\n\n" % parsed.feed.updated
if "subtitle" in parsed.feed:
page += parsed.feed.subtitle + "\n"
if "link" in parsed.feed:
page += "=> %s\n" % parsed.feed.link
page += "\n## Entries\n"
toreturn.append([page, None])
if len(parsed.entries) < 1:
self.validity = False
postslist = ""
for i in parsed.entries:
if "link" in i:
line = "=> %s " % i.link
elif "links" in i and len(i.links) > 0:
link = None
j = 0
while not link and j < len(i.links):
link = i.links[j].href
if link:
line = "=> %s " % link
else:
line = "* "
else:
line = "* "
if "published" in i:
# sometimes fails so protect it
try:
pub_date = time.strftime("%Y-%m-%d", i.published_parsed)
line += pub_date + " : "
except Exception:
pass
if "title" in i:
line += "%s" % (i.title)
if "author" in i:
line += " (by %s)" % i.author
if mode == "full":
toreturn.append([line, None])
if "summary" in i:
toreturn.append([i.summary, "text/html"])
toreturn.append(["------------", None])
else:
postslist += line + "\n"
# If each posts is append to toreturn, a \n is inserted
# between each item of the list. I don’t like it. Hence this hack
if mode != "full":
toreturn.append([postslist, None])
return toreturn
class ImageRenderer(AbstractRenderer):
def get_mime(self):
return "image/*"
def is_valid(self):
if _RENDER_IMAGE:
return True
else:
return False
def get_links(self, mode=None):
return []
def get_title(self):
return "Picture file"
def render(self, img, width=None, mode=None, startlinks=0):
# with inline, we use symbols to be rendered with less.
# else we use the best possible renderer.
if mode in ["full_links_only", "links_only"]:
return "", []
if not width:
width = term_width()
spaces = 0
else:
spaces = int((term_width() - width) // 2)
ansi_img = inline_image(img, width)
# Now centering the image
lines = ansi_img.splitlines()
new_img = ""
for l in lines:
new_img += spaces * " " + l + "\n"
return new_img, []
def has_direct_display(self):
return _RENDER_IMAGE
def display(self, mode=None, directdisplay=False):
wtitle = self.get_formatted_title()
if not directdisplay:
body = wtitle + "\n" + self.get_body(mode=mode)
return body
else:
print(self._window_title(wtitle))
terminal_image(self.body)
return True
class HtmlRenderer(AbstractRenderer):
def get_mime(self):
return "text/html"
def is_valid(self):
if not _DO_HTML:
print(
"HTML document detected. Please install python-bs4 and python-readability."
)
return _DO_HTML and self.validity
def get_subscribe_links(self):
subs = [[self.url, self.get_mime(), self.get_title()]]
soup = BeautifulSoup(self.body, "html.parser")
links = soup.find_all("link", rel="alternate", recursive=True)
for l in links:
ty = l.get("type")
if ty:
if "rss" in ty or "atom" in ty or "feed" in ty:
# some rss links are relatives: we absolutise_url
sublink = urllib.parse.urljoin(self.url, l.get("href"))
subs.append([sublink, ty, l.get("title")])
return subs
def get_title(self):
if self.title:
return self.title
elif self.body:
if _HAS_READABILITY:
try:
readable = Document(self.body)
self.title = readable.short_title()
return self.title
except Exception:
pass
soup = BeautifulSoup(self.body, "html.parser")
if soup.title:
self.title = str(soup.title.string)
else:
self.title = ""
return self.title
else:
return ""
# Our own HTML engine (crazy, isn’t it?)
# Return [rendered_body, list_of_links]
# mode is either links_only, readable or full
def render(self, body, mode=None, width=None, add_title=True, startlinks=0):
if not mode:
mode = self.last_mode
if not width:
width = term_width()
if not _DO_HTML:
print(
"HTML document detected. Please install python-bs4 and python-readability."
)
return
# This method recursively parse the HTML
r = self.representation(
width, title=self.get_title(), center=self.center, theme=self.theme
,options=self.options)
links = []
# You know how bad html is when you realize that space sometimes meaningful, somtimes not.
# CR are not meaniningful. Except that, somethimes, they should be interpreted as spaces.
# HTML is real crap. At least the one people are generating.
def render_image(src, width=40, mode=None):
ansi_img = ""
imgurl, imgdata = looks_like_base64(src, self.url)
if (
_RENDER_IMAGE
and mode not in ["full_links_only", "links_only"]
and imgurl
):
try:
# 4 followings line are there to translate the URL into cache path
img = netcache.get_cache_path(imgurl)
if imgdata:
os.makedirs(os.path.dirname(img), exist_ok=True)
with open(img, "wb") as cached:
cached.write(base64.b64decode(imgdata))
cached.close()
if netcache.is_cache_valid(img):
renderer = ImageRenderer(img, imgurl)
# Image are 40px wide except if terminal is smaller
if width > 40:
size = 40
else:
size = width
ansi_img = "\n" + renderer.get_body(width=size, mode="inline")
except Exception as err:
# we sometimes encounter really bad formatted files or URL
ansi_img = (
textwrap.fill("[BAD IMG] %s - %s" % (err, src), width) + "\n"
)
return ansi_img
def sanitize_string(string):
# never start with a "\n"
# string = string.lstrip("\n")
string = string.replace("\r", "").replace("\n", " ").replace("\t", " ")
endspace = string.endswith(" ") or string.endswith("\xa0")
startspace = string.startswith(" ") or string.startswith("\xa0")
toreturn = string.replace("\n", " ").replace("\t", " ").strip()
while " " in toreturn:
toreturn = toreturn.replace(" ", " ")
toreturn = html.unescape(toreturn)
if (
endspace
and not toreturn.endswith(" ")
and not toreturn.endswith("\xa0")
):
toreturn += " "
if (
startspace
and not toreturn.startswith(" ")
and not toreturn.startswith("\xa0")
):
toreturn = " " + toreturn
return toreturn
def recursive_render(element, indent="", preformatted=False):
if element.name in ["blockquote", "dd"]:
r.newparagraph()
r.startindent(" ", reverse=" ")
for child in element.children:
r.open_theme("blockquote")
recursive_render(child, indent="\t")
r.close_theme("blockquote")
r.endindent()
elif element.name in ["div", "p", "dt"]:
r.newparagraph()
for child in element.children:
recursive_render(child, indent=indent)
r.newparagraph()
elif element.name in ["span"]:
r.add_space()
for child in element.children:
recursive_render(child, indent=indent)
r.add_space()
elif element.name in ["h1", "h2", "h3", "h4", "h5", "h6"]:
if element.name in ["h1"]:
r.open_theme("title")
elif element.name in ["h2", "h3"]:
r.open_theme("subtitle")
elif element.name in ["h4", "h5", "h6"]:
if not r.open_theme("subsubtitle"):
r.open_theme("subtitle")
r.newparagraph()
for child in element.children:
recursive_render(child)
# r.close_all()
r.close_all()
r.newparagraph()
elif element.name in ["code", "tt","pre"]:
for child in element.children:
recursive_render(child, indent=indent, preformatted=True)
elif element.name in ["li"]:
r.startindent(" • ", sub=" ")
for child in element.children:
recursive_render(child, indent=indent)
r.endindent()
elif element.name in ["tr"]:
r.startindent("|", reverse="|")
for child in element.children:
recursive_render(child, indent=indent)
r.endindent()
elif element.name in ["td", "th"]:
r.add_text("| ")
for child in element.children:
recursive_render(child)
r.add_text(" |")
# italics
elif element.name in ["em", "i"]:
r.open_color("italic")
for child in element.children:
recursive_render(child, indent=indent, preformatted=preformatted)
r.close_color("italic")
# bold
elif element.name in ["b", "strong"]:
r.open_color("bold")
for child in element.children:
recursive_render(child, indent=indent, preformatted=preformatted)
r.close_color("bold")
elif element.name == "a":
link = element.get("href")
# support for images nested in links
if link:
text = ""
imgtext = ""
# we display images first in a link
for child in element.children:
if child.name == "img":
recursive_render(child)
imgtext = "[IMG LINK %s]"
links.append(link + " " + text)
link_id = str(len(links) + startlinks)
r.open_theme("link")
for child in element.children:
if child.name != "img":
recursive_render(child, preformatted=preformatted)
if imgtext != "":
r.center_line()
r.add_text(imgtext % link_id)
else:
r.add_text(" [%s]" % link_id)
r.close_theme("link")
else:
# No real link found
for child in element.children:
recursive_render(child, preformatted=preformatted)
elif element.name == "img":
src = element.get("src")
text = ""
ansi_img = render_image(src, width=width, mode=mode)
alt = element.get("alt")
if alt:
alt = sanitize_string(alt)
text += "[IMG] %s" % alt
else:
text += "[IMG]"
if src:
if mode not in self.images:
self.images[mode] = []
abs_url, data = looks_like_base64(src, self.url)
# if abs_url is None, it means we don’t support
# the image (such as svg+xml). So we hide it.
if abs_url:
links.append(abs_url + " " + text)
self.images[mode].append(abs_url)
link_id = " [%s]" % (len(links) + startlinks)
r.add_block(ansi_img)
r.open_theme("image_link")
r.center_line()
r.add_text(text + link_id)
r.close_theme("image_link")
r.newline()
elif element.name == "video":
poster = element.get("poster")
src = element.get("src")
for child in element.children:
if not src:
if child.name == "source":
src = child.get("src")
text = ""
if poster:
ansi_img = render_image(poster, width=width, mode=mode)
alt = element.get("alt")
if alt:
alt = sanitize_string(alt)
text += "[VIDEO] %s" % alt
else:
text += "[VIDEO]"
if poster:
if mode not in self.images:
self.images[mode] = []
poster_url, d = looks_like_base64(poster, self.url)
if poster_url:
vid_url, d2 = looks_like_base64(src, self.url)
self.images[mode].append(poster_url)
r.add_block(ansi_img)
r.open_theme("image_link")
r.center_line()
if vid_url and src:
links.append(vid_url + " " + text)
link_id = " [%s]" % (len(links) + startlinks)
r.add_text(text + link_id)
else:
r.add_text(text)
r.close_theme("image_link")
r.newline()
elif src:
vid_url, d = looks_like_base64(src, self.url)
links.append(vid_url + " " + text)
link_id = " [%s]" % (len(links) + startlinks)
r.open_theme("image_link")
r.center_line()
r.add_text(text + link_id)
r.close_theme("image_link")
r.newline()
elif element.name == "br":
r.newline()
#weirdly, it seems that BS4 sometimes parse elements after
#as children of
for child in element.children:
recursive_render(child, indent=indent)
elif (
element.name not in ["script", "style", "template"]
and type(element) is not Comment
):
if element.string:
if preformatted:
r.open_theme("preformatted")
r.add_text(element.string)
r.close_theme("preformatted")
else:
s = sanitize_string(element.string)
if len(s.strip()) > 0:
r.add_text(s)
else:
for child in element.children:
recursive_render(child, indent=indent)
# the real render_html hearth
# note to vjousse: use self.options["ftr_site_config"] here
# Use self.url to mach against an url
if mode in ["full", "full_links_only"]:
summary = body
elif _HAS_READABILITY:
try:
readable = Document(body)
summary = readable.summary()
except Exception:
summary = body
else:
summary = body
soup = BeautifulSoup(summary, "html.parser")
# soup = BeautifulSoup(summary, 'html5lib')
if soup:
if soup.body:
recursive_render(soup.body)
else:
recursive_render(soup)
return r.get_final(), links
## Now the custom renderers
class XkcdRenderer(HtmlRenderer):
def printgemtext(self,source):
if source:
gemtext_renderer = GemtextRenderer("",self.url)
final,links = gemtext_renderer.render(source)
print(final)
def has_direct_display(self):
return _RENDER_IMAGE
#Custom renderer should return false when they can’t handle a specific content
#This allow fallback to normal html renderer
def is_valid(self):
path = urllib.parse.urlparse(self.url).path
#We strip the leading "/" to avoid empty elements in splitted
splitted = path.strip("/").split("/")
# Custom renderer only works for pure comics which have alphanumeric paths
return splitted[0].isalnum()
def get_images(self, mode="readable"):
img_url,img_path,alttext,title = self.xkcd_extract()
return [img_url]
def get_links(self,mode="readable"):
img_url,img_path,alttext,title = self.xkcd_extract()
links = super().get_links(mode=mode)
if img_url not in links:
links.append(img_url)
return links
#return [image_url,image_path, image_alt_text,image_title]
def xkcd_extract(self):
soup = BeautifulSoup(self.body, "html.parser")
comic_div = soup.find("div",{"id":"comic"})
if comic_div:
img_element = comic_div.find("img")
src=img_element.get("src")
if src.startswith("//"):
scheme = urllib.parse.urlparse(self.url).scheme
img_url = scheme + ":" + src
else:
img_url = src
img_path = netcache.get_cache_path(img_url)
alttext=img_element.get("title")
title=img_element.get("alt")
return img_url,img_path,alttext,title
else:
return None,None,None,None
def display(self, mode=None, directdisplay=False):
wtitle = self.get_formatted_title()
if not directdisplay:
body = wtitle + "\n" + self.get_body(mode=mode)
return body
else:
print(self._window_title(wtitle))
self.printgemtext("# "+self.get_title())
img_url,img_path,alttext,title = self.xkcd_extract()
#now displaying
if img_path and netcache.is_cache_valid(img_url):
terminal_image(img_path)
else:
self.printgemtext("\n> missing picture, please reload\n")
self.printgemtext(alttext)
return True
# Mapping mimetypes with renderers
# (any content with a mimetype text/* not listed here will be rendered with as GemText)
_FORMAT_RENDERERS = {
"text/gemini": GemtextRenderer,
"text/html": HtmlRenderer,
"application/xhtml+xml": HtmlRenderer,
"text/xml": FeedRenderer,
"text/plain": PlaintextRenderer,
"application/xml": FeedRenderer,
"application/rss+xml": FeedRenderer,
"application/atom+xml": FeedRenderer,
"text/gopher": GopherRenderer,
"image/*": ImageRenderer,
"application/javascript": HtmlRenderer,
"application/json": HtmlRenderer,
"text/empty": EmptyRenderer,
"message/news": GemtextRenderer,
}
_CUSTOM_RENDERERS = {
"xkcd.com": XkcdRenderer,
}
def get_mime(path, url=None):
# Beware, this one is really a shaddy ad-hoc function
if not path:
return None
# If the file is empty, simply returns it
elif os.path.exists(path) and os.stat(path).st_size == 0:
return "text/empty"
elif url and url.startswith("gopher://"):
# special case for gopher
# code copy/pasted from netcache
parsed = urllib.parse.urlparse(url)
if len(parsed.path) >= 2:
itemtype = parsed.path[1]
path = parsed.path[2:]
else:
itemtype = "1"
path = ""
if itemtype == "0":
mime = "text/gemini"
elif itemtype == "1":
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9", "g", "I", "s", ";"):
mime = "binary"
else:
mime = "text/gopher"
elif path.startswith("mailto:"):
mime = "mailto"
elif os.path.isdir(path):
mime = "Local Folder"
elif path.endswith(".gmi") or path.endswith(".gemini"):
mime = "text/gemini"
elif path.endswith("gophermap"):
mime = "text/gopher"
elif shutil.which("file"):
mime = run("file -b --mime-type %s", parameter=path).strip()
mime2, encoding = mimetypes.guess_type(path, strict=False)
# If we hesitate between html and xml, takes the xml one
# because the FeedRendered fallback to HtmlRenderer
if mime2 and mime != mime2 and "html" in mime and "xml" in mime2:
mime = "text/xml"
# We will also check if the first line starts with 0 and (not renderer or not renderer.is_valid()):
current_mime = mime_to_use.pop(0)
func = _FORMAT_RENDERERS[current_mime]
if current_mime.startswith("text"):
renderer = func(content, url,**kwargs)
# We double check if the renderer is correct.
# If not, we fallback to html
# (this is currently only for XHTML, often being
# mislabelled as xml thus RSS feeds)
if not renderer.is_valid():
func = _FORMAT_RENDERERS["text/html"]
# print("Set (fallback)RENDERER to html instead of %s"%mime)
renderer = func(content, url,**kwargs)
else:
# TODO: check this code and then remove one if.
# we don’t parse text, we give the file to the renderer
renderer = func(content, url,**kwargs)
if not renderer.is_valid():
renderer = None
#We have not found a renderer. Use a fake one.
if not renderer:
renderer = FakeRenderer("",url,**kwargs)
renderer.set_mime(mime)
if renderer and theme:
renderer.set_theme(theme)
return renderer
# This function should be removed and replaced by a set_renderer()/r.display()
def render(input, path=None, format="auto", mime=None, url=None, mode=None):
if not url:
url = ""
else:
url = url[0]
if format == "gemtext":
r = GemtextRenderer(input, url)
elif format == "html":
r = HtmlRenderer(input, url)
elif format == "feed":
r = FeedRenderer(input, url)
elif format == "gopher":
r = GopherRenderer(input, url)
elif format == "image":
r = ImageRenderer(input, url)
elif format == "folder":
r = FolderRenderer(input, url)
elif format in ["plaintext", "text"]:
r = PlaintextRenderer(input, url)
else:
if not mime and path:
r = renderer_from_file(path, url)
else:
r = set_renderer(input, url, mime)
if r:
r.display(directdisplay=True, mode=mode)
else:
print("Could not render %s" % input)
def main():
descri = (
"ansicat is a terminal rendering tool that will render multiple formats (HTML, \
Gemtext, RSS, Gophermap, Image) into ANSI text and colors.\n\
When used on a file, ansicat will try to autodetect the format. When used with \
standard input, the format must be manually specified.\n\
If the content contains links, the original URL of the content can be specified \
in order to correctly modify relatives links."
)
parser = argparse.ArgumentParser(prog="ansicat", description=descri)
parser.add_argument(
"--format",
choices=[
"auto",
"gemtext",
"html",
"feed",
"gopher",
"image",
"folder",
"text",
"plaintext",
],
help="Renderer to use. Available: auto, gemtext, html, feed, gopher, image, folder, plaintext",
)
parser.add_argument("--mime", help="Mime of the content to parse")
## The argument needs to be a path to a file. If none, then stdin is used which allows
## to pipe text directly into ansirenderer
parser.add_argument(
"--url", metavar="URL", nargs="*", help="Original URL of the content"
)
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="*",
type=argparse.FileType("r"),
default=sys.stdin,
help="Path to the text to render (default to stdin)",
)
args = parser.parse_args()
# Detect if we are running interactively or in a pipe
if sys.stdin.isatty():
# we are interactive, not in stdin, we can have multiple files as input
if isinstance(args.content, list):
for f in args.content:
path = os.path.abspath(f.name)
try:
content = f.read()
except UnicodeDecodeError:
content = f
render(
content,
path=path,
format=args.format,
url=args.url,
mime=args.mime,
mode=args.mode,
)
else:
print("Ansicat needs at least one file as an argument")
else:
# we are in stdin
if not args.format and not args.mime:
print("Format or mime should be specified when running with stdin")
else:
render(
args.content.read(),
path=None,
format=args.format,
url=args.url,
mime=args.mime,
mode=args.mode,
)
if __name__ == "__main__":
main()
offpunk-v2.7.1/cert_migration.py 0000664 0000000 0000000 00000004005 14775435273 0016757 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# SPDX-FileCopyrightText: 2024 Bert Livens
# SPDX-License-Identifier: AGPL-3.0-only
"""
A script to migrate the offpunk certificate storage to the newest version.
For each new version of offpunk that requires changes to the certificate storage
a migration function should be written, performing a migration from the
immediately previous format.
"""
import datetime
import os
import sqlite3
def upgrade_to_1(data_dir: str, config_dir: str) -> None:
print("moving from tofu.db to certificates as files")
db_path = os.path.join(config_dir, "tofu.db")
# We should check if there’s a db that exists.
# Warning: the file might exists but be empty.
if os.path.exists(db_path) and os.path.getsize(db_path) == 0:
os.remove(db_path)
if os.path.exists(db_path):
db_conn = sqlite3.connect(db_path)
db_cur = db_conn.cursor()
db_cur.execute("""
SELECT hostname, address, fingerprint, count, first_seen, last_seen
FROM cert_cache""")
certs = db_cur.fetchall()
data_dir = os.path.join(data_dir, "certs")
os.makedirs(data_dir, exist_ok=True)
for hostname, address, fingerprint, count, first_seen, last_seen in certs:
direc = os.path.join(data_dir, hostname)
os.makedirs(direc, exist_ok=True)
certdir = os.path.join(direc, address)
os.makedirs(certdir, exist_ok=True)
# filename is the fingerprint
certfile = os.path.join(certdir, str(fingerprint))
# write count
with open(certfile, 'w') as file:
file.write(str(count))
# change creation and modification date of file
first_seen = datetime.datetime.strptime(first_seen, "%Y-%m-%d %H:%M:%S.%f")
last_seen = datetime.datetime.strptime(last_seen, "%Y-%m-%d %H:%M:%S.%f")
os.utime(certfile, (first_seen.timestamp(), last_seen.timestamp()))
# remove tofu.db
os.remove(db_path)
offpunk-v2.7.1/debug.sh 0000775 0000000 0000000 00000000173 14775435273 0015026 0 ustar 00root root 0000000 0000000 #!/bin/bash
XDG_DATA_HOME="~/debug/data" XDG_CONFIG_HOME="~/debug/config" XDG_CACHE_HOME="~/debug/cache" python offpunk.py
offpunk-v2.7.1/doc/ 0000775 0000000 0000000 00000000000 14775435273 0014145 5 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/config.gmi 0000664 0000000 0000000 00000000000 14775435273 0016076 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/dev.gmi 0000664 0000000 0000000 00000000000 14775435273 0015407 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/index.gmi 0000664 0000000 0000000 00000002012 14775435273 0015745 0 ustar 00root root 0000000 0000000 # OFFPUNK - An Offline-First Browser for the Smolnet
Offpunk is a command-line browser and feed reader dedicated to browsing the Web, Gemini, Gopher and Spartan. Thanks to its permanent cache, it is optimised to be used offline with rare connections but works as well when connected.
Offpunk is optimised for reading and supports readability mode, displaying pictures, subscribing to pages or RSS feeds, managing complex lists of bookmarks. Its integrated help and easy commands make it a perfect tool for command-line novices while power-users will be amazed by its shell integration.
Offpunk is written in Python 3 by Ploum. It aims to be portable and minimise dependencies, making them optional. It supports http/https/gopher/gemini/spartan on both IPv4 and IPv6.
=> install.gmi Installing Offpunk and dependencies
=> tutorial.gmi First steps
=> config.gmi Configuring Offpunk
=> offline.gmi Using Offpunk offline
=> lists.gmi Lists and subscriptions
=> shell.gmi Shell and OS integrations
=> dev.gmi Roadmap & Contributions
offpunk-v2.7.1/doc/install.gmi 0000664 0000000 0000000 00000000000 14775435273 0016277 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/lists.gmi 0000664 0000000 0000000 00000000000 14775435273 0015767 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/offline.gmi 0000664 0000000 0000000 00000000000 14775435273 0016253 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/shell.gmi 0000664 0000000 0000000 00000000000 14775435273 0015740 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/doc/tutorial.gmi 0000664 0000000 0000000 00000000000 14775435273 0016474 0 ustar 00root root 0000000 0000000 offpunk-v2.7.1/man/ 0000775 0000000 0000000 00000000000 14775435273 0014153 5 ustar 00root root 0000000 0000000 offpunk-v2.7.1/man/ansicat.1 0000664 0000000 0000000 00000003136 14775435273 0015662 0 ustar 00root root 0000000 0000000 .Dd November 25, 2024
.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 Fl \-mode Ar MODE
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
ansicat is a terminal rendering tool
that will render multiple formats
(HTML, Gemtext, RSS, Gophermap, Image)
into ANSI text and colors.
When used on a file,
ansicat will try to autodetect the format.
When used with standard input,
the format must be manually specified.
If the content contains links,
the original URL of the content can be specified
in order to correctly modify relatives links.
.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://offpunk.net/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu
offpunk-v2.7.1/man/netcache.1 0000664 0000000 0000000 00000004253 14775435273 0016013 0 ustar 00root root 0000000 0000000 .Dd November 25, 2024
.Dt NETCACHE 1
.Os
.
.Sh NAME
.Nm netcache
.Nd local Internet cache handler for offpunk
.
.Sh SYNOPSIS
.Nm
.Op Fl \-path
.Op Fl \-ids
.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 a command-line tool to retrieve,
cache and access networked content.
By default,
netcache will returns a cached version of a given URL,
downloading it only if a cache version doesn't exist.
A validity duration,
in seconds,
can also be given
so netcache downloads the content
only if the existing cache is older than the validity.
.Pp
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.
.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 \-ids
return a list of id's for the gemini-site
instead of the content of the cache.
.It Fl \-offline
do not attempt to download,
return the cached version instead,
or error if absent from the cache.
.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 ENVIRONMENT
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
.
.Sh FILES
Default cache path is
.Pa ~/.cache/offpunk .
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr offpunk 1 ,
.Xr opnk 1 ,
.Lk https://offpunk.net/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu
offpunk-v2.7.1/man/offpunk.1 0000664 0000000 0000000 00000005133 14775435273 0015707 0 ustar 00root root 0000000 0000000 .Dd February 2, 2025
.Dt OFFPUNK 1
.Os
.
.Sh NAME
.Nm offpunk
.Nd command line gemini client
.
.Sh SYNOPSIS
.Nm
.Op Fl \-bookmarks
.Op Fl \-config\-file Ar FILE
.Op Fl \-command Ar COMMAND
.Op Fl \-sync
.Op Fl \-assume\-yes
.Op Fl \-disable\-http
.Op Fl \-fetch\-later
.Op Fl \-depth Ar DEPTH
.Op Fl \-images\-mode Ar IMAGES_MODE
.Op Fl \-cache\-validity Ar CACHE_VALIDITY
.Op Ar URL ...
.Nm
.Fl h | \-help
.Nm
.Fl \-version
.Nm
.Fl \-features
.
.Sh DESCRIPTION
Offpunk is a command-line browser and feed reader dedicated to browsing the Web,
Gemini, Gopher and Spartan.
Thanks to its permanent cache, it is optimised to be used offline with rare
connections but works as well when connected.
.Pp
Offpunk is optimised for reading and supports readability mode, displaying
pictures, subscribing to pages or RSS feeds,
managing complex lists of bookmarks.
Its integrated help and easy commands make it a perfect tool for command-line
novices while power-users will be amazed by its shell integration.
.Ss Positional arguments
.Bl -tag -width Ds -offset indent
.It URL
start with this URL
.El
.Ss Keyword arguments
.Bl -tag -width Ds -offset indent
.It Fl h , \-help
Show a help message and exit
.It Fl \-bookmarks
start with your list of bookmarks
.It Fl \-config\-file Ar FILE
use this particular config file instead of default
.It Fl \-command Ar COMMAND
launch this or those command(s) after startup (including config file).
.It Fl \-sync
run non\-interactively to build cache by exploring bookmarks
.It Fl \-assume\-yes
assume\-yes when asked questions about certificates/redirections during sync
(lower security)
.It Fl \-disable\-http
do not try to get http(s) links (but already cached will be displayed)
.It Fl \-fetch\-later
run non\-interactively with an URL as argument to fetch it later
.It Fl \-depth Ar DEPTH
depth of the cache to build.
Default is 1.
More is crazy.
Use at your own risks!
.It Fl \-images-mode Ar IMAGES_MODE
the mode to use
to choose which images to download in a HTML page.
one of (None, readable, full).
Warning: full will slowdown your sync.
.It Fl \-cache\-validity Ar CACHE_VALIDITY
duration for which a cache is valid before sync (seconds)
.It Fl \-version
display version information and quit
.It Fl \-features
display available features and dependancies then quit
.El
.
.Sh EXIT STATUS
.Ex -std
.
.Sh SEE ALSO
.Xr ansicat 1 ,
.Xr migrate-offpunk-cache 1 ,
.Xr netcache 1 ,
.Xr opnk 1 ,
.Lk https://offpunk.net/
.
.Sh HISTORY
.Nm
is a fork of the original AV-98 by
.An Solderpunk
and was originally called AV-98-offline as an experimental branch.
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu
offpunk-v2.7.1/man/opnk.1 0000664 0000000 0000000 00000002270 14775435273 0015205 0 ustar 00root root 0000000 0000000 .Dd November 25, 2024
.Dt OPNK 1
.Os
.
.Sh NAME
.Nm opnk
.Nd universal open (like a punk) for offpunk
.
.Sh SYNOPSIS
.Nm
.Op \-mode Ar MODE
.Op \-cache-validity Ar CACHE_VALIDITY
.Op Ar INPUT ...
.Nm
.Fl h | \-help
.
.Sh DESCRIPTION
opnk is an universal open command tool
that will try to display any file in the pager
.Xr less 1
after rendering its content with
.Xr ansicat 1 .
If that fails,
opnk will fallback to opening the file with
.Xr xdg-open 1 .
If given an URL as input instead of a path,
opnk will rely on
.Xr netcache 1
to get the networked content.
.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://offpunk.net/
.
.Sh AUTHORS
.An Lionel Dricot (Ploum) Aq Mt offpunk2 at ploum.eu
offpunk-v2.7.1/netcache.py 0000775 0000000 0000000 00000125254 14775435273 0015540 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import argparse
import codecs
import datetime
import getpass
import glob
import hashlib
import os
import socket
import ssl
import sys
import time
import urllib.parse
import warnings
from ssl import CertificateError
import ansicat
import offutils
from offutils import xdg
try:
import chardet
_HAS_CHARDET = True
except ModuleNotFoundError:
_HAS_CHARDET = False
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
_HAS_CRYPTOGRAPHY = True
_BACKEND = default_backend()
except (ModuleNotFoundError, ImportError):
_HAS_CRYPTOGRAPHY = False
try:
with warnings.catch_warnings():
# Disable annoying warning shown to LibreSSL users
warnings.simplefilter("ignore")
import requests
_DO_HTTP = True
except (ModuleNotFoundError, ImportError):
_DO_HTTP = False
# This list is also used as a list of supported protocols
standard_ports = {
"gemini": 1965,
"gopher": 70,
"finger": 79,
"http": 80,
"https": 443,
"spartan": 300,
}
default_protocol = "gemini"
CRLF = "\r\n"
DEFAULT_TIMEOUT = 10
_MAX_REDIRECTS = 5
# monkey-patch Gemini support in urllib.parse
# see https://github.com/python/cpython/blob/master/Lib/urllib/parse.py
urllib.parse.uses_relative.append("gemini")
urllib.parse.uses_netloc.append("gemini")
urllib.parse.uses_relative.append("spartan")
urllib.parse.uses_netloc.append("spartan")
class UserAbortException(Exception):
pass
def parse_mime(mime):
options = {}
if mime:
if ";" in mime:
splited = mime.split(";", maxsplit=1)
mime = splited[0]
if len(splited) >= 1:
options_list = splited[1].split()
for o in options_list:
spl = o.split("=", maxsplit=1)
if len(spl) > 0:
options[spl[0]] = spl[1]
return mime, options
def normalize_url(url):
if "://" not in url and ("./" not in url and url[0] != "/"):
if not url.startswith("mailto:"):
url = "gemini://" + url
return url
def cache_last_modified(url):
if not url:
return None
path = get_cache_path(url)
if path and os.path.isfile(path):
return os.path.getmtime(path)
else:
return None
def is_cache_valid(url, validity=0):
# Validity is the acceptable time for
# 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)
if cache:
# If path is too long, we always return True to avoid
# fetching it.
if len(cache) > 259:
print("We return False because path is too long")
return False
if os.path.exists(cache) and not os.path.isdir(cache):
if validity > 0:
last_modification = cache_last_modified(url)
now = time.time()
age = now - last_modification
return age < validity
else:
return True
else:
# Cache has not been build
return False
else:
# There’s not even a cache!
return False
def get_cache_path(url, add_index=True):
# 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 don’t 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):
scheme = "file"
elif parsed.scheme:
scheme = parsed.scheme
else:
scheme = default_protocol
if scheme in ["file", "mailto", "list"]:
local = True
host = ""
port = None
# file:// is 7 char
if url.startswith("file://"):
path = url[7:]
elif scheme == "mailto":
path = parsed.path
elif url.startswith("list://"):
listdir = os.path.join(xdg("data"), "lists")
listname = url[7:].lstrip("/")
if listname in [""]:
name = "My Lists"
path = listdir
else:
name = listname
path = os.path.join(listdir, "%s.gmi" % listname)
else:
path = url
else:
local = False
# Convert unicode hostname to punycode using idna RFC3490
host = parsed.netloc # .encode("idna").decode()
try:
port = parsed.port or standard_ports.get(scheme, 0)
except ValueError:
port = standard_ports.get(scheme, 0)
# special gopher selector case
if scheme == "gopher":
if len(parsed.path) >= 2:
itemtype = parsed.path[1]
path = parsed.path[2:]
else:
itemtype = "1"
path = ""
if itemtype == "0":
mime = "text/gemini"
elif itemtype == "1":
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9", "g", "I", "s", ";"):
mime = "binary"
else:
mime = "text/gopher"
else:
path = parsed.path
if parsed.query:
# we don’t add the query if path is too long because path above 260 char
# are not supported and crash python.
# Also, very long query are usually useless stuff
if len(path + parsed.query) < 258:
path += "/" + parsed.query
# Now, we have a partial path. Let’s make it full path.
if local:
cache_path = path
elif scheme and host:
cache_path = os.path.expanduser(xdg("cache") + scheme + "/" + host + path)
# There’s an OS limitation 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
# index files. This will break if the index is not
# index.gmi. I don’t know how to know the real name
# of the file. But first, we need to ensure that the domain name
# finish by "/". Else, the cache will create a file, not a folder.
if scheme.startswith("http"):
index = "index.html"
elif scheme == "finger":
index = "index.txt"
elif scheme == "gopher":
index = "gophermap"
else:
index = "index.gmi"
if path == "" or os.path.isdir(cache_path):
if not cache_path.endswith("/"):
cache_path += "/"
if not url.endswith("/"):
url += "/"
if add_index and 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):
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 %s characters long which is too long. \
# OS only allows 260 characters.\n\n"%(len(cache_path)))
#print(url)
#return None
# path lenght is limited to 260 charaters. Let’s cut it and
# hope that there’s no major conflict here. (that’s still better
# than crashing, after all.
cache_path = cache_path[:259]
return cache_path
def write_body(url, body, mime=None):
# body is a copy of the raw gemtext
# Write_body() also create the cache !
# DEFAULT GEMINI MIME
mime, options = parse_mime(mime)
cache_path = get_cache_path(url)
if cache_path:
if mime and mime.startswith("text/"):
mode = "w"
else:
mode = "wb"
cache_dir = os.path.dirname(cache_path)
# If the subdirectory already exists as a file (not a folder)
# We remove it (happens when accessing URL/subfolder before
# URL/subfolder/file.gmi.
# This causes loss of data in the cache
# proper solution would be to save "sufolder" as "sufolder/index.gmi"
# If the subdirectory doesn’t exist, we recursively try to find one
# until it exists to avoid a file blocking the creation of folders
root_dir = cache_dir
while not os.path.exists(root_dir):
root_dir = os.path.dirname(root_dir)
if os.path.isfile(root_dir):
os.remove(root_dir)
os.makedirs(cache_dir, exist_ok=True)
with open(cache_path, mode=mode) as f:
f.write(body)
f.close()
return cache_path
def set_error(url, err):
# If we get an error, we want to keep an existing cache
# but we need to touch it or to create an empty one
# to avoid hitting the error at each refresh
cache = get_cache_path(url)
if is_cache_valid(url):
os.utime(cache)
elif cache:
cache_dir = os.path.dirname(cache)
root_dir = cache_dir
while not os.path.exists(root_dir):
root_dir = os.path.dirname(root_dir)
if os.path.isfile(root_dir):
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))
# 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 resource will be tentatively fetched during next sync.\n")
c.close()
return cache
def _fetch_http(
url,
max_size=None,
timeout=DEFAULT_TIMEOUT,
accept_bad_ssl_certificates=False,
force_large_download=False,
**kwargs,
):
if not _DO_HTTP:
return None
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:
if "content-type" in response.headers:
mime = response.headers["content-type"]
else:
mime = None
if "content-length" in response.headers:
length = int(response.headers["content-length"])
else:
length = 0
if not force_large_download and max_size and length > max_size:
response.close()
return too_large_error(url, str(length / 100), max_size)
elif not force_large_download and max_size and length == 0:
body = b""
downloaded = 0
for r in response.iter_content():
body += r
# We divide max_size for streamed content
# in order to catch them faster
size = sys.getsizeof(body)
max = max_size / 2
current = round(size * 100 / max, 1)
if current > downloaded:
downloaded = current
print(
" -> Receiving stream: %s%% of allowed data" % downloaded,
end="\r",
)
# print("size: %s (%s\% of maxlenght)"%(size,size/max_size))
if size > max_size / 2:
response.close()
return too_large_error(url, "streaming", max_size)
response.close()
else:
body = response.content
response.close()
if mime and "text/" in mime:
body = body.decode("UTF-8", "replace")
cache = write_body(url, body, mime)
return cache
def _fetch_gopher(url, timeout=DEFAULT_TIMEOUT, **kwargs):
parsed = urllib.parse.urlparse(url)
host = parsed.hostname
port = parsed.port or 70
if len(parsed.path) >= 2:
itemtype = parsed.path[1]
selector = parsed.path[2:]
else:
itemtype = "1"
selector = ""
addresses = socket.getaddrinfo(host, port, family=0, type=socket.SOCK_STREAM)
s = socket.create_connection((host, port))
for address in addresses:
s = socket.socket(address[0], address[1])
s.settimeout(timeout)
try:
s.connect(address[4])
break
except OSError as e:
err = e
if parsed.query:
request = selector + "\t" + parsed.query
else:
request = selector
request += "\r\n"
s.sendall(request.encode("UTF-8"))
response1 = s.makefile("rb")
response = response1.read()
# Transcode response into UTF-8
# if itemtype in ("0","1","h"):
if itemtype not in ("9", "g", "I", "s", ";"):
# Try most common encodings
for encoding in ("UTF-8", "ISO-8859-1"):
try:
response = response.decode("UTF-8")
break
except UnicodeDecodeError:
pass
else:
# try to find encoding
if _HAS_CHARDET:
detected = chardet.detect(response)
response = response.decode(detected["encoding"])
else:
raise UnicodeDecodeError
if itemtype == "0":
mime = "text/gemini"
elif itemtype == "1":
mime = "text/gopher"
elif itemtype == "h":
mime = "text/html"
elif itemtype in ("9", "g", "I", "s", ";"):
mime = None
else:
# by default, we should consider Gopher
mime = "text/gopher"
cache = write_body(url, response, mime)
return cache
def _fetch_finger(url, timeout=DEFAULT_TIMEOUT, **kwargs):
parsed = urllib.parse.urlparse(url)
host = parsed.hostname
port = parsed.port or standard_ports["finger"]
query = parsed.path.lstrip("/") + "\r\n"
with socket.create_connection((host, port)) as sock:
sock.settimeout(timeout)
sock.send(query.encode())
response = sock.makefile("rb").read().decode("UTF-8")
cache = write_body(response, "text/plain")
return cache
# Originally copied from reference spartan client by Michael Lazar
def _fetch_spartan(url, **kwargs):
cache = None
url_parts = urllib.parse.urlparse(url)
host = url_parts.hostname
port = url_parts.port or standard_ports["spartan"]
path = url_parts.path or "/"
query = url_parts.query
redirect_url = None
with socket.create_connection((host, port)) as sock:
if query:
data = urllib.parse.unquote_to_bytes(query)
else:
data = b""
encoded_host = host.encode("idna")
ascii_path = urllib.parse.unquote_to_bytes(path)
encoded_path = urllib.parse.quote_from_bytes(ascii_path).encode("ascii")
sock.send(b"%s %s %d\r\n" % (encoded_host, encoded_path, len(data)))
fp = sock.makefile("rb")
response = fp.readline(4096).decode("ascii").strip("\r\n")
parts = response.split(" ", maxsplit=1)
code, meta = int(parts[0]), parts[1]
if code == 2:
body = fp.read()
if meta.startswith("text"):
body = body.decode("UTF-8")
cache = write_body(url, body, meta)
elif code == 3:
redirect_url = url_parts._replace(path=meta).geturl()
else:
return set_error(url, "Spartan code %s: Error %s" % (code, meta))
if redirect_url:
cache = _fetch_spartan(redirect_url)
return cache
def _validate_cert(address, host, cert, accept_bad_ssl=False, automatic_choice=None):
"""
Validate a TLS certificate in TOFU mode.
If the cryptography module is installed:
- Check the certificate Common Name or SAN matches `host`
- Check the certificate's not valid before date is in the past
- Check the certificate's not valid after date is in the future
Whether the cryptography module is installed or not, check the
certificate's fingerprint against the TOFU database to see if we've
previously encountered a different certificate for this IP address and
hostname.
"""
now = datetime.datetime.now(datetime.timezone.utc)
if _HAS_CRYPTOGRAPHY:
# Using the cryptography module we can get detailed access
# to the properties of even self-signed certs, unlike in
# the standard ssl library...
c = x509.load_der_x509_certificate(cert, _BACKEND)
# Check certificate validity dates
if accept_bad_ssl:
if c.not_valid_before >= now:
raise CertificateError(
"Certificate not valid until: {}!".format(c.not_valid_before)
)
elif c.not_valid_after <= now:
raise CertificateError(
"Certificate expired as of: {})!".format(c.not_valid_after)
)
# Check certificate hostnames
names = []
common_name = c.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
if common_name:
names.append(common_name[0].value)
try:
names.extend(
[
alt.value
for alt in c.extensions.get_extension_for_oid(
x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME
).value
]
)
except x509.ExtensionNotFound:
pass
names = set(names)
for name in names:
try:
ssl._dnsname_match(str(name), host)
break
except CertificateError:
continue
else:
# If we didn't break out, none of the names were valid
raise CertificateError(
"Hostname does not match certificate common name or any alternative names."
)
sha = hashlib.sha256()
sha.update(cert)
fingerprint = sha.hexdigest()
# The directory of this host and IP-address, e.g.
# ~/.local/share/offpunk/certs/srht.site/46.23.81.157/
certdir = os.path.join(xdg("data"), "certs")
hostdir = os.path.join(certdir, host)
sitedir = os.path.join(hostdir, address)
# 1. We check through cached certificates do extract the
# most_frequent_cert and to see if one is matching the current one.
# 2. If we have no match but one valid most_frequent_cert, we do the
# "throws warning" code.
# 3. If no certificate directory or no valid cached certificates, we do
# the "First-Use" routine.
most_frequent_cert = None
matching_fingerprint = False
# 1. Have we been here before? (the directory exists)
if os.path.isdir(sitedir):
max_count = 0
files = os.listdir(sitedir)
count = 0
certcache = os.path.join(xdg("config"), "cert_cache")
for cached_fingerprint in files:
filepath = os.path.join(sitedir, cached_fingerprint)
certpath = os.path.join(certcache, cached_fingerprint + ".crt")
with open(filepath, "r") as f:
count = int(f.read())
if os.path.exists(certpath):
if count > max_count:
max_count = count
most_frequent_cert = cached_fingerprint
if fingerprint == cached_fingerprint:
# Matched!
# Increase the counter for this certificate (this also updates
# the modification time of the file)
with open(filepath, "w") as f:
f.write(str(count + 1))
matching_fingerprint = True
break
# 2. Do we have some certificates but none of them is matching the current one?
if most_frequent_cert and not matching_fingerprint:
with open(os.path.join(certcache, most_frequent_cert + ".crt"), "rb") as fp:
previous_cert = fp.read()
if _HAS_CRYPTOGRAPHY:
# Load the most frequently seen certificate to see if it has
# expired
previous_cert = x509.load_der_x509_certificate(previous_cert, _BACKEND)
previous_ttl = previous_cert.not_valid_after_utc - now
print(previous_ttl)
print("****************************************")
print("[SECURITY WARNING] Unrecognised certificate!")
print(
"The certificate presented for {} ({}) has never been seen before.".format(
host, address
)
)
print("This MIGHT be a Man-in-the-Middle attack.")
print(
"A different certificate has previously been seen {} times.".format(
max_count
)
)
if _HAS_CRYPTOGRAPHY:
if previous_ttl < datetime.timedelta():
print("That certificate has expired, which reduces suspicion somewhat.")
else:
print("That certificate is still valid for: {}".format(previous_ttl))
print("****************************************")
print("Attempt to verify the new certificate fingerprint out-of-band:")
print(fingerprint)
if automatic_choice:
choice = automatic_choice
else:
choice = input("Accept this new certificate? Y/N ").strip().lower()
if choice in ("y", "yes"):
with open(os.path.join(sitedir, fingerprint), "w") as fp:
fp.write("1")
with open(os.path.join(certcache, fingerprint + ".crt"), "wb") as fp:
fp.write(cert)
else:
raise Exception("TOFU Failure!")
# 3. If no directory or no cert found in it, we cache it
if not most_frequent_cert:
if not os.path.exists(certdir): # XDG_DATA/offpunk/certs
os.makedirs(certdir)
if not os.path.exists(hostdir): # XDG_DATA/offpunk/certs/site.net
os.makedirs(hostdir)
if not os.path.exists(
sitedir
): # XDG_DATA/offpunk/certs/site.net/123.123.123.123
os.makedirs(sitedir)
with open(os.path.join(sitedir, fingerprint), "w") as fp:
fp.write("1")
certcache = os.path.join(xdg("config"), "cert_cache")
if not os.path.exists(certcache):
os.makedirs(certcache)
with open(os.path.join(certcache, fingerprint + ".crt"), "wb") as fp:
fp.write(cert)
def _get_client_certkey(site_id: str, host: str):
# returns {cert: str, key: str}
certdir = os.path.join(xdg("data"), "certs", host)
certf = os.path.join(certdir, "%s.cert" % site_id)
keyf = os.path.join(certdir, "%s.key" % site_id)
if not os.path.exists(certf) or not os.path.exists(keyf):
if host != "":
split = host.split(".")
# if len(split) > 2: # Why not allow a global identity? Maybe I want
# to login to all sites with the same
# certificate.
return _get_client_certkey(site_id, ".".join(split[1:]))
return None
certkey = dict(cert=certf, key=keyf)
return certkey
def _get_site_ids(url: str):
newurl = normalize_url(url)
u = urllib.parse.urlparse(newurl)
if u.scheme == "gemini" and u.username is None:
certdir = os.path.join(xdg("data"), "certs")
netloc_parts = u.netloc.split(".")
site_ids = []
for i in range(len(netloc_parts), 0, -1):
lasti = ".".join(netloc_parts[-i:])
direc = os.path.join(certdir, lasti)
for certfile in glob.glob(os.path.join(direc, "*.cert")):
site_id = certfile.split("/")[-1].split(".")[-2]
site_ids.append(site_id)
return site_ids
else:
return []
def create_certificate(name: str, days: int, hostname: str):
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
sitecertdir = os.path.join(xdg("data"), "certs", hostname)
keyfile = os.path.join(sitecertdir, name + ".key")
# create the directory of it doesn't exist
os.makedirs(sitecertdir, exist_ok=True)
with open(keyfile, "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
xname = x509.Name(
[
x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, name),
]
)
# generate the cert, valid a week ago (timekeeping is hard, let's give it a
# little margin). issuer and subject are your name
cert = (
x509.CertificateBuilder()
.subject_name(xname)
.issuer_name(xname)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow() - datetime.timedelta(days=7))
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=days))
.sign(key, hashes.SHA256())
)
certfile = os.path.join(sitecertdir, name + ".cert")
with open(certfile, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
def get_certs(url: str):
u = urllib.parse.urlparse(normalize_url(url))
if u.scheme == "gemini":
certdir = os.path.join(xdg("data"), "certs")
netloc_parts = u.netloc.split(".")
site_ids = []
if "@" in netloc_parts[0]:
netloc_parts[0] = netloc_parts[0].split("@")[1]
for i in range(len(netloc_parts), 0, -1):
lasti = ".".join(netloc_parts[-i:])
direc = os.path.join(certdir, lasti)
for certfile in glob.glob(os.path.join(direc, "*.cert")):
site_id = certfile.split("/")[-1].split(".")[-2]
site_ids.append(site_id)
return site_ids
else:
return []
def _fetch_gemini(
url,
timeout=DEFAULT_TIMEOUT,
interactive=True,
accept_bad_ssl_certificates=False,
**kwargs,
):
cache = None
newurl = url
url_parts = urllib.parse.urlparse(url)
host = url_parts.hostname
site_id = url_parts.username
port = url_parts.port or standard_ports["gemini"]
path = url_parts.path or "/"
query = url_parts.query
# 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."""
host = host.encode("idna").decode()
# Do DNS resolution
# DNS lookup - will get IPv4 and IPv6 records if IPv6 is enabled
if ":" in host:
# This is likely a literal IPv6 address, so we can *only* ask for
# IPv6 addresses or getaddrinfo will complain
family_mask = socket.AF_INET6
elif socket.has_ipv6:
# Accept either IPv4 or IPv6 addresses
family_mask = 0
else:
# IPv4 only
family_mask = socket.AF_INET
addresses = socket.getaddrinfo(
host, port, family=family_mask, type=socket.SOCK_STREAM
)
# Sort addresses so IPv6 ones come first
addresses.sort(key=lambda add: add[0] == socket.AF_INET6, reverse=True)
# Continuation of send_request
# Prepare TLS context
protocol = (
ssl.PROTOCOL_TLS_CLIENT if sys.version_info.minor >= 6 else ssl.PROTOCOL_TLSv1_2
)
context = ssl.SSLContext(protocol)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
# When using an identity, use the certificate and key
if site_id:
certkey = _get_client_certkey(site_id, host)
if certkey:
context.load_cert_chain(certkey["cert"], certkey["key"])
else:
print("This identity doesn't exist for this site (or is disabled).")
# Impose minimum TLS version
# In 3.7 and above, this is easy...
if sys.version_info.minor >= 7:
context.minimum_version = ssl.TLSVersion.TLSv1_2
# Otherwise, it seems very hard...
# The below is less strict than it ought to be, but trying to disable
# TLS v1.1 here using ssl.OP_NO_TLSv1_1 produces unexpected failures
# with recent versions of OpenSSL. What a mess...
else:
context.options |= ssl.OP_NO_SSLv3
context.options |= ssl.OP_NO_SSLv2
# Try to enforce sensible ciphers
try:
context.set_ciphers(
"AESGCM+ECDHE:AESGCM+DHE:CHACHA20+ECDHE:CHACHA20+DHE:!DSS:!SHA1:!MD5:@STRENGTH"
)
except ssl.SSLError:
# Rely on the server to only support sensible things, I guess...
pass
# Connect to remote host by any address possible
err = None
for address in addresses:
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:
err = e
else:
# If we couldn't connect to *any* of the addresses, just
# bubble up the exception from the last attempt and deny
# knowledge of earlier failures.
raise err
# Do TOFU
cert = s.getpeercert(binary_form=True)
# 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")
# Send request and wrap response in a file descriptor
url = urllib.parse.urlparse(url)
new_host = host
# Handle IPV6 hostname
if ":" in new_host:
new_host = "[" + new_host + "]"
if port != standard_ports["gemini"]:
new_host += ":" + str(port)
url_no_username = urllib.parse.urlunparse(url._replace(netloc=new_host))
if site_id:
url = urllib.parse.urlunparse(url._replace(netloc=site_id + "@" + new_host))
else:
url = url_no_username
s.sendall((url_no_username + CRLF).encode("UTF-8"))
f = s.makefile(mode="rb")
## end of send_request in AV98
# Spec dictates should not exceed 1024 bytes,
# so maximum valid header length is 1027 bytes.
header = f.readline(1027)
header = urllib.parse.unquote(header.decode("UTF-8"))
if not header or header[-1] != "\n":
raise RuntimeError("Received invalid header from server!")
header = header.strip()
# Validate header
status, meta = header.split(maxsplit=1)
if len(meta) > 1024 or len(status) != 2 or not status.isnumeric():
f.close()
raise RuntimeError("Received invalid header from server!")
# Update redirect loop/maze escaping state
if not status.startswith("3"):
previous_redirectors = set()
# TODO FIXME
else:
# we set a previous_redirectors anyway because refactoring in progress
previous_redirectors = set()
# 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:
user_input = input("> ")
newurl = url.split("?")[0]
return _fetch_gemini(newurl + "?" + user_input)
else:
return None, None
# Redirects
elif status.startswith("3"):
newurl = urllib.parse.urljoin(url, meta)
if newurl == url:
raise RuntimeError("URL redirects to itself!")
elif newurl in previous_redirectors:
raise RuntimeError("Caught in redirect loop!")
elif len(previous_redirectors) == _MAX_REDIRECTS:
raise RuntimeError(
"Refusing to follow more than %d consecutive redirects!"
% _MAX_REDIRECTS
)
# TODO: redirections handling should be refactored
# elif "interactive" in options and not options["interactive"]:
# follow = self.automatic_choice
# # Never follow cross-domain redirects without asking
# elif new_gi.host.encode("idna") != gi.host.encode("idna"):
# follow = input("Follow cross-domain redirect to %s? (y/n) " % new_gi.url)
# # Never follow cross-protocol redirects without asking
# elif new_gi.scheme != gi.scheme:
# follow = input("Follow cross-protocol redirect to %s? (y/n) " % new_gi.url)
# # Don't follow *any* redirect without asking if auto-follow is off
# elif not self.options["auto_follow_redirects"]:
# follow = input("Follow redirect to %s? (y/n) " % new_gi.url)
# # Otherwise, follow away
else:
follow = "yes"
if follow.strip().lower() not in ("y", "yes"):
raise UserAbortException()
previous_redirectors.add(url)
# if status == "31":
# # Permanent redirect
# self.permanent_redirects[gi.url] = new_gi.url
return _fetch_gemini(newurl, interactive=interactive)
# Errors
elif status.startswith("4") or status.startswith("5"):
raise RuntimeError(meta)
# Client cert
elif status.startswith("6"):
error = "You need to provide a client-certificate to access this page."
raise RuntimeError(error)
# 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
assert status.startswith("2")
mime = meta
# Read the response body over the network
fbody = f.read()
# DEFAULT GEMINI MIME
if mime == "":
mime = "text/gemini; charset=utf-8"
shortmime, mime_options = parse_mime(mime)
if "charset" in mime_options:
try:
codecs.lookup(mime_options["charset"])
except LookupError:
# raise RuntimeError("Header declared unknown encoding %s" % mime_options)
# If the encoding is wrong, there’s a high probably it’s UTF-8 with a bad header
mime_options["charset"] = "UTF-8"
if shortmime.startswith("text/"):
# Get the charset and default to UTF-8 in none
encoding = mime_options.get("charset", "UTF-8")
try:
body = fbody.decode(encoding)
except UnicodeError:
raise RuntimeError(
"Could not decode response body using %s\
encoding declared in header!"
% encoding
)
else:
body = fbody
cache = write_body(url, body, mime)
return cache, url
def fetch(
url,
offline=False,
download_image_first=True,
images_mode="readable",
validity=0,
**kwargs,
):
url = normalize_url(url)
newurl = url
path = None
print_error = "print_error" in kwargs.keys() and kwargs["print_error"]
# First, 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)
):
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:
try:
scheme = url.split("://")[0]
if scheme not in standard_ports:
if print_error:
print("%s is not a supported protocol" % scheme)
path = None
elif scheme in ("http", "https"):
if _DO_HTTP:
path = _fetch_http(newurl, **kwargs)
else:
print("HTTP requires python-requests")
elif scheme == "gopher":
path = _fetch_gopher(newurl, **kwargs)
elif scheme == "finger":
path = _fetch_finger(newurl, **kwargs)
elif scheme == "gemini":
path, newurl = _fetch_gemini(url, **kwargs)
elif scheme == "spartan":
path, newurl = _fetch_spartan(url, **kwargs)
else:
print("scheme %s not implemented yet" % scheme)
except UserAbortException:
return None, newurl
except Exception as err:
cache = set_error(newurl, err)
# Print an error message
# we fail silently when sync_only
if isinstance(err, socket.gaierror):
if print_error:
print("ERROR: DNS error!")
elif isinstance(err, ConnectionRefusedError):
if print_error:
print("ERROR1: Connection refused!")
elif isinstance(err, ConnectionResetError):
if print_error:
print("ERROR2: Connection reset!")
elif isinstance(err, (TimeoutError, socket.timeout)):
if print_error:
print("""ERROR3: Connection timed out!
Slow internet connection? Use 'set timeout' to be more patient.""")
elif isinstance(err, FileExistsError):
if print_error:
print("""ERROR5: Trying to create a directory which already exists
in the cache : """)
print(err)
elif _DO_HTTP and 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):
if print_error:
print("""ERROR7: Cannot connect to URL:\n""")
print(str(err))
else:
if print_error:
import traceback
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
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 a cache version doesn't exist. A validity duration, in seconds, can also \
be given so netcache downloads the content only if the existing cache is older than the validity."
# Parse arguments
parser = argparse.ArgumentParser(prog="netcache", description=descri)
parser.add_argument(
"--path",
action="store_true",
help="return path to the cache instead of the content of the cache",
)
parser.add_argument(
"--ids",
action="store_true",
help="return a list of id's for the gemini-site instead of the content of the cache",
)
parser.add_argument(
"--offline",
action="store_true",
help="Do not attempt to download, return cached version or error",
)
parser.add_argument(
"--max-size",
type=int,
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",
)
# --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()
param = {}
for u in args.url:
if args.offline:
path = get_cache_path(u)
elif args.ids:
ids = _get_site_ids(u)
else:
path, url = fetch(
u,
max_size=args.max_size,
timeout=args.timeout,
validity=args.cache_validity,
)
if args.path:
print(path)
elif args.ids:
print(ids)
else:
with open(path, "r") as f:
print(f.read())
f.close()
if __name__ == "__main__":
main()
offpunk-v2.7.1/netcache_migration.py 0000664 0000000 0000000 00000002130 14775435273 0017571 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# SPDX-FileCopyrightText: 2023 Sotiris Papatheodorou
# SPDX-License-Identifier: BSD-2-Clause
"""
A script to migrate the offpunk cache to the newest version.
For each new version of offpunk that requires changes to the cache a migration
function should be written. The name of the function should have the format
v__ and it should accept the
offpunk cache directory as a string. The function should perform a migration
from the immediately previous cache format. All migration functions must be
called at the end of this script from oldest to newest.
"""
import os
import os.path
def upgrade_to_1(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)
offpunk-v2.7.1/offblocklist.py 0000664 0000000 0000000 00000001527 14775435273 0016440 0 ustar 00root root 0000000 0000000 # The following are the default redirections from Offpunk
# Those are by default because they should make sens with offpunk
redirects = {
"*reddit.com" : "teddit.net",
"*medium.com" : "scribe.rip",
}
#following are blocked URLs. Visiting them with offpunk doesn’t make sense.
#Blocking them will save a lot of bandwith
blocked = {
"twitter.com",
"x.com",
"youtube.com",
"youtu.be",
"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",
}
offpunk-v2.7.1/offpunk.py 0000775 0000000 0000000 00000254447 14775435273 0015445 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# Offpunk Offline Gemini client
"""
Offline-First Gemini/Web/Gopher/RSS reader and browser
"""
__version__ = "2.7.1"
# Initial imports and conditional imports {{{
import argparse
import cmd
import os
import os.path
import shutil
import sys
import time
import urllib.parse
import ansicat
import netcache
import offblocklist
import offthemes
import opnk
from offutils import (
is_local,
looks_like_url,
mode_url,
run,
term_width,
unmode_url,
xdg,
init_config,
)
try:
import setproctitle
setproctitle.setproctitle("offpunk")
_HAS_SETPROCTITLE = True
except ModuleNotFoundError:
_HAS_SETPROCTITLE = False
# This method copy a string to the system clipboard
def clipboard_copy(to_copy):
copied = False
if shutil.which("xsel"):
run("xsel -b -i", input=to_copy, direct_output=True)
copied = True
if shutil.which("xclip"):
run("xclip -selection clipboard", input=to_copy, direct_output=True)
copied = True
if shutil.which("wl-copy"):
run("wl-copy", input=to_copy, direct_output=True)
copied = True
if not copied:
print("Install xsel/xclip (X11) or wl-clipboard (Wayland) to use copy")
# This method returns an array with all the values in all system clipboards
def clipboard_paste():
# We use a set to avoid duplicates
clipboards = set()
commands = set()
pasted = False
if shutil.which("xsel"):
pasted = True
for selec in ["-p", "-s", "-b"]:
commands.add("xsel " + selec)
if shutil.which("xclip"):
pasted = True
for selec in ["clipboard", "primary", "secondary"]:
commands.add("xsel " + selec)
if shutil.which("wl-paste"):
pasted = True
for selec in ["", "-p"]:
commands.add("wl-paste " + selec)
for command in commands:
try:
clipboards.add(run(command))
except Exception:
# print("Skippink clipboard %s because %s"%(selec,err))
pass
if not pasted:
print(
"Install xsel/xclip (X11) or wl-clipboard (Wayland) to get URLs from your clipboard"
)
return list(clipboards)
# }}} end of imports
# Command abbreviations
_ABBREVS = {
"..": "up",
"a": "add",
"b": "back",
"bb": "blackbox",
"bm": "bookmarks",
"book": "bookmarks",
"cert": "certs",
"cp": "copy",
"f": "forward",
"g": "go",
"h": "history",
"hist": "history",
"l": "view",
"less": "view",
"man": "help",
"mv": "move",
"n": "next",
"off": "offline",
"on": "online",
"p": "previous",
"prev": "previous",
"q": "quit",
"r": "reload",
"s": "save",
"se": "search",
"/": "find",
"t": "tour",
"u": "up",
"v": "view",
"w": "wikipedia",
"wen": "wikipedia en",
"wfr": "wikipedia fr",
"wes": "wikipedia es",
"abbrevs": "alias",
}
_MIME_HANDLERS = {}
# GeminiClient Decorators
# decorator to be sure that self.current_url exists
def needs_gi(inner):
def outer(self, *args, **kwargs):
if not self.current_url:
print("You need to 'go' somewhere, first")
return None
else:
return inner(self, *args, **kwargs)
outer.__doc__ = inner.__doc__
return outer
class GeminiClient(cmd.Cmd):
def __init__(self, completekey="tab", synconly=False):
cmd.Cmd.__init__(self)
# Set umask so that nothing we create can be read by anybody else.
# The certificate cache and TOFU database contain "browser history"
# type sensitivie information.
os.umask(0o077)
self.opencache = opnk.opencache()
self.theme = offthemes.default
self.set_prompt("ON")
self.current_url = None
self.hist_index = 0
self.marks = {}
self.page_index = 0
self.permanent_redirects = {}
# Sync-only mode is restriced by design
self.offline_only = False
self.sync_only = False
self.support_http = netcache._DO_HTTP
self.automatic_choice = "n"
self.client_certs = {"active": None}
self.active_cert_domains = []
self.active_is_transient = False
self.options = {
"debug": False,
"beta": False,
"timeout": 600,
"short_timeout": 5,
"width": 72,
"auto_follow_redirects": True,
"tls_mode": "tofu",
"archives_size": 200,
"history_size": 200,
"max_size_download": 10,
"editor": None,
"images_mode": "readable",
"redirects": True,
# the wikipedia entry needs two %s, one for lang, other for search
"wikipedia": "gemini://gemi.dev/cgi-bin/wp.cgi/view/%s?%s",
"search": "gemini://kennedy.gemi.dev/search?%s",
"accept_bad_ssl_certificates": False,
"default_protocol": "gemini",
"ftr_site_config": None,
"preformat_wrap": False,
}
self.redirects = offblocklist.redirects
for i in offblocklist.blocked:
self.redirects[i] = "blocked"
term_width(new_width=self.options["width"])
self.log = {
"start_time": time.time(),
}
def set_prompt(self, prompt):
key = "prompt_%s" % prompt.lower()
# default color is green
colors = self.theme.get(key, ["green"])
open_color = ""
close_color = ""
for color in colors:
# default to green 32 if color name `green` is not found
ansi = offthemes.colors.get(color, ["32", "39"])
open_color += "%s;" % ansi[0]
close_color += "%s;" % ansi[1]
# removing the last ";"
open_color = open_color.rstrip(";")
close_color = close_color.rstrip(";")
self.prompt = (
"\001\x1b[%sm\002" % open_color
+ prompt
+ "\001\x1b[%sm\002" % close_color
+ "> "
)
# support for 256 color mode:
# self.prompt = "\001\x1b[38;5;76m\002" + "ON" + "\001\x1b[38;5;255m\002" + "> " + "\001\x1b[0m\002"
return self.prompt
def complete_list(self, text, line, begidx, endidx):
allowed = []
cmds = ["create", "edit", "subscribe", "freeze", "normal", "delete", "help"]
lists = self.list_lists()
words = len(line.split())
# We need to autocomplete listname for the first or second argument
# If the first one is a cmds
if words <= 1:
allowed = lists + cmds
elif words == 2:
# if text, the completing word is the second
if text:
allowed = lists + cmds
else:
current_cmd = line.split()[1]
if current_cmd in ["help", "create"]:
allowed = []
elif current_cmd in cmds:
allowed = lists
elif words == 3 and text != "":
current_cmd = line.split()[1]
if current_cmd in ["help", "create"]:
allowed = []
elif current_cmd in cmds:
allowed = lists
return [i + " " for i in allowed if i.startswith(text)]
def complete_add(self, text, line, begidx, endidx):
if len(line.split()) == 2 and text != "":
allowed = self.list_lists()
elif len(line.split()) == 1:
allowed = self.list_lists()
else:
allowed = []
return [i + " " for i in allowed if i.startswith(text)]
def complete_move(self, text, line, begidx, endidx):
return self.complete_add(text, line, begidx, endidx)
def complete_tour(self, text, line, begidx, endidx):
return self.complete_add(text, line, begidx, endidx)
def complete_theme(self, text, line, begidx, endidx):
elements = offthemes.default
colors = offthemes.colors
words = len(line.split())
if words <= 1:
allowed = elements
elif words == 2 and text != "":
allowed = elements
else:
allowed = colors
return [i + " " for i in allowed if i.startswith(text)]
def get_renderer(self, url=None):
# If launched without argument, we return the renderer for the current URL
if not url:
url = self.current_url
return self.opencache.get_renderer(url, theme=self.theme)
def _go_to_url(
self,
url,
update_hist=True,
force_refresh=False,
handle=True,
grep=None,
name=None,
mode=None,
limit_size=False,
force_large_download=False,
):
"""This method might be considered "the heart of Offpunk".
Everything involved in fetching a gemini resource happens here:
sending the request over the network, parsing the response,
storing the response in a temporary file, choosing
and calling a handler program, and updating the history.
Nothing is returned."""
if not url:
return
url, newmode = unmode_url(url)
if not mode:
mode = newmode
# we don’t handle the name anymore !
if name:
print("We don’t handle name of URL: %s" % name)
# Obey permanent redirects
if url in self.permanent_redirects:
self._go_to_url(
self.permanent_redirects[url],
update_hist=update_hist,
force_refresh=force_refresh,
handle=handle,
name=name,
mode=mode,
limit_size=limit_size,
grep=grep,
)
return
# Code to translate URLs to better frontends (think twitter.com -> nitter)
parsed = urllib.parse.urlparse(url)
netloc = parsed.netloc
if netloc.startswith("www."):
netloc = netloc[4:]
# we block/redirect even subdomains
for key in self.redirects.keys():
match = key == netloc
if key.startswith("*"):
match = netloc.endswith(key[1:])
if match:
if self.redirects[key] == "blocked":
text = ""
text += "Blocked URL: "+url + "\n"
text += "This website has been blocked with the following rule:\n"
text += key + "\n"
text += "Use the following redirect command to unblock it:\n"
text += "redirect %s NONE" %key
if handle and not self.sync_only:
print(text)
return
else:
parsed = parsed._replace(netloc=self.redirects[key])
url = urllib.parse.urlunparse(parsed)
params = {}
params["timeout"] = self.options["short_timeout"]
if limit_size:
params["max_size"] = int(self.options["max_size_download"]) * 1000000
params["print_error"] = not self.sync_only
params["interactive"] = not self.sync_only
params["offline"] = self.offline_only
params["accept_bad_ssl_certificates"] = self.options[
"accept_bad_ssl_certificates"
]
params["ftr_site_config"] = self.options["ftr_site_config"]
params["preformat_wrap"] = self.options["preformat_wrap"]
if mode:
params["images_mode"] = mode
else:
params["images_mode"] = self.options["images_mode"]
if force_refresh:
params["validity"] = 1
elif not self.offline_only:
# A cache is always valid at least 60seconds
params["validity"] = 60
params["force_large_download"] = force_large_download
# Use cache or mark as to_fetch if resource is not cached
if handle and not self.sync_only:
displayed, url = self.opencache.opnk(
url, mode=mode, grep=grep, theme=self.theme, **params
)
modedurl = mode_url(url, mode)
if not displayed:
# if we can’t display, we mark to sync what is not local
if not is_local(url) and not netcache.is_cache_valid(url):
self.get_list("to_fetch")
r = self.list_add_line("to_fetch", url=modedurl, verbose=False)
if r:
print("%s not available, marked for syncing" % url)
else:
print("%s already marked for syncing" % url)
else:
self.page_index = 0
# Update state (external files are not added to history)
self.current_url = modedurl
if update_hist and not self.sync_only:
self._update_history(modedurl)
else:
# we are asked not to handle or in sync_only mode
if self.support_http or parsed.scheme not in ["http", "https"]:
netcache.fetch(url, **params)
@needs_gi
def _show_lookup(self, offset=0, end=None, show_url=False):
for n, u in enumerate(self.get_renderer().get_links()[offset:end]):
index = n + offset + 1
line = "[%s] %s" % (index, u)
# TODO: implement proper listing of url (with protocol and show_url)
# protocol = "" if gi.scheme == "gemini" else " %s" % gi.scheme
# line = "[%d%s] %s" % (index, protocol, gi.name or gi.url)
# line += " (%s)" % gi.url
print(line)
def _update_history(self, url):
# We never update while in sync_only
# We don’t add history to itself.
if self.sync_only or not url or url == "list:///history":
return
# First, we call get_list to create history if needed
self.get_list("history")
links = self.list_get_links("history")
length = len(links)
# Don’t update history if we are back/forwarding through it
if length > 0 and links[self.hist_index] == url:
return
if length > self.options["history_size"]:
length = self.options["history_size"]
self.list_add_top(
"history",
limit=self.options["history_size"],
truncate_lines=self.hist_index,
)
self.hist_index = 0
# Cmd implementation follows
def default(self, line):
if line.strip() == "EOF":
return self.onecmd("quit")
elif line.startswith("/"):
return self.do_find(line[1:])
# Expand abbreviated commands
first_word = line.split()[0].strip()
if first_word in _ABBREVS:
full_cmd = _ABBREVS[first_word]
expanded = line.replace(first_word, full_cmd, 1)
return self.onecmd(expanded)
# Try to access it like an URL
if looks_like_url(line):
return self.do_go(line)
# Try to parse numerical index for lookup table
try:
n = int(line.strip())
except ValueError:
print("What?")
return
# if we have no url, there's nothing to do
if self.current_url is None:
print("No links to index")
return
else:
r = self.get_renderer()
if r:
url = r.get_link(n)
self._go_to_url(url)
else:
print("No page with links")
return
# Settings
def do_redirect(self, line):
"""Display and manage the list of redirected URLs. This features is mostly useful to use privacy-friendly frontends for popular websites."""
if len(line.split()) == 1:
if line in self.redirects:
print("%s is redirected to %s" % (line, self.redirects[line]))
else:
print("Please add a destination to redirect %s" % line)
elif len(line.split()) >= 2:
orig, dest = line.split(" ", 1)
if dest.lower() == "none":
if orig in self.redirects:
self.redirects.pop(orig)
print("Redirection for %s has been removed" % orig)
else:
print("%s was not redirected. Nothing has changed." % orig)
elif dest.lower() == "block":
self.redirects[orig] = "blocked"
print("%s will now be blocked" % orig)
else:
self.redirects[orig] = dest
print("%s will now be redirected to %s" % (orig, dest))
else:
toprint = "Current redirections:\n"
toprint += "--------------------\n"
for r in self.redirects:
toprint += "%s\t->\t%s\n" % (r, self.redirects[r])
toprint += '\nTo add new, use "redirect origine.com destination.org"'
toprint += '\nTo remove a redirect, use "redirect origine.com NONE"'
toprint += (
'\nTo completely block a website, use "redirect origine.com BLOCK"'
)
toprint += '\nTo block also subdomains, prefix with *: "redirect *origine.com BLOCK"'
print(toprint)
def do_set(self, line):
"""View or set various options."""
if not line.strip():
# Show all current settings
for option in sorted(self.options.keys()):
print("%s %s" % (option, self.options[option]))
elif len(line.split()) == 1:
# Show current value of one specific setting
option = line.strip()
if option in self.options:
print("%s %s" % (option, self.options[option]))
else:
print("Unrecognised option %s" % option)
else:
# Set value of one specific setting
option, value = line.split(" ", 1)
if option not in self.options:
print("Unrecognised option %s" % option)
return
# Validate / convert values
elif option == "tls_mode":
if value.lower() not in ("ca", "tofu"):
print("TLS mode must be `ca` or `tofu`!")
return
elif option == "accept_bad_ssl_certificates":
if value.lower() == "false":
print("Only high security certificates are now accepted")
elif value.lower() == "true":
print("Low security SSL certificates are now accepted")
else:
print("accept_bad_ssl_certificates should be True or False")
return
elif option == "width":
if value.isnumeric():
value = int(value)
print("changing width to ", value)
term_width(new_width=value)
else:
print("%s is not a valid width (integer required)" % value)
elif value.isnumeric():
value = int(value)
elif value.lower() == "false":
value = False
elif value.lower() == "true":
value = True
else:
try:
value = float(value)
except ValueError:
pass
self.options[option] = value
#We clean the cache for some options that affect rendering
if option in ["preformat_wrap","width"]:
self.opencache.cleanup()
def do_theme(self, line):
"""Change the colors of your rendered text.
"theme ELEMENT COLOR"
ELEMENT is one of: window_title, window_subtitle, title,
subtitle,subsubtitle,link,oneline_link,new_link,image_link,preformatted,blockquote.
COLOR is one or many (separated by space) of: bold, faint, italic, underline, black,
red, green, yellow, blue, purple, cyan, white.
Each color can alternatively be prefaced with "bright_"."""
words = line.split()
le = len(words)
if le == 0:
t = self.get_renderer("list:///").get_theme()
for e in t:
print("%s set to %s" % (e, t[e]))
else:
element = words[0]
if element not in offthemes.default.keys():
print("%s is not a valid theme element" % element)
print("Valid theme elements are: ")
valid = []
for k in offthemes.default:
valid.append(k)
print(valid)
return
else:
if le == 1:
if element in self.theme.keys():
value = self.theme[element]
else:
value = offthemes.default[element]
print("%s is set to %s" % (element, str(value)))
else:
# Now we parse the colors
toset = None
for w in words[1:]:
if w not in offthemes.colors.keys():
print("%s is not a valid color" % w)
print("Valid colors are one of: ")
valid = []
for k in offthemes.colors:
valid.append(k)
print(valid)
return
self.theme[element] = words[1:]
self.opencache.cleanup()
# now we update the prompt
if self.offline_only:
self.set_prompt("OFF")
else:
self.set_prompt("ON")
def do_handler(self, line):
"""View or set handler commands for different MIME types.
handler MIMETYPE : see handler for MIMETYPE
handler MIMETYPE CMD : set handler for MIMETYPE to CMD
in the CMD, %s will be replaced by the filename.
if no %s, it will be added at the end.
MIMETYPE can be the true mimetype or the file extension.
Examples:
handler application/pdf zathura %s
handler .odt lowriter
handler docx lowriter"""
if not line.strip():
# Show all current handlers
h = self.opencache.get_handlers()
for mime in sorted(h.keys()):
print("%s %s" % (mime, h[mime]))
elif len(line.split()) == 1:
mime = line.strip()
h = self.opencache.get_handlers(mime=mime)
if h:
print("%s %s" % (mime, h))
else:
print("No handler set for MIME type %s" % mime)
else:
mime, handler = line.split(" ", 1)
self.opencache.set_handler(mime, handler)
def do_alias(self, line):
"""Create or modifiy an alias
alias : show all existing aliases
alias ALIAS : show the command linked to ALIAS
alias ALIAS CMD : create or replace existing ALIAS to be linked to command CMD"""
#building the list of existing commands to avoid conflicts
commands = []
for name in self.get_names():
if name.startswith("do_"):
commands.append(name[3:])
if not line.strip():
header = "Command Aliases:"
self.stdout.write("\n{}\n".format(str(header)))
if self.ruler:
self.stdout.write("{}\n".format(str(self.ruler * len(header))))
for k, v in _ABBREVS.items():
self.stdout.write("{:<7} {}\n".format(k, v))
self.stdout.write("\n")
elif len(line.split()) == 1:
alias = line.strip()
if alias in commands:
print("%s is a command and cannot be aliased"%alias)
elif alias in _ABBREVS:
print("%s is currently aliased to \"%s\"" %(alias,_ABBREVS[alias]))
else:
print("there’s no alias for \"%s\""%alias)
else:
alias, cmd = line.split(None,1)
if alias in commands:
print("%s is a command and cannot be aliased"%alias)
else:
_ABBREVS[alias] = cmd
print("%s has been aliased to \"%s\""%(alias,cmd))
def do_offline(self, *args):
"""Use Offpunk offline by only accessing cached content"""
if self.offline_only:
print("Offline and undisturbed.")
else:
self.offline_only = True
self.set_prompt("OFF")
print("Offpunk is now offline and will only access cached content")
def do_online(self, *args):
"""Use Offpunk online with a direct connection"""
if self.offline_only:
self.offline_only = False
self.set_prompt("ON")
print("Offpunk is online and will access the network")
else:
print("Already online. Try offline.")
def do_copy(self, arg):
"""Copy the content of the last visited page as gemtext/html in the clipboard.
Use with "url" as argument to only copy the adress.
Use with "raw" to copy ANSI content as seen in your terminal (with colour codes).
Use with "cache" to copy the path of the cached content.
Use with "title" to copy the title of the page.
Use with "link" to copy a link in the gemtext format to that page with the title.
"""
if self.current_url:
args = arg.split()
if args and args[0] == "url":
if len(args) > 1 and args[1].isdecimal():
url = self.get_renderer().get_link(int(args[1]) - 1)
else:
url, mode = unmode_url(self.current_url)
print(url)
clipboard_copy(url)
elif args and args[0] == "raw":
tmp = self.opencache.get_temp_filename(self.current_url)
if tmp:
clipboard_copy(open(tmp, "rb"))
elif args and args[0] == "cache":
clipboard_copy(netcache.get_cache_path(self.current_url))
elif args and args[0] == "title":
title = self.get_renderer().get_page_title()
clipboard_copy(title)
print(title)
elif args and args[0] == "link":
link = "=> %s %s" % (
unmode_url(self.current_url)[0],
self.get_renderer().get_page_title(),
)
print(link)
clipboard_copy(link)
else:
clipboard_copy(open(netcache.get_cache_path(self.current_url), "rb"))
else:
print("No content to copy, visit a page first")
# Stuff for getting around
def do_go(self, line):
"""Go to a gemini URL or marked item."""
line = line.strip()
if not line:
clipboards = clipboard_paste()
urls = []
for u in clipboards:
if "://" in u and looks_like_url(u) and u not in urls:
urls.append(u)
if len(urls) > 1:
stri = "URLs in your clipboard\n"
counter = 0
for u in urls:
counter += 1
stri += "[%s] %s\n" % (counter, u)
stri += "Where do you want to go today ?> "
ans = input(stri)
if ans.isdigit() and 0 < int(ans) <= len(urls):
self.do_go(urls[int(ans) - 1])
elif len(urls) == 1:
self.do_go(urls[0])
else:
print("Go where? (hint: simply copy an URL in your clipboard)")
# First, check for possible marks
elif line in self.marks:
url = self.marks[line]
self._go_to_url(url)
# or a local file
elif os.path.exists(os.path.expanduser(line)):
self._go_to_url(line)
# If this isn't a mark, treat it as a URL
elif looks_like_url(line):
self._go_to_url(line)
elif (
"://" not in line
and "default_protocol" in self.options.keys()
and looks_like_url(self.options["default_protocol"] + "://" + line)
):
self._go_to_url(self.options["default_protocol"] + "://" + line)
else:
print("%s is not a valid URL to go" % line)
@needs_gi
def do_reload(self, *args):
"""Reload the current URL."""
if self.offline_only and not is_local(self.current_url):
self.get_list("to_fetch")
r = self.list_add_line("to_fetch", url=self.current_url, verbose=False)
if r:
print("%s marked for syncing" % self.current_url)
else:
print("%s already marked for syncing" % self.current_url)
else:
self.opencache.cleanup()
self._go_to_url(self.current_url, force_refresh=False)
@needs_gi
def do_up(self, *args):
"""Go up one directory in the path.
Take an integer as argument to go up multiple times."""
level = 1
if args[0].isnumeric():
level = int(args[0])
elif args[0] != "":
print("Up only take integer as arguments")
# TODO : implement up, this code is copy/pasted from GeminiItem
url, mode = unmode_url(self.current_url)
parsed = urllib.parse.urlparse(url)
path = parsed.path.rstrip("/")
count = 0
while count < level:
pathbits = list(os.path.split(path))
# Don't try to go higher than root or in config
if is_local(url) or len(pathbits) == 1:
break
# Get rid of bottom component
if len(pathbits) > 1:
pathbits.pop()
path = os.path.join(*pathbits)
count += 1
if parsed.scheme == "gopher":
path = "/1" + path
newurl = urllib.parse.urlunparse(
(parsed.scheme, parsed.netloc, path, "", "", "")
)
self._go_to_url(newurl)
def do_back(self, *args):
"""Go back to the previous gemini item."""
links = self.list_get_links("history")
if self.hist_index >= len(links) - 1:
return
self.hist_index += 1
url = links[self.hist_index]
self._go_to_url(url, update_hist=False)
def do_forward(self, *args):
"""Go forward to the next gemini item."""
links = self.list_get_links("history")
if self.hist_index <= 0:
return
self.hist_index -= 1
url = links[self.hist_index]
self._go_to_url(url, update_hist=False)
@needs_gi
def do_root(self, *args):
"""Go to root selector of the server hosting current item."""
parse = urllib.parse.urlparse(self.current_url)
self._go_to_url(
urllib.parse.urlunparse((parse.scheme, parse.netloc, "/", "", "", ""))
)
def do_tour(self, line):
"""Add index items as waypoints on a tour, which is basically a FIFO
queue of gemini items.
`tour` or `t` alone brings you to the next item in your tour.
Items can be added with `tour 1 2 3 4` or ranges like `tour 1-4`.
All items in current menu can be added with `tour *`.
All items in $LIST can be added with `tour $LIST`.
Current item can be added back to the end of the tour with `tour .`.
Current tour can be listed with `tour ls` and scrubbed with `tour clear`."""
# Creating the tour list if needed
self.get_list("tour")
line = line.strip()
if not line:
# Fly to next waypoint on tour
if len(self.list_get_links("tour")) < 1:
print("End of tour.")
else:
url = self.list_go_to_line("1", "tour")
if url:
self.list_rm_url(url, "tour")
elif line == "ls":
self.list_show("tour")
elif line == "clear":
for l in self.list_get_links("tour"):
self.list_rm_url(l, "tour")
elif line == "*":
for l in self.get_renderer().get_links():
self.list_add_line("tour", url=l, verbose=False)
elif line == ".":
self.list_add_line("tour", verbose=False)
elif looks_like_url(line):
self.list_add_line("tour", url=line)
elif line in self.list_lists():
list_path = self.list_path(line)
if not list_path:
print("List %s does not exist. Cannot add it to tour" % (list))
else:
url = "list:///%s" % line
for l in self.get_renderer(url).get_links():
self.list_add_line("tour", url=l, verbose=False)
elif self.current_url:
for index in line.split():
try:
pair = index.split("-")
if len(pair) == 1:
# Just a single index
n = int(index)
url = self.get_renderer().get_link(n)
self.list_add_line("tour", url=url, verbose=False)
elif len(pair) == 2:
# Two endpoints for a range of indices
if int(pair[0]) < int(pair[1]):
for n in range(int(pair[0]), int(pair[1]) + 1):
url = self.get_renderer().get_link(n)
self.list_add_line("tour", url=url, verbose=False)
else:
for n in range(int(pair[0]), int(pair[1]) - 1, -1):
url = self.get_renderer().get_link(n)
self.list_add_line("tour", url=url, verbose=False)
else:
# Syntax error
print("Invalid use of range syntax %s, skipping" % index)
except ValueError:
print("Non-numeric index %s, skipping." % index)
except IndexError:
print("Invalid index %d, skipping." % n)
@needs_gi
def do_certs(self, line) -> None:
"""Manage your client certificates (identities) for a site.
`certs` will display all valid certificates for the current site
`certs new ` will create a new certificate, if no url is specified, the current open site will be used.
"""
line = line.strip()
if not line:
certs = netcache.get_certs(self.current_url)
if len(certs) == 0:
print("There are no certificates available for this site.")
else:
if len(certs) == 1:
print("The one available certificate for this site is:")
else:
print(
"The", len(certs), "available certificates for this site are:"
)
print(*certs)
print("Use the 'id@site.net' notation to activate a certificate.")
else:
lineparts = line.split(" ")
if lineparts[0] == "new":
if len(lineparts) == 4:
name = lineparts[1]
days = lineparts[2]
site = lineparts[3]
netcache.create_certificate(name, int(days), site)
elif len(lineparts) == 3:
name = lineparts[1]
days = lineparts[2]
site = urllib.parse.urlparse(self.current_url)
netcache.create_certificate(name, int(days), site.hostname)
else:
print("usage")
@needs_gi
def do_mark(self, line):
"""Mark the current item with a single letter. This letter can then
be passed to the 'go' command to return to the current item later.
Think of it like marks in vi: 'mark a'='ma' and 'go a'=''a'.
Marks are temporary until shutdown (not saved to disk)."""
line = line.strip()
if not line:
for mark, gi in self.marks.items():
print("[%s] %s (%s)" % (mark, gi.name, gi.url))
elif line.isalpha() and len(line) == 1:
self.marks[line] = self.current_url
else:
print("Invalid mark, must be one letter")
@needs_gi
def do_info(self, line):
"""Display information about current page."""
renderer = self.get_renderer()
url, mode = unmode_url(self.current_url)
out = renderer.get_page_title() + "\n\n"
out += "URL : " + url + "\n"
out += "Mime : " + renderer.get_mime() + "\n"
out += "Cache : " + netcache.get_cache_path(url) + "\n"
if self.get_renderer():
rend = str(self.get_renderer().__class__)
rend = rend.lstrip("")
else:
rend = "None"
out += "Renderer : " + rend + "\n\n"
lists = []
for l in self.list_lists():
if self.list_has_url(url, l):
lists.append(l)
if len(lists) > 0:
out += "Page appeard in following lists :\n"
for l in lists:
if not self.list_is_system(l):
status = "normal list"
if self.list_is_subscribed(l):
status = "subscription"
elif self.list_is_frozen(l):
status = "frozen list"
out += " • %s\t(%s)\n" % (l, status)
for l in lists:
if self.list_is_system(l):
out += " • %s\n" % l
else:
out += "Page is not save in any list"
print(out)
def do_version(self, line):
"""Display version and system information."""
def has(value):
if value:
return "\t\x1b[1;32mInstalled\x1b[0m\n"
else:
return "\t\x1b[1;31mNot Installed\x1b[0m\n"
output = "Offpunk " + __version__ + "\n"
output += "===========\n"
output += "System: " + sys.platform + "\n"
output += "Python: " + sys.version + "\n"
output += "\nHighly recommended:\n"
output += " - python-cryptography : " + has(netcache._HAS_CRYPTOGRAPHY)
output += " - xdg-open : " + has(opnk._HAS_XDGOPEN)
output += "\nWeb browsing:\n"
output += " - python-requests : " + has(netcache._DO_HTTP)
output += " - python-feedparser : " + has(ansicat._DO_FEED)
output += " - python-bs4 : " + has(ansicat._HAS_SOUP)
output += " - python-readability : " + has(ansicat._HAS_READABILITY)
output += " - timg 1.3.2+ : " + has(ansicat._HAS_TIMG)
output += " - chafa 1.10+ : " + has(ansicat._HAS_CHAFA)
output += "\nNice to have:\n"
output += " - python-setproctitle : " + has(_HAS_SETPROCTITLE)
clip_support = shutil.which("xsel") or shutil.which("xclip")
output += " - X11 clipboard (xsel or xclip) : " + has(clip_support)
output += " - Wayland clipboard (wl-clipboard): " + has(shutil.which("wl-copy"))
output += "\nFeatures :\n"
output += " - Render images (chafa or timg) : " + has(
ansicat._RENDER_IMAGE
)
output += " - Render HTML (bs4, readability) : " + has(
ansicat._DO_HTML
)
output += " - Render Atom/RSS feeds (feedparser) : " + has(
ansicat._DO_FEED
)
output += " - Connect to http/https (requests) : " + has(
netcache._DO_HTTP
)
output += " - Detect text encoding (python-chardet) : " + has(
netcache._HAS_CHARDET
)
output += " - restore last position (less 572+) : " + has(
opnk._LESS_RESTORE_POSITION
)
output += "\n"
output += "Config directory : " + xdg("config") + "\n"
output += "User Data directory : " + xdg("data") + "\n"
output += "Cache directoy : " + xdg("cache")
print(output)
# Stuff that modifies the lookup table
def do_ls(self, line):
"""List contents of current index.
Use 'ls -l' to see URLs."""
self._show_lookup(show_url="-l" in line)
self.page_index = 0
def do_search(self, line):
"""Search on Gemini using the engine configured (by default kennedy.gemi.dev)
You can configure it using "set search URL".
URL should contains one "%s" that will be replaced by the search term."""
search = urllib.parse.quote(line)
url = self.options["search"] % search
self._go_to_url(url)
def do_wikipedia(self, line):
"""Search on wikipedia using the configured Gemini interface.
The first word should be the two letters code for the language.
Exemple : "wikipedia en Gemini protocol"
But you can also use abbreviations to go faster:
"wen Gemini protocol". (your abbreviation might be missing, report the bug)
The interface used can be modified with the command:
"set wikipedia URL" where URL should contains two "%s", the first
one used for the language, the second for the search string."""
words = line.split(" ", maxsplit=1)
if len(words[0]) == 2:
lang = words[0]
search = urllib.parse.quote(words[1])
else:
lang = "en"
search = urllib.parse.quote(line)
url = self.options["wikipedia"] % (lang, search)
self._go_to_url(url)
def do_xkcd(self,line):
"""Open the specified XKCD comics (a number is required as parameter)"""
words = line.split(" ")
if len(words) > 0 and words[0].isalnum():
self._go_to_url("https://xkcd.com/%s"%words[0])
else:
print("Please enter the number of the XKCD comic you want to see")
def do_gus(self, line):
"""Submit a search query to the geminispace.info search engine."""
if not line:
print("What?")
return
search = line.replace(" ", "%20")
self._go_to_url("gemini://geminispace.info/search?%s" % search)
def do_history(self, *args):
"""Display history."""
self.list_show("history")
@needs_gi
def do_find(self, searchterm):
"""Find in current page by displaying only relevant lines (grep)."""
self._go_to_url(self.current_url, update_hist=False, grep=searchterm)
def emptyline(self):
"""Page through index ten lines at a time."""
i = self.page_index
if not self.current_url or i > len(self.get_renderer().get_links()):
return
self._show_lookup(offset=i, end=i + 10)
self.page_index += 10
@needs_gi
def do_feed(self, *args):
"""Display RSS or Atom feeds linked to the current page."""
subs = self.get_renderer().get_subscribe_links()
# No feed found
if len(subs) == 1:
if "rss" in subs[0][1] or "atom" in subs[0][1]:
print("Current page is already a feed")
else:
print("No feed found on current page")
# Multiple feeds found
elif len(subs) > 2:
stri = "Available feeds :\n"
counter = 0
for s in subs:
counter += 1
stri += "[%s] %s [%s]\n" % (counter, s[0], s[1])
stri += "Which view do you want to see ? >"
ans = input(stri)
if ans.isdigit() and 0 < int(ans) <= len(subs):
self.do_go(subs[int(ans) - 1][0])
# Only one feed found
else:
self.do_go(subs[1][0])
@needs_gi
def do_view(self, *args):
"""Run most recently visited item through "less" command, restoring \
previous position.
Use "view normal" to see the default article view on html page.
Use "view full" to see a complete html page instead of the article view.
Use "view XX" where XX is a number to view information about link XX.
(full, feed, feeds have no effect on non-html content)."""
if self.current_url and args and args[0] != "":
u, m = unmode_url(self.current_url)
if args[0] in ["full", "debug", "source"]:
self._go_to_url(self.current_url, mode=args[0])
elif args[0] in ["normal", "readable"]:
self._go_to_url(self.current_url, mode="readable")
elif args[0] == "feed":
print("view feed is deprecated. Use the command feed directly")
self.do_feed()
elif args[0].isdigit():
link_url = self.get_renderer().get_link(int(args[0]))
if link_url:
print("Link %s is: %s" % (args[0], link_url))
if netcache.is_cache_valid(link_url):
last_modified = netcache.cache_last_modified(link_url)
link_renderer = self.get_renderer(link_url)
if link_renderer:
link_title = link_renderer.get_page_title()
print(link_title)
else:
print("Empty cached version")
print("Last cached on %s" % time.ctime(last_modified))
else:
print("No cached version for this link")
else:
print(
"Valid argument for view are : normal, full, source or a number"
)
else:
self._go_to_url(self.current_url)
@needs_gi
def do_open(self, *args):
"""Open current item with the configured handler or xdg-open.
Use "open url" to open current URL in a browser.
Use "open 2 4" to open links 2 and 4
You can combine with "open url 2 4" to open URL of links
see "handler" command to set your handler."""
# do we open the URL (true) or the cached file (false)
url_list = []
urlmode = False
arglist = args[0].split()
if len(arglist) > 0 and arglist[0] == "url":
arglist.pop(0)
urlmode = True
if len(arglist) > 0:
# we try to match each argument with a link
for a in arglist:
try:
n = int(a)
u = self.get_renderer().get_link(n)
url_list.append(u)
except ValueError:
print("Non-numeric index %s, skipping." % a)
except IndexError:
print("Invalid index %d, skipping." % n)
else:
# if no argument, we use current url
u, m = unmode_url(self.current_url)
url_list.append(u)
for u in url_list:
if urlmode:
run("xdg-open %s", parameter=u, direct_output=True)
else:
self.opencache.opnk(u, terminal=False)
def do_shell(self, line):
"""Send the content of the current page to the shell and pipe it.
You are supposed to write what will come after the pipe. For example,
if you want to count the number of lines containing STRING in the
current page:
> shell grep STRING|wc -l
'!' is an useful shortcut.
> !grep STRING|wc -l
"""
# input is used if we wand to send something else than current page
# to the shell
tmp = None
if self.current_url:
tmp = self.opencache.get_temp_filename(self.current_url)
if tmp:
input = open(tmp, "rb")
run(line, input=input, direct_output=True)
else:
run(line,direct_output=True)
@needs_gi
def do_save(self, line):
"""Save an item to the filesystem.
'save n filename' saves menu item n to the specified filename.
'save filename' saves the last viewed item to the specified filename.
'save n' saves menu item n to an automagic filename."""
args = line.strip().split()
# First things first, figure out what our arguments are
if len(args) == 0:
# No arguments given at all
# Save current item, if there is one, to a file whose name is
# inferred from the gemini path
if not netcache.is_cache_valid(self.current_url):
print("You cannot save if not cached!")
return
else:
index = None
filename = None
elif len(args) == 1:
# One argument given
# If it's numeric, treat it as an index, and infer the filename
try:
index = int(args[0])
filename = None
# If it's not numeric, treat it as a filename and
# save the current item
except ValueError:
index = None
filename = os.path.expanduser(args[0])
elif len(args) == 2:
# Two arguments given
# Treat first as an index and second as filename
index, filename = args
try:
index = int(index)
except ValueError:
print("First argument is not a valid item index!")
return
filename = os.path.expanduser(filename)
else:
print("You must provide an index, a filename, or both.")
return
# Next, fetch the item to save, if it's not the current one.
if index:
last_url = self.current_url
try:
url = self.get_renderer().get_link(index)
self._go_to_url(url, update_hist=False, handle=False)
except IndexError:
print("Index too high!")
self.current_url = last_url
return
else:
url = self.current_url
# Derive filename from current GI's path, if one hasn't been set
if not filename:
filename = os.path.basename(netcache.get_cache_path(self.current_url))
# Check for filename collisions and actually do the save if safe
if os.path.exists(filename):
print("File %s already exists!" % filename)
else:
# Don't use _get_active_tmpfile() here, because we want to save the
# "source code" of menus, not the rendered view - this way Offpunk
# can navigate to it later.
path = netcache.get_cache_path(url)
if os.path.isdir(path):
print("Can’t save %s because it’s a folder, not a file" % path)
else:
print("Saved to %s" % filename)
shutil.copyfile(path, filename)
# Restore gi if necessary
if index is not None:
self._go_to_url(last_url, handle=False)
@needs_gi
def do_url(self, args):
"""Print the url of the current page.
Use "url XX" where XX is a number to print the url of link XX.
"url" can also be piped to the shell, using the pipe "|"
"""
splitted = args.split("|",maxsplit=1)
url = None
final_url = None
if splitted[0].strip().isdigit():
link_id = int(splitted[0])
link_url = self.get_renderer().get_link(link_id)
if link_url:
url = link_url
else:
url = self.current_url
if url:
final_url, mode = unmode_url(url)
print(final_url)
if final_url and len(splitted) > 1:
run(splitted[1], input=final_url, direct_output=True)
# Bookmarking stuff
@needs_gi
def do_add(self, line):
"""Add the current URL to the list specified as argument.
If no argument given, URL is added to Bookmarks.
You can pass a link number as the second argument to add the link.
"add $LIST XX" will add link number XX to $LIST
"""
args = line.split()
if len(args) < 1:
list = "bookmarks"
if not self.list_path(list):
self.list_create(list)
self.list_add_line(list)
elif len(args) > 1 and args[1].isdigit():
link_id = int(args[1])
link_url = self.get_renderer().get_link(link_id)
if link_url:
self.list_add_line(args[0],url=link_url)
else:
self.list_add_line(args[0])
# Get the list file name, creating or migrating it if needed.
# Migrate bookmarks/tour/to_fetch from XDG_CONFIG to XDG_DATA
# We migrate only if the file exists in XDG_CONFIG and not XDG_DATA
def get_list(self, list):
list_path = self.list_path(list)
if not list_path:
old_file_gmi = os.path.join(xdg("config"), list + ".gmi")
old_file_nogmi = os.path.join(xdg("config"), list)
target = os.path.join(xdg("data"), "lists")
if os.path.exists(old_file_gmi):
shutil.move(old_file_gmi, target)
elif os.path.exists(old_file_nogmi):
targetgmi = os.path.join(target, list + ".gmi")
shutil.move(old_file_nogmi, targetgmi)
else:
if list == "subscribed":
title = "Subscriptions #subscribed (new links in those pages will be added to tour)"
elif list == "to_fetch":
title = "Links requested and to be fetched during the next --sync"
else:
title = None
self.list_create(list, title=title, quite=True)
list_path = self.list_path(list)
return list_path
@needs_gi
def do_subscribe(self, line):
"""Subscribe to current page by saving it in the "subscribed" list.
If a new link is found in the page during a --sync, the new link is automatically
fetched and added to your next tour.
To unsubscribe, remove the page from the "subscribed" list."""
subs = self.get_renderer().get_subscribe_links()
if len(subs) > 1:
stri = "Multiple feeds have been found :\n"
elif "rss" in subs[0][1] or "atom" in subs[0][1]:
stri = "This page is already a feed:\n"
else:
stri = "No feed detected. You can still watch the page :\n"
counter = 0
for l in subs:
link = l[0]
already = []
for li in self.list_lists():
if self.list_is_subscribed(li):
if self.list_has_url(link, li):
already.append(li)
stri += "[%s] %s [%s]\n" % (counter + 1, link, l[1])
if len(already) > 0:
stri += "\t -> (already subscribed through lists %s)\n" % (str(already))
counter += 1
stri += "\n"
stri += "Which feed do you want to subscribe ? > "
ans = input(stri)
if ans.isdigit() and 0 < int(ans) <= len(subs):
sublink, mime, title = subs[int(ans) - 1]
else:
sublink = None
if sublink:
added = self.list_add_line("subscribed", url=sublink, verbose=False)
if added:
print("Subscribed to %s" % sublink)
else:
print("You are already subscribed to %s" % sublink)
else:
print("No subscription registered")
def do_bookmarks(self, line):
"""Show or access the bookmarks menu.
'bookmarks' shows all bookmarks.
'bookmarks n' navigates immediately to item n in the bookmark menu.
Bookmarks are stored using the 'add' command."""
args = line.strip()
if len(args.split()) > 1 or (args and not args.isnumeric()):
print("bookmarks command takes a single integer argument!")
elif args:
self.list_go_to_line(args, "bookmarks")
else:
self.list_show("bookmarks")
@needs_gi
def do_archive(self, args):
"""Archive current page by removing it from every list and adding it to
archives, which is a special historical list limited in size. It is similar to `move archives`."""
u, m = unmode_url(self.current_url)
for li in self.list_lists():
if li not in ["archives", "history"]:
deleted = self.list_rm_url(u, li)
if deleted:
print("Removed from %s" % li)
self.list_add_top("archives", limit=self.options["archives_size"])
r = self.get_renderer()
title = r.get_page_title()
print("Archiving: %s" % title)
print(
"\x1b[2;34mCurrent maximum size of archives : %s\x1b[0m"
% self.options["archives_size"]
)
# what is the line to add to a list for this url ?
def to_map_line(self, url=None):
if not url:
url = self.current_url
r = self.get_renderer(url)
if r:
title = r.get_page_title()
else:
title = ""
toreturn = "=> {} {}\n".format(url, title)
return toreturn
def list_add_line(self, list, url=None, verbose=True):
list_path = self.list_path(list)
if not list_path and self.list_is_system(list):
self.list_create(list, quite=True)
list_path = self.list_path(list)
if not list_path:
print(
"List %s does not exist. Create it with "
"list create %s"
"" % (list, list)
)
return False
else:
if not url:
url = self.current_url
unmoded_url, mode = unmode_url(url)
# first we check if url already exists in the file
if self.list_has_url(url, list, exact_mode=True):
if verbose:
print("%s already in %s." % (url, list))
return False
# If the URL already exists but without a mode, we update the mode
# FIXME: this doesn’t take into account the case where you want to remove the mode
elif url != unmoded_url and self.list_has_url(unmoded_url, list):
self.list_update_url_mode(unmoded_url, list, mode)
if verbose:
print("%s has updated mode in %s to %s" % (url, list, mode))
else:
with open(list_path, "a") as l_file:
l_file.write(self.to_map_line(url))
l_file.close()
if verbose:
print("%s added to %s" % (url, list))
return True
@needs_gi
def list_add_top(self, list, limit=0, truncate_lines=0):
stri = self.to_map_line().strip("\n")
if list == "archives":
stri += ", archived on "
elif list == "history":
stri += ", visited on "
else:
stri += ", added to %s on " % list
stri += time.ctime() + "\n"
list_path = self.get_list(list)
with open(list_path, "r") as l_file:
lines = l_file.readlines()
l_file.close()
with open(list_path, "w") as l_file:
l_file.write("#%s\n" % list)
l_file.write(stri)
counter = 0
# Truncating is useful in case we open a new branch
# after a few back in history
to_truncate = truncate_lines
for l in lines:
if not l.startswith("#"):
if to_truncate > 0:
to_truncate -= 1
elif limit == 0 or counter < limit:
l_file.write(l)
counter += 1
l_file.close()
# remove an url from a list.
# return True if the URL was removed
# return False if the URL was not found
def list_rm_url(self, url, list):
return self.list_has_url(url, list, deletion=True)
def list_update_url_mode(self, url, list, mode):
return self.list_has_url(url, list, update_mode=mode)
# deletion and has_url are so similar, I made them the same method
# deletion : true or false if you want to delete the URL
# exact_mode : True if you want to check only for the exact url, not the canonical one
# update_mode : a new mode to update the URL
def list_has_url(
self, url, list, deletion=False, exact_mode=False, update_mode=None
):
list_path = self.list_path(list)
if list_path:
to_return = False
with open(list_path, "r") as lf:
lines = lf.readlines()
lf.close()
to_write = []
# let’s remove the mode
if not exact_mode:
url = unmode_url(url)[0]
for l in lines:
# we separate components of the line
# to ensure we identify a complete URL, not a part of it
splitted = l.split()
if url not in splitted and len(splitted) > 1:
current = unmode_url(splitted[1])[0]
# sometimes, we must remove the ending "/"
if url == current or (url.endswith("/") and url[:-1] == current):
to_return = True
if update_mode:
new_line = l.replace(current, mode_url(url, update_mode))
to_write.append(new_line)
elif not deletion:
to_write.append(l)
else:
to_write.append(l)
elif url in splitted:
to_return = True
# We update the mode if asked by replacing the old url
# by a moded one in the same line
if update_mode:
new_line = l.replace(url, mode_url(url, update_mode))
to_write.append(new_line)
elif not deletion:
to_write.append(l)
else:
to_write.append(l)
if deletion or update_mode:
with open(list_path, "w") as lf:
for l in to_write:
lf.write(l)
lf.close()
return to_return
else:
return False
def list_get_links(self, list):
list_path = self.list_path(list)
if list_path and os.path.exists(list_path):
return self.get_renderer("list:///%s" % list).get_links()
else:
return []
def list_go_to_line(self, line, list):
list_path = self.list_path(list)
if not list_path:
print(
"List %s does not exist. Create it with "
"list create %s"
"" % (list, list)
)
elif not line.isnumeric():
print("go_to_line requires a number as parameter")
else:
r = self.get_renderer("list:///%s" % list)
url = r.get_link(int(line))
display = not self.sync_only
if url:
self._go_to_url(url, handle=display)
return url
def list_show(self, list):
list_path = self.list_path(list)
if not list_path:
print(
"List %s does not exist. Create it with "
"list create %s"
"" % (list, list)
)
else:
url = "list:///%s" % list
display = not self.sync_only
self._go_to_url(url, handle=display)
# return the path of the list file if list exists.
# return None if the list doesn’t exist.
def list_path(self, list):
listdir = os.path.join(xdg("data"), "lists")
list_path = os.path.join(listdir, "%s.gmi" % list)
if os.path.exists(list_path):
return list_path
else:
return None
def list_create(self, list, title=None, quite=False):
list_path = self.list_path(list)
if list in ["create", "edit", "delete", "help"]:
print("%s is not allowed as a name for a list" % list)
elif not list_path:
listdir = os.path.join(xdg("data"), "lists")
os.makedirs(listdir, exist_ok=True)
list_path = os.path.join(listdir, "%s.gmi" % list)
with open(list_path, "a") as lfile:
if title:
lfile.write("# %s\n" % title)
else:
lfile.write("# %s\n" % list)
lfile.close()
if not quite:
print("list created. Display with `list %s`" % list)
else:
print("list %s already exists" % list)
def do_move(self, arg):
"""move LIST will add the current page to the list LIST.
With a major twist: current page will be removed from all other lists.
If current page was not in a list, this command is similar to `add LIST`."""
if not arg:
print("LIST argument is required as the target for your move")
elif arg[0] == "archives":
self.do_archive()
else:
args = arg.split()
list_path = self.list_path(args[0])
if not list_path:
print("%s is not a list, aborting the move" % args[0])
else:
lists = self.list_lists()
for l in lists:
if l != args[0] and l not in ["archives", "history"]:
url, mode = unmode_url(self.current_url)
isremoved = self.list_rm_url(url, l)
if isremoved:
print("Removed from %s" % l)
self.list_add_line(args[0])
def list_lists(self):
listdir = os.path.join(xdg("data"), "lists")
to_return = []
if os.path.exists(listdir):
lists = os.listdir(listdir)
if len(lists) > 0:
for l in lists:
# removing the .gmi at the end of the name
to_return.append(l[:-4])
return to_return
def list_has_status(self, list, status):
path = self.list_path(list)
toreturn = False
if path:
with open(path) as f:
line = f.readline().strip()
f.close()
if line.startswith("#") and status in line:
toreturn = True
return toreturn
def list_is_subscribed(self, list):
return self.list_has_status(list, "#subscribed")
def list_is_frozen(self, list):
return self.list_has_status(list, "#frozen")
def list_is_system(self, list):
return list in ["history", "to_fetch", "archives", "tour"]
# This modify the status of a list to one of :
# normal, frozen, subscribed
# action is either #frozen, #subscribed or None
def list_modify(self, list, action=None):
path = self.list_path(list)
with open(path) as f:
lines = f.readlines()
f.close()
if lines[0].strip().startswith("#"):
first_line = lines.pop(0).strip("\n")
else:
first_line = "# %s " % list
first_line = first_line.replace("#subscribed", "").replace("#frozen", "")
if action:
first_line += " " + action
print("List %s has been marked as %s" % (list, action))
else:
print("List %s is now a normal list" % list)
first_line += "\n"
lines.insert(0, first_line)
with open(path, "w") as f:
for line in lines:
f.write(line)
f.close()
def do_list(self, arg):
"""Manage list of bookmarked pages.
- list : display available lists
- list $LIST : display pages in $LIST
- list create $NEWLIST : create a new list
- list edit $LIST : edit the list
- list subscribe $LIST : during sync, add new links found in listed pages to tour
- list freeze $LIST : don’t update pages in list during sync if a cache already exists
- list normal $LIST : update pages in list during sync but don’t add anything to tour
- list delete $LIST : delete a list permanently (a confirmation is required)
- list help : print this help
See also :
- add $LIST (to add current page to $LIST or, by default, to bookmarks)
- move $LIST (to add current page to list while removing from all others)
- archive (to remove current page from all lists while adding to archives)
There’s no "delete" on purpose. The use of "archive" is recommended.
The following lists cannot be removed or frozen but can be edited with "list edit"
- list archives : contains last 200 archived URLs
- history : contains last 200 visisted URLs
- to_fetch : contains URLs that will be fetch during the next sync
- tour : contains the next URLs to visit during a tour (see "help tour")
"""
listdir = os.path.join(xdg("data"), "lists")
os.makedirs(listdir, exist_ok=True)
if not arg:
lists = self.list_lists()
if len(lists) > 0:
lurl = "list:///"
self._go_to_url(lurl)
else:
print("No lists yet. Use `list create`")
else:
args = arg.split()
if args[0] == "create":
if len(args) > 2:
name = " ".join(args[2:])
self.list_create(args[1].lower(), title=name)
elif len(args) == 2:
self.list_create(args[1].lower())
else:
print(
"A name is required to create a new list. Use `list create NAME`"
)
elif args[0] == "edit":
editor = None
if "editor" in self.options and self.options["editor"]:
editor = self.options["editor"]
elif os.environ.get("VISUAL"):
editor = os.environ.get("VISUAL")
elif os.environ.get("EDITOR"):
editor = os.environ.get("EDITOR")
if editor:
if len(args) > 1 and args[1] in self.list_lists():
path = os.path.join(listdir, args[1] + ".gmi")
try:
# Note that we intentionally don't quote the editor.
# In the unlikely case `editor` includes a percent
# sign, we also escape it for the %-formatting.
cmd = editor.replace("%", "%%") + " %s"
run(cmd, parameter=path, direct_output=True)
except Exception as err:
print(err)
print('Please set a valid editor with "set editor"')
else:
print("A valid list name is required to edit a list")
else:
print("No valid editor has been found.")
print(
"You can use the following command to set your favourite editor:"
)
print("set editor EDITOR")
print("or use the $VISUAL or $EDITOR environment variables.")
elif args[0] == "delete":
if len(args) > 1:
if self.list_is_system(args[1]):
print("%s is a system list which cannot be deleted" % args[1])
elif args[1] in self.list_lists():
size = len(self.list_get_links(args[1]))
stri = "Are you sure you want to delete %s ?\n" % args[1]
confirm = "YES"
if size > 0:
stri += "! %s items in the list will be lost !\n" % size
confirm = "YES DELETE %s" % size
else:
stri += (
"The list is empty, it should be safe to delete it.\n"
)
stri += (
'Type "%s" (in capital, without quotes) to confirm :'
% confirm
)
answer = input(stri)
if answer == confirm:
path = os.path.join(listdir, args[1] + ".gmi")
os.remove(path)
print("* * * %s has been deleted" % args[1])
else:
print("A valid list name is required to be deleted")
else:
print("A valid list name is required to be deleted")
elif args[0] in ["subscribe", "freeze", "normal"]:
if len(args) > 1:
if self.list_is_system(args[1]):
print("You cannot modify %s which is a system list" % args[1])
elif args[1] in self.list_lists():
if args[0] == "subscribe":
action = "#subscribed"
elif args[0] == "freeze":
action = "#frozen"
else:
action = None
self.list_modify(args[1], action=action)
else:
print("A valid list name is required after %s" % args[0])
elif args[0] == "help":
self.onecmd("help list")
elif len(args) == 1:
self.list_show(args[0].lower())
else:
self.list_go_to_line(args[1], args[0].lower())
def do_help(self, arg):
"""ALARM! Recursion detected! ALARM! Prepare to eject!"""
if arg == "!":
print("! is an alias for 'shell'")
elif arg == "?":
print("? is an alias for 'help'")
elif arg in _ABBREVS:
full_cmd = _ABBREVS[arg]
print("%s is an alias for '%s'" % (arg, full_cmd))
print("See the list of aliases with 'abbrevs'")
print("'help %s':" % full_cmd)
cmd.Cmd.do_help(self, full_cmd)
else:
cmd.Cmd.do_help(self, arg)
def do_tutorial(self, arg):
"""Access the offpunk.net tutorial (online)"""
self._go_to_url("gemini://offpunk.net/firststeps.gmi")
def do_sync(self, line):
"""Synchronize all bookmarks lists and URLs from the to_fetch list.
- New elements in pages in subscribed lists will be added to tour
- Elements in list to_fetch will be retrieved and added to tour
- Normal lists will be synchronized and updated
- Frozen lists will be fetched only if not present.
Before a sync, you can edit the list of URLs that will be fetched with the
following command: "list edit to_fetch"
Argument : duration of cache validity (in seconds)."""
if self.offline_only:
print("Sync can only be achieved online. Change status with `online`.")
return
args = line.split()
if len(args) > 0:
if not args[0].isdigit():
print("sync argument should be the cache validity expressed in seconds")
return
else:
validity = int(args[0])
else:
validity = 0
self.call_sync(refresh_time=validity)
def call_sync(self, refresh_time=0, depth=1, lists=None):
# fetch_url is the core of the sync algorithm.
# It takes as input :
# - an URL to be fetched
# - depth : the degree of recursion to build the cache (0 means no recursion)
# - validity : the age, in seconds, existing caches need to have before
# being refreshed (0 = never refreshed if it already exists)
# - savetotour : if True, newly cached items are added to tour
def add_to_tour(url):
if url and netcache.is_cache_valid(url):
toprint = " -> adding to tour: %s" % url
width = term_width() - 1
toprint = toprint[:width]
toprint += " " * (width - len(toprint))
print(toprint)
self.list_add_line("tour", url=url, verbose=False)
return True
else:
return False
def fetch_url(
url, depth=0, validity=0, savetotour=False, count=[0, 0], strin="",
force_large_download=False
):
# savetotour = True will save to tour newly cached content
# else, do not save to tour
# regardless of valitidy
if not url:
return
if not netcache.is_cache_valid(url, validity=validity):
if strin != "":
endline = "\r"
else:
endline = None
# Did we already had a cache (even an old one) ?
isnew = not netcache.is_cache_valid(url)
toprint = "%s [%s/%s] Fetch " % (strin, count[0], count[1]) + url
width = term_width() - 1
toprint = toprint[:width]
toprint += " " * (width - len(toprint))
print(toprint, end=endline)
# If not saving to tour, then we should limit download size
limit = not savetotour
self._go_to_url(url, update_hist=False, limit_size=limit,\
force_large_download=force_large_download)
if savetotour and isnew and netcache.is_cache_valid(url):
# we add to the next tour only if we managed to cache
# the ressource
add_to_tour(url)
# Now, recursive call, even if we didn’t refresh the cache
# This recursive call is impacting performances a lot but is needed
# For the case when you add a address to a list to read later
# You then expect the links to be loaded during next refresh, even
# if the link itself is fresh enough
# see fetch_list()
if depth > 0:
# we should only savetotour at the first level of recursion
# The code for this was removed so, currently, we savetotour
# at every level of recursion.
r = self.get_renderer(url)
url, oldmode = unmode_url(url)
if oldmode == "full":
mode = "full_links_only"
else:
mode = "links_only"
if r:
links = r.get_links(mode=mode)
subcount = [0, len(links)]
d = depth - 1
for k in links:
# recursive call (validity is always 0 in recursion)
substri = strin + " -->"
subcount[0] += 1
fetch_url(
k,
depth=d,
validity=0,
savetotour=savetotour,
count=subcount,
strin=substri,
)
def fetch_list(
list, validity=0, depth=1, tourandremove=False, tourchildren=False,
force_large_download=False
):
links = self.list_get_links(list)
end = len(links)
counter = 0
print(" * * * %s to fetch in %s * * *" % (end, list))
for l in links:
counter += 1
# If cache for a link is newer than the list
fetch_url(
l,
depth=depth,
validity=validity,
savetotour=tourchildren,
count=[counter, end],
force_large_download=force_large_download
)
if tourandremove:
if add_to_tour(l):
self.list_rm_url(l, list)
self.sync_only = True
if not lists:
lists = self.list_lists()
# We will fetch all the lists except "archives" and "history"
# We keep tour for the last round
subscriptions = []
normal_lists = []
fridge = []
for l in lists:
# only try existing lists
if l in self.list_lists():
if not self.list_is_system(l):
if self.list_is_frozen(l):
fridge.append(l)
elif self.list_is_subscribed(l):
subscriptions.append(l)
else:
normal_lists.append(l)
# We start with the "subscribed" as we need to find new items
starttime = int(time.time())
for l in subscriptions:
fetch_list(l, validity=refresh_time, depth=depth, tourchildren=True)
# Then the to_fetch list (item are removed from the list after fetch)
# We fetch regarless of the refresh_time
if "to_fetch" in lists:
nowtime = int(time.time())
short_valid = nowtime - starttime
fetch_list(
"to_fetch", validity=short_valid, depth=depth, tourandremove=True,
force_large_download=True
)
# then we fetch all the rest (including bookmarks and tour)
for l in normal_lists:
fetch_list(l, validity=refresh_time, depth=depth)
for l in fridge:
fetch_list(l, validity=0, depth=depth)
# tour should be the last one as item my be added to it by others
fetch_list("tour", validity=refresh_time, depth=depth)
print("End of sync")
self.sync_only = False
# The end!
def do_quit(self, *args):
"""Exit Offpunk."""
self.opencache.cleanup()
print("You can close your screen!")
sys.exit()
do_exit = do_quit
# Main function
def main():
# Parse args
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--bookmarks", action="store_true", help="start with your list of bookmarks"
)
parser.add_argument(
"--command",
metavar="COMMAND",
nargs="*",
help="Launch this command after startup",
)
parser.add_argument(
"--config-file",
metavar="FILE",
help="use this particular config file instead of default",
)
parser.add_argument(
"--sync",
action="store_true",
help="run non-interactively to build cache by exploring lists passed \
as argument. Without argument, all lists are fetched.",
)
parser.add_argument(
"--assume-yes",
action="store_true",
help="assume-yes when asked questions about certificates/redirections during sync (lower security)",
)
parser.add_argument(
"--disable-http",
action="store_true",
help="do not try to get http(s) links (but already cached will be displayed)",
)
parser.add_argument(
"--fetch-later",
action="store_true",
help="run non-interactively with an URL as argument to fetch it later",
)
parser.add_argument(
"--depth",
help="depth of the cache to build. Default is 1. More is crazy. Use at your own risks!",
)
parser.add_argument(
"--images-mode",
help="the mode to use to choose which images to download in a HTML page.\
one of (None, readable, full). Warning: full will slowdown your sync.",
)
parser.add_argument(
"--cache-validity",
help="duration for which a cache is valid before sync (seconds)",
)
parser.add_argument(
"--version", action="store_true", help="display version information and quit"
)
parser.add_argument(
"--features",
action="store_true",
help="display available features and dependancies then quit",
)
parser.add_argument(
"url",
metavar="URL",
nargs="*",
help="Arguments should be URL to be fetched or, if --sync is used, lists",
)
args = parser.parse_args()
# Handle --version
if args.version:
print("Offpunk " + __version__)
sys.exit()
elif args.features:
GeminiClient.do_version(None, None)
sys.exit()
else:
for f in [xdg("config"), xdg("data")]:
if not os.path.exists(f):
print("Creating config directory {}".format(f))
os.makedirs(f)
# Instantiate client
gc = GeminiClient(synconly=args.sync)
torun_queue = []
# Act on args
if args.bookmarks:
torun_queue.append("bookmarks")
elif args.url and not args.sync:
if len(args.url) == 1:
torun_queue.append("go %s" % args.url[0])
else:
for url in args.url:
torun_queue.append("tour %s" % url)
torun_queue.append("tour")
if args.disable_http:
gc.support_http = False
# Endless interpret loop (except while --sync or --fetch-later)
if args.fetch_later:
if args.url:
gc.sync_only = True
for u in args.url:
if looks_like_url(u):
if netcache.is_cache_valid(u):
gc.list_add_line("tour", u)
else:
gc.list_add_line("to_fetch", u)
else:
print("%s is not a valid URL to fetch" % u)
else:
print("--fetch-later requires an URL (or a list of URLS) as argument")
elif args.sync:
if args.assume_yes:
gc.automatic_choice = "y"
gc.onecmd("set accept_bad_ssl_certificates True")
if args.cache_validity:
refresh_time = int(args.cache_validity)
else:
# if no refresh time, a default of 0 is used (which means "infinite")
refresh_time = 0
if args.images_mode and args.images_mode in [
"none",
"readable",
"normal",
"full",
]:
gc.options["images_mode"] = args.images_mode
if args.depth:
depth = int(args.depth)
else:
depth = 1
torun_queue += init_config(rcfile=args.config_file, interactive=False)
for line in torun_queue:
gc.onecmd(line)
gc.call_sync(refresh_time=refresh_time, depth=depth, lists=args.url)
else:
# We are in the normal mode. First process config file
torun_queue += init_config(rcfile=args.config_file,interactive=True)
print("Welcome to Offpunk!")
print("Type `help` to get the list of available command.")
for line in torun_queue:
gc.onecmd(line)
if args.command:
for cmd in args.command:
gc.onecmd(cmd)
while True:
try:
gc.cmdloop()
except KeyboardInterrupt:
print("")
if __name__ == "__main__":
main()
offpunk-v2.7.1/offthemes.py 0000664 0000000 0000000 00000004067 14775435273 0015741 0 ustar 00root root 0000000 0000000 #!/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
offpunk-v2.7.1/offutils.py 0000664 0000000 0000000 00000025014 14775435273 0015607 0 ustar 00root root 0000000 0000000 #!/bin/python
# This file contains some utilities common to offpunk, ansicat and netcache.
# Currently, there are the following utilities:
#
# run : run a shell command and get the results with some security
# term_width : get or set the width to display on the terminal
import io
import os
import shlex
import shutil
import subprocess
import urllib.parse
import cert_migration
import netcache
import netcache_migration
CACHE_VERSION = 1
CERT_VERSION = 1
# let’s find if grep supports --color=auto
try:
test = subprocess.run(
["grep", "--color=auto", "x"],
input=b"x",
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
GREPCMD = "grep --color=auto"
except Exception:
GREPCMD = "grep"
# We upgrade the cache only once at startup, hence the CACHE_UPGRADED variable
# This is only to avoid unnecessary checks each time the cache is accessed
CACHE_UPGRADED = False
def upgrade_cache(cache_folder):
# Let’s 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 Exception:
current_version = 0
# Now, let’s 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()
CACHE_UPGRADED = True
CERT_UPGRADED = False
def upgrade_cert(config_folder: str, data_folder: str) -> None:
# read the current version
certdata = os.path.join(data_folder, "certs")
if not os.path.exists(certdata):
os.makedirs(certdata, exist_ok=True)
version_path = os.path.join(certdata, ".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 Exception:
current_version = 0
else:
current_version = 0
# Now, let’s upgrade the certificate storage if needed
while current_version < CERT_VERSION:
current_version += 1
upgrade_func = getattr(cert_migration, "upgrade_to_" + str(current_version))
upgrade_func(data_folder, config_folder)
with open(version_path, "w") as f:
f.write(str(current_version))
f.close()
CERT_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 CACHE_UPGRADED:
upgrade_cache(_CACHE_PATH)
if folder == "cache":
return _CACHE_PATH
elif folder == "config":
return _CONFIG_DIR
elif folder == "data":
if not CERT_UPGRADED:
upgrade_cert(_CONFIG_DIR, _DATA_DIR)
return _DATA_DIR
else:
print("No XDG folder for %s. Check your code." % folder)
return None
#Return a list of the commands that must be run
#if skip_go = True, any command changing the url will be ignored (go, tour)
#if not interactive, only redirects and handlers are considered
def init_config(rcfile=None,skip_go=False,interactive=True,verbose=True):
cmds = []
if not rcfile:
rcfile = os.path.join(xdg("config"), "offpunkrc")
if os.path.exists(rcfile):
if verbose:
print("Using config %s" % rcfile)
with open(rcfile,"r") as fp:
for line in fp:
line = line.strip()
#Is this a command to go to an url ?
is_go = any(line.startswith(x) for x in ("go","g","tour","t"))
#Is this a command necessary, even when non-interactive ?
is_necessary = any(line.startswith(x) for x in ("redirect","handler"))
if is_necessary:
cmds.append(line)
elif interactive:
if skip_go and is_go:
if verbose:
print("Skipping startup command \"%s\" due to provided URL"%line)
continue
else:
cmds.append(line)
return cmds
# 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):
if url:
mode = None
splitted = url.split("##offpunk_mode=")
if len(splitted) > 1:
url = splitted[0]
mode = splitted[1]
return [url, mode]
else:
return [None,None]
# 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={}):
if parameter:
cmd = cmd % shlex.quote(parameter)
e = os.environ
e.update(env)
if isinstance(input, io.IOBase):
stdin = input
input = None
else:
if input:
input = input.encode()
stdin = None
if not direct_output:
# subprocess.check_output() wouldn't allow us to pass stdin.
result = subprocess.run(
cmd,
check=True,
env=e,
input=input,
shell=True,
stdin=stdin,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
return result.stdout.decode()
else:
subprocess.run(cmd, env=e, input=input, shell=True, stdin=stdin)
global TERM_WIDTH
TERM_WIDTH = 72
# if absolute, returns the real terminal width, not the text width
def term_width(new_width=None, absolute=False):
if new_width:
global TERM_WIDTH
TERM_WIDTH = new_width
cur = shutil.get_terminal_size()[0]
if absolute:
return cur
width = TERM_WIDTH
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 it’s 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 can’t handle other data:image such as svg for now
imgurl = None
else:
imgurl = urllib.parse.urljoin(baseurl, imgname)
return imgurl, imgdata
offpunk-v2.7.1/opnk.py 0000775 0000000 0000000 00000037152 14775435273 0014734 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# 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 argparse
import fnmatch
import os
import shutil
import sys
import tempfile
import time
import ansicat
import netcache
import offutils
from offutils import GREPCMD, is_local, mode_url, run, term_width, unmode_url, init_config
_HAS_XDGOPEN = shutil.which("xdg-open")
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(
'(I’m 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:
# On macOS the version can be something like 581.2 not just an int:
if all(_.isdigit() for _ in w.split(".")):
less_version = int(w.split(".", 1)[0])
# 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 and not grep:
cmd_str = _DEFAULT_CAT
elif grep:
grep_cmd = GREPCMD
# 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,file_extension=None):
# 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
#we try to match the file extension, with a starting dot or not
elif file_extension == handled_mime.strip("."):
break
else:
# Use "xdg-open" as a last resort.
if _HAS_XDGOPEN:
cmd_str = "xdg-open %s"
else:
cmd_str = 'echo "Can’t 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):
if "%s" not in handler:
#if no %s, we automatically add one. I can’t think of any usecase
# where it should not be part of the handler
handler += " %s"
previous = None
if mime in self.mime_handlers.keys():
previous = self.mime_handlers[mime]
self.mime_handlers[mime] = handler
def get_renderer(self, inpath, mode=None, theme=None,**kwargs):
# We remove the ##offpunk_mode= from the URL
# If mode is already set, we don’t use the part from the URL
inpath, newmode = unmode_url(inpath)
if not mode:
mode = newmode
# If we still doesn’t 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,\
**kwargs)
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="readable", terminal=True, grep=None, theme=None, link=None,\
direct_open_unsupported=False, **kwargs):
# Return True if inpath opened in Terminal
# False otherwise
# also returns the url in case it has been modified
# if terminal = False, we don’t try to open in the terminal,
# we immediately fallback to xdg-open.
# netcache currently provide the path if it’s a file.
# If link is a digit, we open that link number instead of the inpath
# If direct_open_unsupported, we don’t print the "unsupported warning"
# and, instead, immediately fallback to external open
if not offutils.is_local(inpath):
if mode:
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, **kwargs)
if link and link.isdigit():
inpath = renderer.get_link(int(link))
renderer = self.get_renderer(inpath, mode=mode, theme=theme, **kwargs)
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 renderer and not renderer.is_format_supported() and direct_open_unsupported:
terminal = False
if terminal and renderer:
# If this is an image and we have chafa/timg, we
# don’t 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 there’s 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 don’t 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)
#we find the file extension by taking the last part of the path
#and finding a dot.
last_part = cachepath.split("/")[-1]
extension = None
if last_part and "." in last_part:
extension = last_part.split(".")[-1]
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,file_extension=extension)
change_cmd = "\"handler %s MY_PREFERED_APP %%s\""%mimetype
try:
#we don’t write the info if directly opening to avoid
#being verbose in opnk
if not direct_open_unsupported:
print("External open of type %s with \"%s\""%(mimetype,cmd_str))
print("You can change the default handler with %s"%change_cmd)
run(
cmd_str,
parameter=netcache.get_cache_path(inpath),
direct_output=True,
)
return True, inpath
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.")
print("You can change the default handler with %s"%change_cmd)
return False, inpath
# 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="*",
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()
#we read the startup config and we only care about the "handler" command
cmds = init_config(skip_go=True,interactive=False,verbose=False)
for cmd in cmds:
splitted = cmd.split(maxsplit=2)
if len(splitted) >= 3 and splitted[0] == "handler":
cache.set_handler(splitted[1],splitted[2])
# if the second argument is an integer, we associate it with the previous url
# to use as a link_id
if len(args.content) == 2 and args.content[1].isdigit():
url = args.content[0]
link_id = args.content[1]
cache.opnk(url, mode=args.mode, validity=args.cache_validity, link=link_id,\
direct_open_unsupported=True)
else:
for f in args.content:
cache.opnk(f, mode=args.mode, validity=args.cache_validity,\
direct_open_unsupported=True)
if __name__ == "__main__":
main()
offpunk-v2.7.1/pyproject.toml 0000664 0000000 0000000 00000003335 14775435273 0016320 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["hatchling>=1.5"]
build-backend = "hatchling.build"
[project]
name = "offpunk"
description = "Offline-First Gemini/Web/Gopher/RSS reader and browser"
authors = [
{name = "Solderpunk", email = "solderpunk@sdf.org"},
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
]
maintainers = [
{name = "Lionel Dricot (Ploum)", email = "offpunk2@ploum.eu"},
]
license = "AGPL-3.0-or-later"
license-files = ["LICENSE"]
readme = "README.md"
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Communications",
"Topic :: Internet",
]
keywords = ["gemini", "browser"]
requires-python = ">=3.7"
dynamic = ["version"]
[project.optional-dependencies]
better-tofu = ["cryptography"]
chardet = ["chardet"]
html = ["bs4", "readability-lxml"]
http = ["requests"]
process-title = ["setproctitle"]
rss = ["feedparser"]
[project.urls]
Homepage = "https://offpunk.net/"
Source = "https://git.sr.ht/~lioploum/offpunk"
"Bug Tracker" = "https://todo.sr.ht/~lioploum/offpunk"
[project.scripts]
offpunk = "offpunk:main"
netcache = "netcache:main"
ansicat = "ansicat:main"
opnk = "opnk:main"
[dependency-groups]
test = [
"pytest",
"pytest-mock",
]
[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", "cert_migration.py",
]
[tool.ruff.lint]
select = ["E"]
# Never enforce `E501` (line length violations)
# Never enforce `E741` (ambigous variable name for `l`)
ignore = ["E501", "E741"]
offpunk-v2.7.1/requirements-dev.txt 0000664 0000000 0000000 00000000023 14775435273 0017433 0 ustar 00root root 0000000 0000000 pytest
pytest-mock
offpunk-v2.7.1/requirements.txt 0000664 0000000 0000000 00000000145 14775435273 0016664 0 ustar 00root root 0000000 0000000 chardet
cryptography
requests
feedparser
bs4
readability-lxml
lxml-html-clean
setproctitle
timg
file
offpunk-v2.7.1/screenshots/ 0000775 0000000 0000000 00000000000 14775435273 0015740 5 ustar 00root root 0000000 0000000 offpunk-v2.7.1/screenshots/1.png 0000664 0000000 0000000 00000245752 14775435273 0016625 0 ustar 00root root 0000000 0000000 PNG
IHDR u sBIT|d tEXtSoftware gnome-screenshot> IDATxw|e3@Ez$rTTE(z+r?r'z"Q,@:B.Mlll$g63*n\B!Bqs{GYC!B!(1ckNB!BQ,B! `!B! !B!,8:B:
+
ZBHB!t(
#AeZx0d2MzXtp*t|4A#N
˨Gmz\]5+b4`;lQNae!I~}R1P4S$,,
8,.sb
qm:Q̽58Dž]'Njp4wi]G
8Ss$z<';.209;,p:àf1;sa]{;ǹ bVMeދQs!a`LkC1`,sS?[U_ƎF~~t{r%n^}av뢨؉i[k"%-WZkj^7MfeY54$܅6NKRY(R|˾Iàx4c丆Jetc͂}I)2$%0'4g+xRԚyLo;(A61٦
9yY{crïkӷ=