aboutsummaryrefslogtreecommitdiff
path: root/.config/i3/bin/elmord-i3status.py
blob: 819c30a69f0c6cf7b86d5ac6e7006c866974c622 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3

import json
import re
import sys
import time
from glob import glob
from pydbus import SessionBus

bus = SessionBus()

STATUS_UPDATE_PERIOD_MILLISECONDS = 1000
DESKTOP_NOTIFICATION_DURATION_SECONDS = 15

class NotificationMessage:
    MESSAGE_LENGTH = 117

    def __init__(self, app_name, summary, body):
        self.app_name = app_name
        self.summary = summary
        self.body = body.replace('\n', ' ')

    def to_components(self):
        if self.app_name == 'Slack':
            components = self.slack_message_to_components()

        elif self.app_name == 'Telegram Desktop':
            components = self.telegram_message_to_components()

        else:
            components = self.regular_message_to_components()

        length = sum(len(component['full_text']) for component in components)

        if length <= self.MESSAGE_LENGTH:
            components[-1]['full_text'] += ' ' * (self.MESSAGE_LENGTH - length)

        else:
            components[-1]['full_text'] = components[-1]['full_text'][:-(length - self.MESSAGE_LENGTH)]

        return components

    def regular_message_to_components(self):
        return [
            {
                'full_text': f'[{self.app_name}] ',
                'separator': False,
                'separator_block_width': 0,
            },
            {
                'full_text': self.summary,
                'color': '#00ffff',
                'separator': False,
                'separator_block_width': 0,
            },
            {
                'full_text': f': {self.body}',
            }
        ]

    def telegram_message_to_components(self):
        self.app_name = 'Telegram'
        return self.regular_message_to_components()

    def slack_message_to_components(self):
        sender = None
        channel = None
        body = self.body

        match = re.match(r'^New message from (.*)', self.summary)
        if match:
            sender = match.group(1)

        else:
            match = re.match(r'^New message in (.*)', self.summary)
            if match:
                channel = match.group(1)

            match = re.match(r'^([^:]*): (.*)', self.body)
            if match:
                sender = match.group(1)
                body = match.group(2)

        components = [
            {
                'full_text': '[Slack] ',
                'separator': False,
                'separator_block_width': 0,
            }
        ]

        if channel:
            components.extend([
                {'full_text': channel, 'color': '#00ff00',
                 'separator': False, 'separator_block_width': 0},
                {'full_text': ': ',
                 'separator': False, 'separator_block_width': 0},
            ])

        if sender:
            components.extend([
                {'full_text': sender, 'color': '#00ffff',
                 'separator': False, 'separator_block_width': 0},
                {'full_text': ': ',
                 'separator': False, 'separator_block_width': 0},
            ])

        components.append({'full_text': body})

        return components


class Notify:
    """
    <node>
      <interface name="org.freedesktop.Notifications">
        <method name="GetServerInformation">
          <arg name="return_name" type="s" direction="out"/>
          <arg name="return_vendor" type="s" direction="out"/>
          <arg name="return_version" type="s" direction="out"/>
          <arg name="return_spec_version" type="s" direction="out"/>
        </method>
        <method name="GetCapabilities">
          <arg name="return_caps" type="as" direction="out"/>
        </method>
        <method name="CloseNotification">
          <arg name="id" type="u" direction="in"/>
        </method>
        <method name="Notify">
          <arg name="app_name" type="s" direction="in"/>
          <arg name="id" type="u" direction="in"/>
          <arg name="icon" type="s" direction="in"/>
          <arg name="summary" type="s" direction="in"/>
          <arg name="body" type="s" direction="in"/>
          <arg name="actions" type="as" direction="in"/>
          <arg name="hints" type="a{sv}" direction="in"/>
          <annotation name="org.qtproject.QtDBus.QtTypeName.In6" value="QVariantMap"/>
          <arg name="timeout" type="i" direction="in"/>
          <arg name="return_id" type="u" direction="out"/>
        </method>
      </interface>
    </node>
    """

    def __init__(self):
        self.last_message = None
        self.last_message_time = 0

    def get_message_to_show(self):
        if time.time() - self.last_message_time < DESKTOP_NOTIFICATION_DURATION_SECONDS:
            return self.last_message.to_components()

        return []

    def Notify(self, app_name, id, icon, summary, body, actions, hints, timeout):
        #print("Notify", args)

        self.last_message = NotificationMessage(app_name, summary, body)
        self.last_message_time = time.time()
        emit_components()
        return 42

    def GetServerInformation(self, *args, **kwargs):
        #print("GetServerInformation", args, kwargs)
        return ("elmord-notify", "https://elmord.org", "0.0.1", "1")

    def GetCapabilities(self, *args, **kwargs):
        #print("GetCapabilities", args, kwargs)
        return ["body", "body-hyperlinks", "body-images"]

    def CloseNotification(self, *args, **kwargs):
        self.last_message_time = 0
        emit_components()
        #print("CloseNotification", args, kwargs)

notify = Notify()

try:
    bus.publish("org.freedesktop.Notifications", notify)
except RuntimeError as error:
    print(str(error), file=sys.stderr)

from gi.repository import GLib

loop = GLib.MainLoop()

[battery_directory] = glob('/sys/class/power_supply/BAT*/')

def get_battery_status():
    with open(f'{battery_directory}/capacity') as f:
        percentage = int(f.read().strip())

    with open(f'{battery_directory}/status') as f:
        status = f.read().strip()

    if status == 'Discharging':
        if percentage < 10:
            color = '#ff4040'
        elif percentage < 25:
            color = '#ffff00'
        else:
            color = '#ffffff'
    elif status in ['Charging', 'Full']:
        color = '#b0b0ff'
    else:
        color = '#ffffff'

    return [
        {
            'full_text': f'{percentage}%',
            'color': color,
        },
    ]

def emit_components():
    components = []
    components.extend(notify.get_message_to_show())
    components.extend([{'full_text': time.strftime('%a %b %d')}])
    components.extend([{'full_text': time.strftime("(%H:%M)", time.gmtime())}])
    components.extend([{'full_text': time.strftime('%H:%M')}])
    components.extend(get_battery_status())

    print(json.dumps(components), ",", flush=True)


def tick(*args, **kwargs):
    emit_components()
    GLib.timeout_add(STATUS_UPDATE_PERIOD_MILLISECONDS, tick)

def print_desktop_notification():
    print(last_desktop_notification_content, flush=True)

print('{"version": 1}\n[')

tick()
loop.run()