-
Notifications
You must be signed in to change notification settings - Fork 0
/
media
337 lines (282 loc) · 13.5 KB
/
media
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2011 Eike Hein <[email protected]>
# The overall format of this script's output. The format of the individual
# elements referenced here is specified further below.
output_format = "/me 04$intro 07$info 06using 08$player. $xdcc"
# This is the '$intro' element in output_format.
intro_strings = {'audio': 'is 07listening 08to', 'video': 'is 07watching 08'}
# This is the '$info' element in output_format. You should not tinker with the
# case names on the left side of the colons.
format_strings = {
'Title+SelfTitled': "09$title11 by 13$artist (eponymous)",
'SelfTitled': "09${artist}'s self-titled album",
'Title+Artist+Album': "09$title11 by 13$artist 06on 04$album",
'Title+Artist': "09$title11 by 13$artist",
'Title+Album': "09$title06from 04$album",
'Album+Artist': "09$album11 by 13$artist",
'Title': "09$title",
'Artist': "09$artist",
'Album': "09$album"
}
# The lists below determine in which order the '/media', '/audio' and '/video'
# commands will query players if several of them are running. For '/audio'
# and '/video' they also determine which players are queried at all, however
# '/media' will query everything implementing the MPRIS2 standard, with un-
# listed players being queried last in alphabetical order.
# Entries should be the unique MPRIS2 bus names of players, i.e. the "amarok"
# part of "org.mpris.MediaPlayer2.amarok".
player_rankings = {
'all': ['amarok', 'cantata', 'juk', 'tomahawk', 'rhythmbox', 'banshee', 'clementine',
'audacious', 'spotify', 'dragonplayer', 'bangarang', 'vlc'],
'audio': ['amarok', 'cantata', 'juk', 'tomahawk', 'rhythmbox', 'banshee', 'audacious',
'clementine', 'spotify', 'pragha', 'gogglesmm', 'qmmp', 'gmusicbrowser',
'guayadeque', 'bangarang', 'dragonplayer', 'vlc'],
'video': ['dragonplayer', 'kaffeine', 'bangarang', 'vlc', 'smplayer', 'totem']
}
# When the generic '/media' command is used rather than '/audio' or '/video',
# the intro (see intro_strings) will be chosen based on the preferred media
# type of a player, specified here. If a player is not listed here, the
# 'audio' intro is used by default.
# Entries should be the unique MPRIS2 bus names of players, i.e. the "amarok"
# part of "org.mpris.MediaPlayer2.amarok".
preferred_media = {
'dragonplayer': 'video',
'kaffeine': 'video',
'smplayer': 'video',
'totem': 'video',
'vlc': 'video',
'SMPlayer2': 'video'
}
# To list players and retrieve media metadata his script by default calls the
# 'qdbus' command installed by Qt. If you need to you can change this here,
# but beware that the output format of the alternate command has to match that
# of 'qdbus'.
dbus_command = 'qdbus'
# If one of the title, album or artist metadata fields contains a character
# listed in FIXUP_CHARS, or if a string matching the regular expression given
# in REGEX_FIXUP is found in one of them, the respective field's text is
# surrounded by QUOTE_BEFORE and QUOTE_AFTER.
SIMPLE_FIXUP = '' # e.g. ' ' or '-'
REGEX_FIXUP = ''
QUOTE_BEFORE = '"'
QUOTE_AFTER = '"'
# ===== Do not change anything below this line. =====
import collections
import os.path
import re
import subprocess
import string
import sys
try:
from urllib.parse import unquote_plus, urlsplit
except ImportError:
from urllib import unquote_plus
from urlparse import urlsplit
try:
import konversation.dbus
konversation.dbus.default_message_prefix = 'media: '
import konversation.i18n
konversation.i18n.init()
except ImportError:
sys.exit("This script is intended to be run from within Konversation.")
if sys.hexversion < 0x02070000:
err = i18n("The media script requires Python %1 or higher.", '2.7')
konversation.dbus.error(err)
sys.exit(err)
Player = collections.namedtuple('player', ('busname', 'name', 'identity', 'hastrack'))
class PlayerList(list):
def insert(self, player, type='all'):
try:
index = player_rankings[type].index(player.name)
list.insert(self, index, player)
except ValueError:
list.append(self, player)
def is_specific_player(kind):
return kind is not None and kind not in ('audio', 'video')
def fetch_property(busname, attribute):
output = subprocess.check_output((dbus_command, busname, '/org/mpris/MediaPlayer2', attribute))
return output.decode(encoding='utf-8', errors='replace').strip()
def list_players():
running = PlayerList()
audio = PlayerList()
video = PlayerList()
eligible = PlayerList()
try:
output = subprocess.check_output((dbus_command, 'org.mpris.MediaPlayer2.*'))
except subprocess.CalledProcessError:
konversation.dbus.error(i18n("An error occurred while trying to list the running media players."), exit=True)
for line in output.decode(errors='replace').splitlines():
try:
busname = line
name = busname.split('.')[3]
identity = fetch_property(busname, 'org.mpris.MediaPlayer2.Identity')
hastrack = fetch_property(busname, 'org.mpris.MediaPlayer2.Player.PlaybackStatus')
# If this is a player-specific invocation, consider both paused and playing states
if is_specific_player(requested):
hastrack = hastrack in ('Playing', 'Paused')
else:
hastrack = hastrack == 'Playing'
player = Player(busname, name, identity, hastrack)
running.insert(player)
if name in player_rankings['audio']:
audio.insert(player, 'audio')
if name in player_rankings['video']:
video.insert(player, 'audio')
except (subprocess.CalledProcessError, IndexError):
pass
if requested == 'audio':
eligible = audio
elif requested == 'video':
eligible = video
elif requested is not None:
eligible = filter_by_name(running, requested)
else:
eligible = running
eligible = [player for player in eligible if player.hastrack]
return running, audio, video, eligible
def filter_by_name(player_list, name):
return [player for player in player_list if player.name.lower() == name or player.identity.lower() == name]
def check_running():
if requested == 'audio' and not players_audio:
konversation.dbus.error(i18n("No running audio players found.", requested), exit=True)
elif requested == 'video' and not players_video:
konversation.dbus.error(i18n("No running video players found.", requested), exit=True)
elif is_specific_player(requested) and not filter_by_name(players_running, requested):
konversation.dbus.error(i18n("\"%1\" is not running.", requested), exit=True)
elif not players_running:
konversation.dbus.error(i18n("No running media players found.", exit=True))
def check_playing():
if not players_eligible:
if requested == 'audio':
players = players_audio
elif requested == 'video':
players = players_video
elif requested is not None:
players = filter_by_name(players_running, requested)
else:
players = players_running
if len(players) == 1:
konversation.dbus.error(i18n("Nothing is playing in %1.", players[0].identity), exit=True)
else:
if requested == 'audio':
konversation.dbus.error(i18nc("1 = Comma-separated list of audio players.",
"None of the running audio players (%1) are playing anything.",
', '.join([player.identity for player in players])),
exit=True)
elif requested == 'video':
konversation.dbus.error(i18nc("1 = Comma-separated list of video players.",
"None of the running video players (%1) are playing anything.",
', '.join([player.identity for player in players])),
exit=True)
elif requested is not None:
konversation.dbus.error(i18nc("1 = Comma-separated list of players.",
"None of the running instances of %1 are playing anything.",
', '.join([player.identity for player in players])),
exit=True)
else:
konversation.dbus.error(i18nc("1 = Comma-separated list of players.",
"None of the running media players (%1) are playing anything.",
', '.join([player.identity for player in players])),
exit=True)
def get_metadata(player):
try:
output = fetch_property(player.busname, 'org.mpris.MediaPlayer2.Player.Metadata')
except subprocess.CalledProcessError:
konversation.dbus.error(i18n("An error occurred while trying to retrieve media metadata from %1.", player.identity), exit=True)
keys = ('xesam:title', 'xesam:artist', 'xesam:albumArtist', 'xesam:album', 'xesam:url')
metadata = dict()
search_filename = None
for line in output.splitlines():
for key in keys:
if line.startswith(key):
key = key.split(':')[1]
value = line.split(':', 2)[-1].strip()
if value:
metadata[key] = value
# Extract the filename from the URL for searching purposes
if 'url' in metadata:
url = urlsplit(metadata['url'])
if url.scheme == 'file' and url.path:
search_filename = os.path.basename(unquote_plus(url.path))
else:
search_filename = os.path.basename(url.path)
# Use filename as title if title is not available
if 'title' not in metadata and search_filename:
metadata['title'] = search_filename
return metadata, search_filename
def find_pack_number(filename):
try:
with open('/path/to/mybot.txt', 'r') as file:
for line in file:
if filename in line:
pack_number = line.split('#')[1].split()[0].strip() # Extracting only the pack number
return pack_number
except FileNotFoundError:
konversation.dbus.error(i18n("mybot.txt file not found."), exit=True)
except IndexError:
konversation.dbus.error(i18n("Pack number not found in mybot.txt."), exit=True)
def format(player, metadata):
fixup(metadata)
format_key = [x for x in list(metadata) if x in ('album', 'artist', 'title')]
if not format_key:
konversation.dbus.error(i18n("%1 did not report the metadata needed to output a message.", player.identity), exit=True)
try:
if metadata['album'] == metadata['artist']:
format_key.remove('album')
format_key.remove('artist')
format_key.append('selftitled')
except KeyError:
pass
format_key = '+'.join(sorted(format_key))
format = {'+'.join(sorted(k.lower().split('+'))): v for (k, v) in format_strings.items()}[format_key]
if format:
info = string.Template(format).safe_substitute(metadata)
else:
konversation.dbus.error(i18n("There is a problem in the output format configuration."), exit=True)
if requested in ('audio', 'video'):
intro = intro_strings[requested]
else:
try:
intro = intro_strings[preferred_media[player.name]]
except KeyError:
intro = intro_strings['audio']
# Adding XDCC download message
pack_number = find_pack_number(metadata['search_filename'])
xdcc_message = f'09Type 11"/msg mybot XDCC GET {pack_number}" 13to 06download 04{metadata["search_filename"]}!' if pack_number else ''
output = dict(intro=intro, info=info, player=player.identity, xdcc=xdcc_message)
return string.Template(output_format).safe_substitute(output)
def fixup(metadata):
if SIMPLE_FIXUP or REGEX_FIXUP:
for key in ('title', 'album', 'artist'):
if key in metadata:
if SIMPLE_FIXUP:
if SIMPLE_FIXUP in metadata[key]:
metadata[key] = QUOTE_BEFORE + metadata[key] + QUOTE_AFTER
if REGEX_FIXUP:
if re.search(REGEX_FIXUP, metadata[key]):
metadata[key] = QUOTE_BEFORE + metadata[key] + QUOTE_AFTER
if __name__ == '__main__':
if not konversation.dbus.target:
version = '3'
indent = ' '
i = konversation.dbus.info
i(i18n("media v%1 for Konversation.", version))
i(i18n("Usage:"))
i(indent + i18n("\"/media\" - report what the first player found is playing."))
i(indent + i18n("\"/media [ 'audio' | 'video' ]\" - report what is playing in a known audio or video player."))
i(indent + i18n("\"/media { Player }\" - report what is playing in the specified player if it is found."))
else:
try:
requested = sys.argv[3].lower().strip()
except IndexError:
requested = None
players_running, players_audio, players_video, players_eligible = list_players()
check_running()
check_playing()
player = players_eligible[0]
metadata, search_filename = get_metadata(player)
metadata['search_filename'] = search_filename
konversation.dbus.say(format(player, metadata), '')