aboutsummaryrefslogtreecommitdiffstats
path: root/i3wm/.bin/spotifycl
blob: 4cd6943c3f5a8e54d5ee494e0199ce8c86aeb1aa (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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env python

# MIT License
#
# Copyright (c) 2018 Andreas Backx
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


import os
import socket
import sys
import time
import traceback
from concurrent.futures import ThreadPoolExecutor

import click
import dbus
import dbus.mainloop.glib
import spotipy
import spotipy.util as util
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from spotipy import SpotifyException
from spotipy.oauth2 import SpotifyClientCredentials

inactive_color = '%{F#6E6E6E}'
active_color = '%{F#CECECE}'
default_color = '%{F-}'

server_address = '/tmp/spotifycl-socket'


class Spotify:

    SPOTIFY_BUS = 'org.mpris.MediaPlayer2.spotify'
    SPOTIFY_OBJECT_PATH = '/org/mpris/MediaPlayer2'

    PLAYER_INTERFACE = 'org.mpris.MediaPlayer2.Player'
    PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'

    SAVE_REMOVE = b'save'

    def __init__(self):
        DBusGMainLoop(set_as_default=True)
        self.session_bus = dbus.SessionBus()
        self.last_output = ''
        self.empty_output = True

        # Last shown metadata
        self.last_title = None
        # Whether the current song is added to the library
        self.saved_track = False
        # Whether to ignore the update
        self.ignore = False

        #self.setup_spotipy()

    def monitor(self):
        self.setup_properties_changed()
        self.freedesktop = self.session_bus.get_object(
            "org.freedesktop.DBus",
            "/org/freedesktop/DBus"
        )
        self.freedesktop.connect_to_signal(
            "NameOwnerChanged",
            self.on_name_owner_changed,
            arg0="org.mpris.MediaPlayer2.spotify"
        )

        executor = ThreadPoolExecutor(max_workers=2)
        executor.submit(self._start_glib_loop)
        executor.submit(self._start_server)

    def _start_glib_loop(self):
        loop = GLib.MainLoop()
        loop.run()

    def _start_server(self):
        try:
            os.unlink(server_address)
        except OSError:
            if os.path.exists(server_address):
                raise
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.bind(server_address)
        sock.listen(5)

        while True:
            connection, client_address = sock.accept()
            try:
                command = connection.recv(16)

                if command == Spotify.SAVE_REMOVE:
                    self.save_remove()
            except Exception as e:
                print(e)
            finally:
                connection.close()

    def stop_server(self):
        self.server_loop.close()

    def send_to_server(self, command: bytes):
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            sock.connect(server_address)
        except socket.error:
            raise

        try:
            sock.sendall(command)
        finally:
            sock.close()

    @property
    def metadata_status(self):
        spotify_properties = dbus.Interface(
            self.spotify,
            dbus_interface=Spotify.PROPERTIES_INTERFACE
        )
        metadata = spotify_properties.Get(
            Spotify.PLAYER_INTERFACE,
            'Metadata'
        )
        playback_status = spotify_properties.Get(
            Spotify.PLAYER_INTERFACE,
            'PlaybackStatus'
        )
        return metadata, playback_status

    def setup_spotipy(self):
        auth = util.prompt_for_user_token(
            username=os.environ.get('SPOTIFY_USERNAME'),
            scope='user-library-read,user-library-modify'
        )
        self.spotipy = spotipy.Spotify(auth=auth)

    def save_remove(self, retry=False):
        try:
            metadata, playback_status = self.metadata_status
            trackid = metadata['mpris:trackid']

            self.ignore = True
            remove = self.saved_track
            self.saved_track = not self.saved_track
            try:
                if remove:
                    self.spotipy.current_user_saved_tracks_delete(tracks=[trackid])
                    self.output(f'{active_color}Removed from library!{default_color}')
                else:
                    self.spotipy.current_user_saved_tracks_add(tracks=[trackid])
                    self.output(f'{active_color}Saved to library!{default_color}')
            except SpotifyException:
                if not retry:
                    # Refresh access token
                    self.setup_spotipy()
                    self.save_remove(retry=True)
                    return
                else:
                    raise
            time.sleep(2)
            self.ignore = False

            metadata, playback_status = self.metadata_status
            self.output_playback_status(
                data={
                    'Metadata': metadata,
                    'PlaybackStatus': playback_status,
                }
            )

        except dbus.DBusException:
            self.output('Could not connect to spotify.')

    def output(self, line):
        if not line:
            self.empty_output = True
        if line != self.last_output:
            print(line, flush=True)
            self.last_output = line

    def setup_spotify(self):
        self.spotify = self.session_bus.get_object(
            Spotify.SPOTIFY_BUS,
            Spotify.SPOTIFY_OBJECT_PATH
        )

    def setup_properties_changed(self):
        try:
            self.setup_spotify()
            self.spotify.connect_to_signal(
                'PropertiesChanged',
                self.on_properties_changed
            )

            if self.empty_output:
                metadata, playback_status = self.metadata_status
                self.output_playback_status(
                    data={
                        'Metadata': metadata,
                        'PlaybackStatus': playback_status,
                    }
                )

        except dbus.DBusException:
            self.output('')

    def output_playback_status(self, data, retry=False):
        if self.ignore:
            return

        metadata = data['Metadata']
        artists = metadata['xesam:artist']
        artist = artists[0] if artists else None

        if not artist:
            self.output('')
            return

        title = metadata['xesam:title']
        playback_status = data['PlaybackStatus']
        same_song = title == self.last_title

        color = active_color if playback_status == 'Playing' else inactive_color
        # divider = '+' if same_song and self.saved_track else '-'
        self.output(f'{color}{artist} - {title}{default_color}')

        if not same_song:
            self.last_title = title
            trackid = metadata['mpris:trackid']

            # try:
            #     self.update_saved_track(trackid=trackid)
            # except SpotifyException:
            #     # Refresh access token
            #     self.setup_spotipy()
            #     self.update_saved_track(trackid=trackid)
            # if self.saved_track:
            #     divider = '+'
            #     self.output(f'{color}{artist} {divider} {title}{default_color}')

    def update_saved_track(self, trackid: str):
        self.saved_track = self.spotipy.current_user_saved_tracks_contains(
            tracks=[trackid]
        )[0]

    def on_properties_changed(self, interface, data, *args, **kwargs):
        self.output_playback_status(data)

    def on_name_owner_changed(self, name, old_owner, new_owner):
        if name == 'org.mpris.MediaPlayer2.spotify':
            if new_owner:
                # Spotify was opened.
                self.setup_properties_changed()
            else:
                # Spotify was closed.
                self.spotify = None
                self.output('')


@click.group()
def cli():
    """Script for listening to Spotify over dbus and adding tracks to your library."""
    pass


@cli.command()
def status():
    """Follow the status of the currently playing song on Spotify."""
    spotify = Spotify()
    spotify.monitor()


# @cli.command()
# def save_remove():
#     """Save/remove the currently playing song to/from your library."""
#     spotify = Spotify()
#     spotify.send_to_server(Spotify.SAVE_REMOVE)


if __name__ == '__main__':
    cli()