👽
This commit is contained in:
1 parent
0b17aa140b
commit
dde4ef218a
136 files changed
+9796
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+211
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""A DBus eavesdropper for org.freedesktop.Notifications
|
||||
interface.
|
||||
|
||||
This is created mainly to cache the raw image data that is
|
||||
sent by stupid applications like Spotify, Discord, etc.
|
||||
Now that I think about it all of the electron clients do this.
|
||||
|
||||
Usually any application, if they had to they'd send the
|
||||
notifications as a path i.e. caching the image themselves
|
||||
and then returning the path to it.
|
||||
|
||||
Also, <https://specifications.freedesktop.org/notification-spec/latest/>
|
||||
is a really nice manual. Give it a read.
|
||||
"""
|
||||
|
||||
# Authored By dharmx <dharmx@gmail.com> under:
|
||||
# GNU GENERAL PUBLIC LICENSE
|
||||
# Version 3, 29 June 2007
|
||||
#
|
||||
# Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
# Everyone is permitted to copy and distribute verbatim copies
|
||||
# of this license document, but changing it is not allowed.
|
||||
#
|
||||
# Permissions of this strong copyleft license are conditioned on
|
||||
# making available complete source code of licensed works and
|
||||
# modifications, which include larger works using a licensed work,
|
||||
# under the same license. Copyright and license notices must be
|
||||
# preserved. Contributors provide an express grant of patent rights.
|
||||
#
|
||||
# Read the complete license here:
|
||||
# <https://github.com/dharmx/vile/blob/main/LICENSE.txt>
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
import dbus
|
||||
import utils
|
||||
|
||||
from dbus.mainloop.glib import DBusGMainLoop
|
||||
from gi.repository import GLib
|
||||
|
||||
|
||||
# TODO: Use actual enumerations by using the enum module from the standard library.
|
||||
class Urgency:
|
||||
"""Acts as an Enum for indicating the urgency levels as per
|
||||
the notifications specification.
|
||||
|
||||
You may use these to match wheter a specific notification belongs
|
||||
to a specific urgency class or, not.
|
||||
|
||||
Attributes:
|
||||
LOW: Ads, Login, etc.
|
||||
NORMAL: USB unplugged, Drive mounted, etc.
|
||||
CRITICAL: Your PC is on fire, Storage Full, etc.
|
||||
"""
|
||||
|
||||
LOW = b"\x00"
|
||||
NORMAL = b"\x01"
|
||||
CRITICAL = b"\x02"
|
||||
|
||||
|
||||
class Eavesdropper:
|
||||
"""A quick and naive way of saving the image-data.
|
||||
|
||||
The main idea is to keep a notification server running that
|
||||
implements image-data and image-path as per the freedesktop
|
||||
notification specification.
|
||||
And, then you'd run the eavesdropper which will connect to that
|
||||
interface (org.freedesktop.Notifications) and will continuously
|
||||
monitor that interface.
|
||||
And, if any application sends a notification, that contains a raw
|
||||
icon then it will be saved into the cache directory.
|
||||
|
||||
Attributes:
|
||||
callback:
|
||||
The arbitrary subroutine that will executed on getting a notification.
|
||||
cache_dir:
|
||||
The directory path that all of those image-data would be saved.
|
||||
"""
|
||||
|
||||
# TODO: Segregate more.
|
||||
def __init__(self, callback: typing.Callable = print, cache_dir: str = "/tmp"):
|
||||
"""Assigns the CTOR parameters to the field variables (duh..)
|
||||
|
||||
Arguments:
|
||||
callback: The arbitrary subroutine that will executed on getting a notification.
|
||||
cache_dir: The directory path that all of those image-data would be saved.
|
||||
"""
|
||||
self.callback = callback
|
||||
self.cache_dir = f"{os.path.expandvars(cache_dir)}/image-data"
|
||||
# translation: mkdir --parents cache_dir
|
||||
pathlib.PosixPath(self.cache_dir).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _message_callback(
|
||||
self,
|
||||
_,
|
||||
message: dbus.lowlevel.MethodReturnMessage or dbus.lowlevel.MethodCallMessage,
|
||||
):
|
||||
"""A filter callback for parsing the specific messages that are received from the DBus interface.
|
||||
|
||||
Arguments:
|
||||
proxy_bus:
|
||||
The bus that sent the message.
|
||||
message:
|
||||
In this case a message is sent when the
|
||||
Notify method is called AND when the Notify method returns something.
|
||||
|
||||
If the message is of type dbus.lowlevel.MethodCallMessage then this will NOT call the passed callback.
|
||||
"""
|
||||
|
||||
# we will be filtering this out as we only need the value that the method call returns
|
||||
# i.e. dbus.lowlevel.MethodReturnMessage
|
||||
if type(message) != dbus.lowlevel.MethodCallMessage:
|
||||
return
|
||||
|
||||
args_list = message.get_args_list()
|
||||
# convert dbus data types to pythonic ones
|
||||
# eg: dbus.String('Hello') -> 'Hello'
|
||||
args_list = [utils.unwrap(item) for item in args_list]
|
||||
|
||||
# set fallbacks like a fine gentleman
|
||||
details = {
|
||||
"appname": args_list[0].strip() or "Unknown",
|
||||
"summary": args_list[3].strip() or "",
|
||||
"body": args_list[4].strip() or "",
|
||||
"id": datetime.datetime.now().strftime("%s"),
|
||||
"urgency": "unknown",
|
||||
}
|
||||
|
||||
if "urgency" in args_list[6]:
|
||||
details["urgency"] = args_list[6]["urgency"]
|
||||
|
||||
if args_list[2].strip():
|
||||
# if the iconpath value is a path i.e. if it has slashes on them
|
||||
# then assign that as the iconpath
|
||||
if "/" in args_list[2] or "." in args_list[2]:
|
||||
details["iconpath"] = args_list[2]
|
||||
else:
|
||||
# and if the iconpath is just a string that has no extensions or,
|
||||
# a pathlike structure like: 'bell' or 'custom-folder-bookmark'
|
||||
# it might have a dash (-) sign but not all the time.
|
||||
# then fetch that actual path of that icon as that is a part of the
|
||||
# icon theme naming convention and the current icon theme should probably have it
|
||||
details["iconpath"] = utils.get_gtk_icon_path(args_list[2])
|
||||
else:
|
||||
# if there are no icon hints then use fallback (generic bell)
|
||||
details["iconpath"] = utils.get_gtk_icon_path("custom-notification")
|
||||
|
||||
if "image-data" in args_list[6]:
|
||||
# capture the raw image bytes and save them to the cache_dir/x.png path
|
||||
details[
|
||||
"iconpath"
|
||||
] = f"{self.cache_dir}/{details['appname']}-{details['id']}.png"
|
||||
utils.save_img_byte(args_list[6]["image-data"], details["iconpath"])
|
||||
|
||||
# BUG: add a print statement -> init logger.py and disown the process
|
||||
# BUG: then you'll notice the notifications with value (progress) hint does not get logged
|
||||
if "value" in args_list[6]:
|
||||
details["progress"] = args_list[6]["value"]
|
||||
|
||||
# execute arbitrary callback and passing details about the current notification.
|
||||
self.callback(details)
|
||||
|
||||
# TODO: Segregate more.
|
||||
def eavesdrop(
|
||||
self, timeout: int or bool = False, timeout_callback: typing.Callable = print
|
||||
):
|
||||
"""Primes the session bus instance and starts a GLib mainloop.
|
||||
|
||||
Arguments:
|
||||
timeout:
|
||||
Intervals for executing the callback.
|
||||
timeout_callback:
|
||||
Callback that will be executed on intervals.
|
||||
"""
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
|
||||
rules = {
|
||||
"interface": "org.freedesktop.Notifications",
|
||||
"member": "Notify",
|
||||
"eavesdrop": "true", # https://bugs.freedesktop.org/show_bug.cgi?id=39450
|
||||
}
|
||||
|
||||
bus = dbus.SessionBus()
|
||||
# discard all other interfaces except org.freedesktop.Notifications
|
||||
# setting eavesdrop to true enables DBus to send the messages that are
|
||||
# not meant for you.
|
||||
# removing the eavesdrop key from rules will not send the Notify method's
|
||||
# contents to you (you can try and see what happens)
|
||||
bus.add_match_string(
|
||||
",".join([f"{key}={value}" for key, value in rules.items()])
|
||||
)
|
||||
bus.add_message_filter(self._message_callback)
|
||||
|
||||
try:
|
||||
loop = GLib.MainLoop()
|
||||
if timeout:
|
||||
# executes a callback in intervals
|
||||
GLib.set_timeout(timeout, timeout_callback)
|
||||
loop.run()
|
||||
except (KeyboardInterrupt, Exception) as excep:
|
||||
sys.stderr.write(str(excep) + "\n")
|
||||
bus.close()
|
||||
|
||||
|
||||
# vim:filetype=python
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
rm -r ~/.config/eww/\$XDG_CACHE_HOME/
|
||||
eww -c ~/.config/polybar/widgets/noti open --toggle notifications
|
||||
eww -c ~/.config/polybar/widgets/noti open --toggle notifications
|
||||
Executable
+326
@@ -0,0 +1,326 @@
|
||||
"""This file is tightly integrated with logger.py and won't work without it.
|
||||
Unlike the files cache.py and utils.py.
|
||||
|
||||
This module just redirects specific presets of messages based on the source
|
||||
(the application) that sent that message.
|
||||
|
||||
The redirector will call the specific function based off the appname, then
|
||||
the called handler function will evaluate the YUCK literal and replace all
|
||||
of the items on the format string with the passed attributes and then return it.
|
||||
"""
|
||||
|
||||
# Authored By dharmx <dharmx@gmail.com> under:
|
||||
# GNU GENERAL PUBLIC LICENSE
|
||||
# Version 3, 29 June 2007
|
||||
#
|
||||
# Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
# Everyone is permitted to copy and distribute verbatim copies
|
||||
# of this license document, but changing it is not allowed.
|
||||
#
|
||||
# Permissions of this strong copyleft license are conditioned on
|
||||
# making available complete source code of licensed works and
|
||||
# modifications, which include larger works using a licensed work,
|
||||
# under the same license. Copyright and license notices must be
|
||||
# preserved. Contributors provide an express grant of patent rights.
|
||||
#
|
||||
# Read the complete license here:
|
||||
# <https://github.com/dharmx/vile/blob/main/LICENSE.txt>
|
||||
|
||||
import datetime
|
||||
|
||||
import cache
|
||||
import utils
|
||||
|
||||
# WARN: Subject to heavy change.
|
||||
# TODO: Use OOP instead of passing around variables
|
||||
# TODO: Add fallback / canned lambdas for common handler operations eg: formats["appname"] % attributes
|
||||
|
||||
|
||||
# TODO: Handle '\n' in body / summary.
|
||||
def redir_to_handlers(formats, attributes: dict) -> str:
|
||||
r"""Function for evaluating which handler function will be called.
|
||||
|
||||
Before calling the handler function it will do some filtering and
|
||||
then actually call the handler which should return a fully evaluated
|
||||
YUCK literal string.
|
||||
|
||||
Arguments:
|
||||
formats:
|
||||
All of the YUCK literal format strings.
|
||||
attributes:
|
||||
Details about the currently sent notification like summary, body, appname, etc.
|
||||
|
||||
Returns:
|
||||
A str that is a primed YUCK literal with passed attributes.
|
||||
|
||||
Example:
|
||||
Format:
|
||||
(_cardimage :identity ':::###::::XXXWWW%(id)s===::'
|
||||
:close_action 'scripts/logger.py rmid %(id)s'
|
||||
:limit_body '%(BODY_LIMITER)s'
|
||||
:limit_summary '%(SUMMARY_LIMITER)s'
|
||||
:summary '%(summary)s'
|
||||
:body '%(body)s'
|
||||
:close '繁'
|
||||
:image_height 100
|
||||
:image_width 100
|
||||
:image '%(iconpath)s'
|
||||
:appname '%(appname)s'
|
||||
:icon '%(iconpath)s'
|
||||
:icon_height 32
|
||||
:icon_width 32
|
||||
:timestamp '%(TIMESTAMP)s'
|
||||
:urgency '%(URGENCY)s')
|
||||
Primed:
|
||||
(_cardimage :identity ':::###::::XXXWWW1658665761===::'
|
||||
:close_action 'scripts/logger.py rmid 1658665761'
|
||||
:limit_body '110'
|
||||
:limit_summary '30'
|
||||
:summary 'Picom'
|
||||
:body 'The compositer is now disabled.'
|
||||
:close '繁'
|
||||
:image_height 100
|
||||
:image_width 100
|
||||
:image '/home/maker/.icons/custom/stock/128/custom-crying.png'
|
||||
:appname 'Picom'
|
||||
:icon '/home/maker/.icons/custom/stock/128/custom-crying.png'
|
||||
:icon_height 32
|
||||
:icon_width 32
|
||||
:timestamp '17:59'
|
||||
:urgency 'CRITICAL')
|
||||
"""
|
||||
|
||||
# assign the timestamp of the notification.
|
||||
attributes["TIMESTAMP"] = datetime.datetime.now().strftime(
|
||||
attributes["TIMESTAMP_FORMAT"]
|
||||
)
|
||||
|
||||
# turn the urgency values (which are in bytes) to a more readable format (string).
|
||||
match attributes["urgency"]:
|
||||
case cache.Urgency.LOW:
|
||||
attributes["URGENCY"] = "LOW"
|
||||
case cache.Urgency.NORMAL:
|
||||
attributes["URGENCY"] = "NORMAL"
|
||||
case cache.Urgency.CRITICAL:
|
||||
attributes["URGENCY"] = "CRITICAL"
|
||||
case _:
|
||||
attributes["URGENCY"] = "NORMAL"
|
||||
|
||||
# handle next lines (especially discord code blocks)
|
||||
# NOTE: may make this only discord / firefox specific
|
||||
attributes["body"] = attributes["body"].replace("\n", " ")
|
||||
attributes["summary"] = attributes["summary"].replace("\n", " ")
|
||||
|
||||
# check if there are any pango tags on the body and summary and if so
|
||||
# it will then remove it.
|
||||
if utils.contains_pango(attributes["body"]):
|
||||
attributes["body"] = utils.strip_pango_tags(attributes["body"])
|
||||
if utils.contains_pango(attributes["summary"]):
|
||||
attributes["summary"] = utils.strip_pango_tags(attributes["summary"])
|
||||
|
||||
# it will replace all of the apostrophes with \' i.e. escape them.
|
||||
if "'" in attributes["body"]:
|
||||
attributes["body"] = attributes["body"].replace("'", "\\'")
|
||||
if "'" in attributes["summary"]:
|
||||
attributes["summary"] = attributes["summary"].replace("'", "\\'")
|
||||
|
||||
# only 15 chars would be taken if the summary has non-english charecters.
|
||||
attributes["SUMMARY_LIMITER"] = ""
|
||||
summary_lang_char_check = utils.has_non_english_chars(attributes["summary"][:15])
|
||||
# if summary has asian characters like Japanese, Hindi or, Chinese
|
||||
if summary_lang_char_check["CJK"]:
|
||||
attributes["SUMMARY_LIMITER"] = 14
|
||||
# if summary has Cyrillic characters
|
||||
elif summary_lang_char_check["CYR"]:
|
||||
attributes["SUMMARY_LIMITER"] = 30
|
||||
|
||||
attributes["BODY_LIMITER"] = ""
|
||||
body_lang_char_check = utils.has_non_english_chars(attributes["body"][:70])
|
||||
if body_lang_char_check["CJK"]:
|
||||
attributes["BODY_LIMITER"] = 80
|
||||
elif body_lang_char_check["CYR"]:
|
||||
attributes["BODY_LIMITER"] = 110
|
||||
else:
|
||||
attributes["BODY_LIMITER"] = 100
|
||||
|
||||
# redirect to handlers
|
||||
match attributes["appname"]:
|
||||
case "notify-send":
|
||||
return notify_send_handler(formats, attributes)
|
||||
case "volume":
|
||||
return volume_handler(formats, attributes)
|
||||
case "backlight":
|
||||
return brightness_handler(formats, attributes)
|
||||
case "shot":
|
||||
return shot_handler(formats, attributes)
|
||||
case "shot_icon":
|
||||
return shot_icon_handler(formats, attributes)
|
||||
case "todo":
|
||||
return todo_handler(formats, attributes)
|
||||
case "Spotify":
|
||||
return Spotify_handler(formats, attributes)
|
||||
case _:
|
||||
return default_handler(formats, attributes)
|
||||
|
||||
|
||||
# TODO: Segregate redir_to_handlers into more utility / helper functions.
|
||||
# NOTE: Currently it is a bit hard to utilize config values without making the code dirtier.
|
||||
# NOTE: For instance shot_handler will eventually load the command strings from the config JSON for attributes["DELETE"]. See logger.py
|
||||
def shot_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for screenshot related notifications.
|
||||
|
||||
Note that this handler will only handle the screenshots itself.
|
||||
That is, it won't handle it if say.. the screenshot is copied to the clipboard, etc.
|
||||
All of those are handled by shot_icon_handler.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
# TODO: Make this better
|
||||
attributes[
|
||||
"DELETE"
|
||||
] = f"rm --force \\'{attributes['iconpath']}\\' && scripts/logger.py rmid {attributes['id']}"
|
||||
attributes["OPEN"] = f"xdg-open \\'{attributes['iconpath']}\\'"
|
||||
|
||||
# capitalize words i.e. notify_send -> Notify Send
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["shot"] % attributes
|
||||
|
||||
|
||||
def Spotify_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for notifications related to the official electron client for Spotify.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
return formats["Spotify"] % attributes
|
||||
|
||||
|
||||
def default_handler(formats, attributes: dict) -> str:
|
||||
r"""Handler for basic notifications. The notifications that are ordinary.
|
||||
Or, rather the notifications that do not match any of the match-cases in
|
||||
the redir_to_handlers function.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Example:
|
||||
notify-send Hello
|
||||
notify-send Greetings
|
||||
notify-send -u low -i bell Greetings Ding\!
|
||||
notify-send -a appname-does-not-exist -i bell Yo
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["default"] % attributes
|
||||
|
||||
|
||||
def notify_send_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for notifications related to the notify-send command.
|
||||
|
||||
See:
|
||||
default_handler
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["notify-send"] % attributes
|
||||
|
||||
|
||||
def brightness_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for notifications related to brightness control.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["brightness"] % attributes
|
||||
|
||||
|
||||
def volume_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for notifications related to volume control.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["volume"] % attributes
|
||||
|
||||
|
||||
# TODO: Make this general purpose and not just todo specific.
|
||||
def todo_handler(formats, attributes: dict) -> str:
|
||||
"""Handler for notifications related to todo-bin CLI application by Siddomy.
|
||||
|
||||
The notification body needs to be in a particular format in order for it to register.
|
||||
That is: <completed_tasks> tasks done and <total_tasks> are remaining.
|
||||
|
||||
The fragments <completed_tasks> and <total_tasks> will be picked up by this handler.
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
splitted = attributes["body"].split(" ")
|
||||
attributes["TOTAL"] = int(splitted[4])
|
||||
attributes["DONE"] = int(splitted[0])
|
||||
|
||||
# handle division by zero
|
||||
attributes["PERC"] = (
|
||||
(attributes["DONE"] / attributes["TOTAL"]) * 100
|
||||
if attributes["DONE"] > 0
|
||||
else 0
|
||||
)
|
||||
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["todo"] % attributes
|
||||
|
||||
|
||||
def shot_icon_handler(formats, attributes: dict) -> str:
|
||||
"""Almost same as default_handler only just it uses a different icon.
|
||||
|
||||
Redundant, but still nice to if you want to add additional
|
||||
functionalities on this particular appname.
|
||||
|
||||
See:
|
||||
default_handler
|
||||
shot_handler
|
||||
|
||||
Arguments:
|
||||
formats: See redir_to_handlers.
|
||||
attributes: See redir_to_handlers.
|
||||
|
||||
Returns:
|
||||
See redir_to_handlers
|
||||
"""
|
||||
attributes["appname"] = utils.prettify_name(attributes["appname"])
|
||||
return formats["shot_icon"] % attributes
|
||||
|
||||
|
||||
# vim:filetype=python
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env --split-string=python -u
|
||||
"""Script for logging desktop notifications in the form of YUCK literal.
|
||||
|
||||
General idea is to have a file log the notifications in the form of YUCK
|
||||
literal containing a widget structure which will then be concatenated into
|
||||
a box widget to take a list-like structure.
|
||||
|
||||
The said structure needs to be re-rendered whenever the log file notices
|
||||
a change. Like, deleting an entry or, adding an entry or, editing an entry.
|
||||
|
||||
Note, if you still have not guessed already, if you make any changes to the
|
||||
log file then the list of notifications will be re-rendered again.
|
||||
"""
|
||||
|
||||
# Authored By dharmx <dharmx@gmail.com> under:
|
||||
# GNU GENERAL PUBLIC LICENSE
|
||||
# Version 3, 29 June 2007
|
||||
#
|
||||
# Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
# Everyone is permitted to copy and distribute verbatim copies
|
||||
# of this license document, but changing it is not allowed.
|
||||
#
|
||||
# Permissions of this strong copyleft license are conditioned on
|
||||
# making available complete source code of licensed works and
|
||||
# modifications, which include larger works using a licensed work,
|
||||
# under the same license. Copyright and license notices must be
|
||||
# preserved. Contributors provide an express grant of patent rights.
|
||||
#
|
||||
# Read the complete license here:
|
||||
# <https://github.com/dharmx/vile/blob/main/LICENSE.txt>
|
||||
|
||||
# TODO: Utilize JSON instead of YUCK Literals.
|
||||
# WARN: This script is under active development and is subject to frequent changes.
|
||||
# WARN: Currently this script is quite inefficient. So, you have been warned.
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
from threading import main_thread
|
||||
|
||||
import cache
|
||||
import handlers
|
||||
import subprocess
|
||||
import utils
|
||||
|
||||
# presetted notification format strings i.e. they are just utility items that help reducing the size of code
|
||||
# another reason is convenience i.e. it would be easier to have all the formats in one place and defining them
|
||||
# would be less cumbersome.
|
||||
FORMATS = {
|
||||
"spotifyd": "(cardimage :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"ncspot": "(cardimage :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"Spotify": "(cardimage :class 'Spotify-rectangle' :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"shot_icon": "(cardimage :class 'shot-image-bord-dashed' :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"shot": "(cardscr :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :delete '%(DELETE)s' :open '%(OPEN)s' :summary '%(summary)s' :image '%(iconpath)s' :image_height 250 :image_width 100 :urgency '%(URGENCY)s' :close '' :timestamp '%(TIMESTAMP)s')",
|
||||
"default": "(cardimage :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"notify-send": "(cardimage :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"empty": "(box :class 'notifications-empty-box' :height 750 :orientation 'vertical' :space-evenly false (image :class 'notifications-empty-banner' :valign 'end' :vexpand true :path 'images/wedding-bells.png' :image-width 250 :image-height 250) (label :vexpand true :valign 'start' :wrap true :class 'notifications-empty-label' :text '%(QUOTE)s'))",
|
||||
"brightness": "(cardprog :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s' :progress '%(progress)s')",
|
||||
"todo": "(cardradial :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :appname '%(appname)s' :progress %(PERC)s :thickness 20.0 :total %(TOTAL)s :done %(DONE)s :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s')",
|
||||
"volume": "(cardprog :identity ':::###::::XXXWWW%(id)s===::' :close_action 'scripts/logger.py rmid %(id)s' :limit_body '%(BODY_LIMITER)s' :limit_summary '%(SUMMARY_LIMITER)s' :summary '%(summary)s' :body '%(body)s' :close '' :image_height 50 :image_width 50 :image '%(iconpath)s' :appname '%(appname)s' :icon '%(iconpath)s' :icon_height 32 :icon_width 32 :timestamp '%(TIMESTAMP)s' :urgency '%(URGENCY)s' :progress '%(progress)s')",
|
||||
}
|
||||
|
||||
spotify_song_name = str(
|
||||
subprocess.run(
|
||||
["playerctl", "metadata", "title", "-p", "spotify"], capture_output=True
|
||||
).stdout
|
||||
)[2:-3]
|
||||
|
||||
if __name__ == "__main__":
|
||||
# load only notification related options from the config JSON
|
||||
config = json.loads(
|
||||
pathlib.PosixPath(
|
||||
os.path.expandvars("$HOME/.config/eww/.config.json")
|
||||
).read_text()
|
||||
)["notify"]
|
||||
|
||||
# kind of like the sliding window algorithm i.e. will pop the notifications if this number is reached
|
||||
HISTORY_LIMIT = config["limit"]
|
||||
# file path where the notifications will be saved
|
||||
CACHE_PATH = os.path.expandvars(config["cache_path"])
|
||||
# directory path where the notifications will be saved
|
||||
# WARN: Do not edit this; Only edit this if you know what you are doing!
|
||||
CACHE_DIR = os.path.dirname(CACHE_PATH)
|
||||
# file path where the quotes are stored
|
||||
QUOTE_PATH = os.path.expandvars(config["quote_path"])
|
||||
# fallback if the quote DB has no quotes in them
|
||||
DEFAULT_QUOTE = config["default_quote"]
|
||||
# Watcher interval; Reflects how fast notifications will be rendered.
|
||||
INTERVAL = config["interval"]
|
||||
|
||||
# handle IndexError
|
||||
if len(sys.argv) < 2:
|
||||
sys.argv = ("dummy", "dummy")
|
||||
match sys.argv[1]:
|
||||
case "subscribe":
|
||||
utils.create_parents_file(CACHE_PATH) # mkdir --parents
|
||||
utils.create_parents_file(QUOTE_PATH) # mkdir --parents
|
||||
utils.watcher(
|
||||
CACHE_PATH,
|
||||
lambda contents: sys.stdout.write(
|
||||
"(box :spacing 20 :orientation 'vertical' :space-evenly false " +
|
||||
# handle empty and display fallback
|
||||
contents.replace("\n", " ") + ")\n"
|
||||
if contents.strip()
|
||||
else (
|
||||
(FORMATS["empty"] + "\n")
|
||||
% {"QUOTE": utils.get_rand_quote(QUOTE_PATH, DEFAULT_QUOTE)}
|
||||
)
|
||||
),
|
||||
INTERVAL,
|
||||
)
|
||||
case "rmid":
|
||||
# grep based off the notification id and then remove that YUCK literal entry from the log file
|
||||
utils.file_matched_index_rm(
|
||||
CACHE_PATH, f":identity ':::###::::XXXWWW{sys.argv[2]}===::'"
|
||||
)
|
||||
case "stats":
|
||||
sys.stdout.write(
|
||||
json.dumps(
|
||||
utils.parse_and_print_stats(
|
||||
pathlib.PosixPath(CACHE_PATH).read_text()
|
||||
)
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
case "rm":
|
||||
utils.file_rm_line(CACHE_PATH, int(sys.argv[2]))
|
||||
case "quote":
|
||||
sys.stdout.write(utils.get_rand_quote(QUOTE_PATH, DEFAULT_QUOTE))
|
||||
case "cls":
|
||||
pathlib.PosixPath(CACHE_PATH).write_text("")
|
||||
case "init":
|
||||
|
||||
def master_callback(details: dict):
|
||||
r"""Callback function that handles fetching and logging the notification details.
|
||||
|
||||
Arguments:
|
||||
details: the JSON that should have a similar structure to the following:
|
||||
{
|
||||
"summary": "Hello",
|
||||
"body": "Who's there?",
|
||||
"id": 16444442,
|
||||
"urgency": "LOW"
|
||||
}
|
||||
"""
|
||||
details["TIMESTAMP_FORMAT"] = config["timestamp"]
|
||||
if (
|
||||
not config["excluded_appnames"]
|
||||
or details["appname"] not in config["excluded_appnames"]
|
||||
):
|
||||
saved_path = handlers.redir_to_handlers(FORMATS, details)
|
||||
# actual point where the notification is being logged.
|
||||
utils.file_add_line(CACHE_PATH, saved_path, HISTORY_LIMIT)
|
||||
|
||||
# start eavesdropping on the org.freedesktop.Notifications interface and log the notification info
|
||||
cache.Eavesdropper(master_callback, CACHE_DIR).eavesdrop()
|
||||
|
||||
# vim:filetype=python
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
|
||||
def launch_logger():
|
||||
logger_path = os.path.join("scripts", "logger.py")
|
||||
try:
|
||||
# Check if logger.py is already running
|
||||
subprocess.check_output(["pidof", "-x", "python", logger_path])
|
||||
print("logger.py is already running")
|
||||
except subprocess.CalledProcessError:
|
||||
# logger.py is not running, launch it
|
||||
subprocess.Popen(["python", logger_path, "init", "&"])
|
||||
print("logger.py has been launched")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
launch_logger()
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
# Author: github.com/NeshHari
|
||||
|
||||
import random
|
||||
import sys
|
||||
|
||||
quotes = [
|
||||
"Be the change you wish to see in the world. ~ Mahatma Gandhi",
|
||||
"I have a dream. ~ Martin Luther King Jr.",
|
||||
"Not all those who wander are lost. ~ J.R.R. Tolkien",
|
||||
"All that we see or seem is but a dream within a dream. ~ Edgar Allan Poe",
|
||||
"To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment. ~ Ralph Waldo Emerson",
|
||||
"The only way to do great work is to love what you do. ~ Steve Jobs",
|
||||
"We are what we repeatedly do. Excellence, then, is not an act, but a habit. ~ Aristotle",
|
||||
"In three words I can sum up everything I've learned about life: it goes on. ~ Robert Frost",
|
||||
"The best and most beautiful things in the world cannot be seen or even touched - they must be felt with the heart. ~ Helen Keller",
|
||||
"It does not matter how slowly you go as long as you do not stop. ~ Confucius",
|
||||
"Believe you can and you're halfway there. ~ Theodore Roosevelt",
|
||||
"The unexamined life is not worth living. ~ Socrates",
|
||||
"In the end, we will remember not the words of our enemies, but the silence of our friends. ~ Martin Luther King Jr.",
|
||||
"Success is not final, failure is not fatal: it is the courage to continue that counts. ~ Winston Churchill",
|
||||
"You miss 100% of the shots you don't take. ~ Wayne Gretzky",
|
||||
"If you want to go fast, go alone. If you want to go far, go together. ~ African proverb",
|
||||
"You can't build a reputation on what you are going to do. ~ Henry Ford",
|
||||
"The only thing we have to fear is fear itself. ~ Franklin D. Roosevelt",
|
||||
"The journey of a thousand miles begins with one step. ~ Lao Tzu",
|
||||
"A house divided against itself cannot stand. ~ Abraham Lincoln",
|
||||
"Ask not what your country can do for you, ask what you can do for your country. ~ John F. Kennedy",
|
||||
"I am not a product of my circumstances. I am a product of my decisions. ~ Stephen Covey",
|
||||
"Our greatest glory is not in never falling, but in rising every time we fall. ~ Confucius",
|
||||
"Education is the most powerful weapon which you can use to change the world. ~ Nelson Mandela",
|
||||
"It always seems impossible until it's done. ~ Nelson Mandela",
|
||||
"The only true wisdom is in knowing you know nothing. ~ Socrates",
|
||||
"The best way to predict your future is to create it. ~ Abraham Lincoln",
|
||||
"The future belongs to those who believe in the beauty of their dreams. ~ Eleanor Roosevelt",
|
||||
"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle. ~ Christian D. Larson",
|
||||
"The true test of leadership is how well you function in a crisis. ~ Brian Tracy",
|
||||
"Change your thoughts and you change your world. ~ Norman Vincent Peale",
|
||||
"The way to get started is to quit talking and begin doing. ~ Walt Disney",
|
||||
"Don't wait for opportunities, create them. ~ Unknown",
|
||||
"You must be the change you wish to see in the world. ~ Mahatma Gandhi",
|
||||
"Happiness can be found, even in the darkest of times, if one only remembers to turn on the light. ~ Albus Dumbledore",
|
||||
"Life is a journey, and if you fall in love with the journey, you will be in love forever. ~ Peter Hagerty",
|
||||
"The only thing we have to fear is fear itself. ~ Franklin D. Roosevelt",
|
||||
"All our dreams can come true, if we have the courage to pursue them. ~ Walt Disney",
|
||||
"The only limit to our realization of tomorrow will be our doubts of today. ~ Franklin D. Roosevelt",
|
||||
"You are not a drop in the ocean. You are the entire ocean in a drop. ~ Rumi",
|
||||
"The best way to find yourself is to lose yourself in the service of others.~ Mahatma Gandhi",
|
||||
"Life is 10% what happens to us and 90% how we react to it. ~ Charles R. Swindoll",
|
||||
"The greatest glory in living lies not in never falling, but in rising every time we fall. ~ Nelson Mandela",
|
||||
"The purpose of our lives is to be happy. ~ Dalai Lama",
|
||||
"The most wasted of all days is one without laughter. ~ E.E. Cummings",
|
||||
"I can't change the direction of the wind, but I can adjust my sails to always reach my destination. ~ Jimmy Dean",
|
||||
"You have within you right now, everything you need to deal with whatever the world can throw at you. ~ Brian Tracy",
|
||||
"The greatest wealth is to live content with little. ~ Plato",
|
||||
"It's not about how hard you hit. It's about how hard you can get hit and keep moving forward. ~ Rocky Balboa",
|
||||
"The biggest adventure you can ever take is to live the life of your dreams. ~ Oprah Winfrey",
|
||||
"The best way to predict the future is to create it. ~ Peter Drucker",
|
||||
"Don't be pushed around by the fears in your mind. Be led by the dreams in your heart. ~ Roy T. Bennett",
|
||||
]
|
||||
|
||||
|
||||
last_quote = ""
|
||||
quote = random.choice(quotes)
|
||||
while quote == last_quote:
|
||||
quote = random.choice(quotes)
|
||||
quote_parts = quote.split("~")
|
||||
last_quote = quote_parts[0] + "~" + quote_parts[1]
|
||||
|
||||
if len(sys.argv) >= 2:
|
||||
if sys.argv[1] == "--quote-and-quotee":
|
||||
print(quote_parts[0] + "\n\n~" + quote_parts[1])
|
||||
Executable
+469
@@ -0,0 +1,469 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Utility module. Shared across almost all of the python scripts / modules."""
|
||||
|
||||
# Authored By dharmx <dharmx.dev@gmail.com> under:
|
||||
# GNU GENERAL PUBLIC LICENSE
|
||||
# Version 3, 29 June 2007
|
||||
#
|
||||
# Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
# Everyone is permitted to copy and distribute verbatim copies
|
||||
# of this license document, but changing it is not allowed.
|
||||
#
|
||||
# Permissions of this strong copyleft license are conditioned on
|
||||
# making available complete source code of licensed works and
|
||||
# modifications, which include larger works using a licensed work,
|
||||
# under the same license. Copyright and license notices must be
|
||||
# preserved. Contributors provide an express grant of patent rights.
|
||||
#
|
||||
# Read the complete license here:
|
||||
# <https://github.com/dharmx/vile/blob/main/LICENSE.txt>
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
import unicodedata
|
||||
|
||||
# from wand.image import COLORSPACE_TYPES, Image
|
||||
from html.parser import HTMLParser
|
||||
from io import StringIO
|
||||
|
||||
import dbus
|
||||
import gi
|
||||
|
||||
# supress GIO warnings
|
||||
gi.require_version("Gtk", "3.0")
|
||||
gi.require_version("GdkPixbuf", "2.0")
|
||||
|
||||
import requests
|
||||
from gi.repository import GdkPixbuf, Gio, GLib, Gtk
|
||||
|
||||
|
||||
class PangoStripper(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.reset()
|
||||
self.strict = False
|
||||
self.convert_charrefs = True
|
||||
self.text = StringIO()
|
||||
|
||||
def handle_data(self, d):
|
||||
self.text.write(d)
|
||||
|
||||
def get_data(self):
|
||||
return self.text.getvalue()
|
||||
|
||||
|
||||
def contains_pango(string: str) -> bool:
|
||||
"""Checks if a string contains HTML tags or not. Since a pango string has to have at least two tags
|
||||
|
||||
Arguments:
|
||||
string: The Pango markup format string.
|
||||
|
||||
Returns:
|
||||
A bool value i.e. whether a has pango markup or not.
|
||||
"""
|
||||
return any(item in string for item in ["<span>", "</a>", "</span>"])
|
||||
|
||||
|
||||
def strip_pango_tags(pango: str) -> str:
|
||||
"""Removes HTML tags like <span>, <span align='left'>, etc.
|
||||
|
||||
Arguments:
|
||||
pango: The Pango format string that needs to be stripped of its tags.
|
||||
|
||||
Returns:
|
||||
A str without the tags.
|
||||
"""
|
||||
stripper = PangoStripper()
|
||||
stripper.feed(pango)
|
||||
return stripper.get_data()
|
||||
|
||||
|
||||
def create_parents_file(file_path: str):
|
||||
"""A replication of [ -f "$FILE_PATH" ] || mkdir --parents "$FILE_PATH"
|
||||
|
||||
Arguments:
|
||||
file_path: The location of the file.
|
||||
"""
|
||||
pathlib.PosixPath(os.path.dirname(file_path)).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.PosixPath(file_path).touch(exist_ok=True)
|
||||
|
||||
|
||||
def watcher(
|
||||
file_path: str, callback: typing.Callable, interval: int, initial: bool = True
|
||||
):
|
||||
"""A file watcher function that executes a callback function if any change is made to a file.
|
||||
|
||||
Arguments:
|
||||
file_path: The file location that needs to be monitored.
|
||||
callback: A callback function that would be invoked when any change is noticed.
|
||||
interval: The time rate at which the file will be checked for changes.
|
||||
initial: Initially execute the callback once before entering the watch loop.
|
||||
"""
|
||||
try:
|
||||
old = pathlib.PosixPath(file_path).read_text()
|
||||
if initial:
|
||||
callback(old)
|
||||
while not time.sleep(interval):
|
||||
new = pathlib.PosixPath(file_path).read_text()
|
||||
if new != old:
|
||||
callback(new)
|
||||
old = new
|
||||
except KeyboardInterrupt:
|
||||
sys.stdout.write("Closed.\n")
|
||||
except FileNotFoundError:
|
||||
sys.stderr.write("The path does not exist!\n")
|
||||
except Exception as excep:
|
||||
sys.stderr.write(f"{excep}\n")
|
||||
|
||||
|
||||
def get_rand_quote(file_path: str, default_quote: str) -> str:
|
||||
"""Get a random quote or, rather a random line.
|
||||
|
||||
Arguments:
|
||||
file_path: The location of the file.
|
||||
default_quote: Fallback quote if the file doesn't exist r, is empty.
|
||||
"""
|
||||
loaded_quotes: str = pathlib.PosixPath(file_path).read_text().strip()
|
||||
return random.choice(loaded_quotes.splitlines()) if loaded_quotes else default_quote
|
||||
|
||||
|
||||
def file_matched_index_rm(file_path: str, pattern: str):
|
||||
"""Removes line from a file if a pattern matches that line.
|
||||
|
||||
Arguments:
|
||||
file_path: The location of the file.
|
||||
pattern: Pattern to match the line that needs to be removed.
|
||||
"""
|
||||
posix_file_path = pathlib.PosixPath(file_path)
|
||||
lines = posix_file_path.read_text().splitlines()
|
||||
|
||||
# skip the line if pattern matches
|
||||
rm_index_lines = [
|
||||
lines[index]
|
||||
for index in range(len(lines))
|
||||
if not re.search(pattern, lines[index])
|
||||
]
|
||||
|
||||
if len(lines) != len(rm_index_lines):
|
||||
posix_file_path.write_text("\n".join(rm_index_lines))
|
||||
|
||||
|
||||
def file_rm_line(file_path: str, position: int | bool | range = True):
|
||||
"""Ranged line removal, indexed line removal and stack-like (pop / reverse pop) line removal.
|
||||
|
||||
Arguments:
|
||||
file_path: The location of the file.
|
||||
position: If the value is of type:
|
||||
range: then that the lines starting from that range will be removed.
|
||||
int: then that specific file line number will be removed.
|
||||
bool: True will pop and False will pop from the end.
|
||||
"""
|
||||
file = pathlib.PosixPath(file_path)
|
||||
match str(type(position)):
|
||||
case "<class 'int'>":
|
||||
file_contents = file.read_text().splitlines()
|
||||
# no need to run the loop if all you need to do is remove the first line
|
||||
if position == 0:
|
||||
file_rm_line(file_path, position=True)
|
||||
return
|
||||
elif position == len(file_contents) - 1:
|
||||
file_rm_line(file_path, position=False)
|
||||
return
|
||||
line_removed_contents = []
|
||||
# skip the line that matches the position value.
|
||||
for index in range(len(file_contents)):
|
||||
if index != position:
|
||||
line_removed_contents += [file_contents[index]]
|
||||
file.write_text("\n".join(line_removed_contents))
|
||||
# filter falsey and truthy and use the actual bool class signature
|
||||
case "<class 'bool'>":
|
||||
file_contents = file.read_text().splitlines()
|
||||
file_contents = file_contents[1:] if position else file_contents[:-1]
|
||||
file.write_text("\n".join(file_contents))
|
||||
case "<class 'range'>":
|
||||
if not position:
|
||||
file.write_text("")
|
||||
return
|
||||
file_contents = file.read_text().splitlines()
|
||||
write_contents = []
|
||||
# keep on skipping the lines if they are in the range.
|
||||
for index in range(len(file_contents)):
|
||||
if index not in position:
|
||||
write_contents += [file_contents[index]]
|
||||
file.write_text("\n".join(write_contents))
|
||||
|
||||
|
||||
def prettify_name(name: str) -> str:
|
||||
"""Transforms 'Hello-World' -> 'Hello World', 'notify-send++lol' -> 'Notify Send Lol'
|
||||
|
||||
Arguments:
|
||||
name: The string that needs to be prettified.
|
||||
|
||||
Returns:
|
||||
A prettified str.
|
||||
"""
|
||||
return " ".join(
|
||||
item.capitalize()
|
||||
for item in name.replace("-", " ").replace("_", " ").split(" ")
|
||||
)
|
||||
|
||||
|
||||
def file_add_line(file_path: str, write_contents: str, limit: int, top: bool = True):
|
||||
"""Functions like sliding window algorithm <https://towardsdev.com/sliding-window-algorithm-145f8e201a64>
|
||||
|
||||
That is after the file hits a certain line limit, lines from the behind will be dropped (older entries)
|
||||
and THEN the newer ones will be entered.
|
||||
|
||||
Arguments:
|
||||
file_path: The location of the file.
|
||||
write_contents: The contents that needs to be written to the file.
|
||||
limit: The line limit.
|
||||
top: Adds new entry at the beginning of the file if True, at the end otherwise.
|
||||
"""
|
||||
file = pathlib.PosixPath(file_path)
|
||||
file_contents = file.read_text().splitlines()
|
||||
if len(file_contents) == limit:
|
||||
file_contents = file_contents[:-1]
|
||||
file_contents = (
|
||||
[write_contents] + file_contents if top else file_contents + [write_contents]
|
||||
)
|
||||
file.write_text("\n".join(file_contents))
|
||||
|
||||
|
||||
def parse_and_print_stats(file_contents: str) -> dict:
|
||||
"""Looks the words CRITICAL, LOW and NORMAL and calcuates its frequency.
|
||||
|
||||
Arguments:
|
||||
file_contents: the string that needs to be calculated for frequency.
|
||||
|
||||
Returns:
|
||||
Individual frequency of the words in dict format.
|
||||
{"CRITICAL": 10.00, "NORMAL": 85.00, "LOW": 5.00}
|
||||
"""
|
||||
stats = {"critical": 0, "low": 0, "normal": 0, "total": 0}
|
||||
|
||||
for line in file_contents.splitlines():
|
||||
if "CRITICAL" in line:
|
||||
stats["critical"] += 1
|
||||
stats["total"] += 1
|
||||
elif "LOW" in line:
|
||||
stats["low"] += 1
|
||||
stats["total"] += 1
|
||||
elif "NORMAL" in line:
|
||||
stats["normal"] += 1
|
||||
stats["total"] += 1
|
||||
|
||||
# handle division / zero
|
||||
stats["critical"] = (
|
||||
stats["critical"] * 100 / stats["total"] if stats["critical"] > 0 else 0
|
||||
)
|
||||
stats["normal"] = (
|
||||
stats["normal"] * 100 / stats["total"] if stats["normal"] > 0 else 0
|
||||
)
|
||||
stats["low"] = stats["low"] * 100 / stats["total"] if stats["low"] > 0 else 0
|
||||
return stats
|
||||
|
||||
|
||||
def has_non_english_chars(string: str) -> dict:
|
||||
"""Check if there is any CJK / Cyrillic characters in the given string.
|
||||
|
||||
Arguments:
|
||||
string: the string that needs to be checked.
|
||||
|
||||
Returns:
|
||||
A dict containing True / False for keys representing if such characters exist or not.
|
||||
{"CJK": True, "CYR": False} for string value: "おはようございます means Good Morning!"
|
||||
"""
|
||||
return {
|
||||
"CJK": any(unicodedata.category(char) == "Lo" for char in string),
|
||||
"CYR": any(unicodedata.category(char) == "Lu" for char in string),
|
||||
}
|
||||
|
||||
|
||||
def unwrap(
|
||||
value: dbus.Array
|
||||
| dbus.Boolean
|
||||
| dbus.Byte
|
||||
| dbus.Dictionary
|
||||
| dbus.Double
|
||||
| dbus.Int16
|
||||
| dbus.ByteArray
|
||||
| dbus.Int32
|
||||
| dbus.Int64
|
||||
| dbus.Signature
|
||||
| dbus.UInt16
|
||||
| dbus.UInt32
|
||||
| dbus.UInt64
|
||||
| dbus.String,
|
||||
) -> str | int | list | tuple | float | dict | bool | bytes:
|
||||
"""Try to trivially translate a dictionary's elements into nice string formatting.
|
||||
|
||||
Arguments:
|
||||
value: A type out of:
|
||||
dbus.Boolean,
|
||||
dbus.Byte,
|
||||
dbus.Dictionary,
|
||||
dbus.Double,
|
||||
dbus.Int16,
|
||||
dbus.ByteArray,
|
||||
dbus.Int32,
|
||||
dbus.Int64,
|
||||
dbus.Signature,
|
||||
dbus.UInt16,
|
||||
dbus.UInt32,
|
||||
dbus.UInt64 and dbus.String
|
||||
|
||||
Returns:
|
||||
A str or int or list or tuple or float or dict or bool or bytes depending on the value.
|
||||
"""
|
||||
if isinstance(value, dbus.ByteArray):
|
||||
return "".join([str(byte) for byte in value])
|
||||
if isinstance(value, (dbus.Array, list, tuple)):
|
||||
return [unwrap(item) for item in value]
|
||||
if isinstance(value, (dbus.Dictionary, dict)):
|
||||
return dict([(unwrap(x), unwrap(y)) for x, y in value.items()])
|
||||
if isinstance(value, (dbus.Signature, dbus.String)):
|
||||
return str(value)
|
||||
if isinstance(value, dbus.Boolean):
|
||||
return bool(value)
|
||||
if isinstance(
|
||||
value,
|
||||
(dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64),
|
||||
):
|
||||
return int(value)
|
||||
if isinstance(value, dbus.Byte):
|
||||
return bytes([int(value)])
|
||||
return value
|
||||
|
||||
|
||||
def save_img_byte(px_args: typing.Iterable, save_path: str):
|
||||
"""Converts image data to an image file.
|
||||
|
||||
See <https://docs.gtk.org/gdk-pixbuf/ctor.Pixbuf.new_from_bytes.html> for the whole description.
|
||||
|
||||
Arguments:
|
||||
px_args: Should contain an iterable in the following format.
|
||||
[image_width, image_height, rowstride, has_alpha, bits_per_sample, _, image_bytes]
|
||||
save_path: the filepath where this pixbuf should be saved to.
|
||||
"""
|
||||
# https://specifications.freedesktop.org/notification-spec/latest/ar01s08.html
|
||||
# https://specifications.freedesktop.org/notification-spec/latest/ar01s05.html
|
||||
GdkPixbuf.Pixbuf.new_from_bytes(
|
||||
width=px_args[0],
|
||||
height=px_args[1],
|
||||
has_alpha=px_args[3],
|
||||
data=GLib.Bytes(px_args[6]),
|
||||
colorspace=GdkPixbuf.Colorspace.RGB,
|
||||
rowstride=px_args[2],
|
||||
bits_per_sample=px_args[4],
|
||||
).savev(save_path, "png")
|
||||
|
||||
|
||||
def get_gtk_icon_path(icon_name: str, size: int = 128) -> str:
|
||||
"""Returns the icon path by the specified name from your current icon theme.
|
||||
|
||||
Recursively search for lower sizes until 32x32 and
|
||||
return a fallback if the requested path does not exists.
|
||||
|
||||
Arguments:
|
||||
icon_name: Icon name as per the icon naming specification:
|
||||
<https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html>
|
||||
size: the pixel size (widthxheight -> heightxheight -> size) of the requested icon.
|
||||
"""
|
||||
if size < 32:
|
||||
return os.path.expandvars(
|
||||
"/usr/share/icons/Papirus-Dark/48x48/status/dialog-information.svg"
|
||||
)
|
||||
if info := Gtk.IconTheme.get_default().lookup_icon(icon_name, size, 0):
|
||||
return info.get_filename()
|
||||
return get_gtk_icon_path(icon_name, size - 1)
|
||||
|
||||
|
||||
def get_mime_icon_path(mimetype: str, size: int = 32) -> str:
|
||||
"""Gets the default icon path from the current GTK icon theme for the specified mime type.
|
||||
|
||||
Arguments:
|
||||
mimetype: The file type like png, json, etc.
|
||||
size: The of the returned icon
|
||||
|
||||
Returns:
|
||||
A str that is the path to the requested icon.
|
||||
"""
|
||||
icon = Gio.content_type_get_icon(mimetype)
|
||||
theme = Gtk.IconTheme.get_default()
|
||||
if info := theme.choose_icon(icon.get_names(), size, 0):
|
||||
return info.get_filename()
|
||||
|
||||
|
||||
def get_location() -> dict | None:
|
||||
try:
|
||||
response = requests.get("https://api64.ipify.org?format=json").json()
|
||||
ip_address = response["ip"]
|
||||
response = requests.get(f"https://ipapi.co/{ip_address}/json/").json()
|
||||
return {
|
||||
"latitude": response.get("latitude"),
|
||||
"longitude": response.get("longitude"),
|
||||
"city": response.get("city"),
|
||||
"country": response.get("country_name"),
|
||||
"lang": response.get("languages").split(",")[0],
|
||||
}
|
||||
except requests.exceptions.ConnectionError:
|
||||
return None
|
||||
|
||||
|
||||
def auto_locate(cache_dir: str) -> dict | None:
|
||||
cache_posix_path = pathlib.PosixPath(f"{cache_dir}/location.json")
|
||||
if not cache_posix_path.is_file(): # assuming the directory exists
|
||||
fetched_location = get_location()
|
||||
if not fetched_location:
|
||||
return None
|
||||
|
||||
cache_posix_path.write_text(json.dumps(fetched_location))
|
||||
return fetched_location
|
||||
return json.loads(cache_posix_path.read_text())
|
||||
|
||||
|
||||
def fetch_save(link: str, save_path: str, callback: typing.Callable = None) -> bool:
|
||||
try:
|
||||
data = requests.get(link)
|
||||
if data.status_code == 200:
|
||||
metadata = data.json()
|
||||
if callback:
|
||||
metadata = callback(metadata)
|
||||
pathlib.PosixPath(save_path).write_text(json.dumps(metadata))
|
||||
return True
|
||||
return False
|
||||
except requests.exceptions.ConnectionError:
|
||||
return False
|
||||
|
||||
|
||||
def img_dark_bright_col(filepath: str, colors: int = 10) -> tuple:
|
||||
with Image(filename=filepath) as image:
|
||||
image.quantize(
|
||||
number_colors=colors,
|
||||
colorspace_type=COLORSPACE_TYPES[21],
|
||||
dither=True,
|
||||
measure_error=False,
|
||||
treedepth=8,
|
||||
)
|
||||
return tuple(
|
||||
"#%02X%02X%02X" % (item.red_int8, item.green_int8, item.blue_int8)
|
||||
for item in image.histogram
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
match sys.argv[1]:
|
||||
case "histogram":
|
||||
image_path = sys.argv[2]
|
||||
histogram_colors = int(sys.argv[3])
|
||||
print(json.dumps(img_dark_bright_col(image_path, histogram_colors)))
|
||||
|
||||
# vim:filetype=python
|
||||
Reference in new issue
Block a user