-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.pyw
371 lines (301 loc) · 13 KB
/
main.pyw
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from logging.handlers import RotatingFileHandler
from datetime import datetime
import threading
import traceback
import logging
import ctypes
import time
import json
import sys
import os
from PIL import Image
from pystray import Menu, MenuItem
import flet as ft
import webbrowser
import pypresence
import winshell
import pystray
import pylast
ctypes.windll.shcore.SetProcessDpiAwareness(True) # Avoids blurry context menu
rotating_file_handler = RotatingFileHandler(
filename="log.txt", mode="a", maxBytes=5*1024*1024,
backupCount=1, encoding="utf-8", delay=0)
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S", handlers=[rotating_file_handler])
for l in logging.root.manager.loggerDict:
logging.getLogger(l).setLevel(logging.WARNING)
class LastPresence:
"""Takes your current song in Last.fm, puts it in your Discord profile."""
def __init__(self):
self.apps = {
"Last.fm": "1131823801454297190",
"Music": "1204332455729827900",
"YT Music": "1204315253085839371",
"YouTube Music": "1204329359616376882",
"Apple Music": "1204329881563828274",
"Tidal": "1204332410872004628"}
self.shortcut_startup_path = os.path.join(
os.getenv("appdata"),
"Microsoft\\Windows\\Start Menu\\Programs\\Startup",
"Last.presence.lnk")
self.last_track = None
self.last_track_timestamp = None
self.tray_icon = None
self.load_and_check_settings()
self.setup_lastfm()
self.setup_rpc()
def load_and_check_settings(self):
"""Load settings.json and warn user if settings are default."""
default_settings = {
"username": "",
"lastfm_api_key": "",
"discord_rpc_presence": "1131823801454297190",
"rpc_enabled": True,
"profile_button_enabled": True}
try:
with open("settings.json") as f:
self.settings = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
self.settings = default_settings
for setting in ("username", "lastfm_api_key"):
if not self.settings[setting]:
ft.app(target=self.configuration_page)
break
for setting in ("username", "lastfm_api_key"):
if not self.settings[setting]:
sys.exit(0)
def save_settings(self):
with open("settings.json", "w") as f:
json.dump(self.settings, f, indent=4)
def configuration_page(self, page: ft.Page):
"""Setup page shown to user when first using the app."""
page.title = "Last.presence"
page.padding = 40
page.window.width = 600
page.window.height = 450
page.window.center()
page.window.resizable = False
page.window.maximizable = False
center = ft.MainAxisAlignment.CENTER
container_description = ft.Container(content=ft.Text(
"Enter the Last.fm username you want to use, and an API key "
"obtained from Last.fm.",
size=20, width=500, text_align=ft.TextAlign.CENTER))
container_description.margin = ft.margin.only(bottom=40)
username = ft.TextField(
label="Last.fm username", value=self.settings["username"],
autofocus=True, width=400)
api_key = ft.TextField(
label="Last.fm API key", value=self.settings["lastfm_api_key"],
width=400)
container_api_key = ft.Container(content=api_key)
container_api_key.margin = ft.margin.only(bottom=40)
def continue_click(_):
network = pylast.LastFMNetwork(api_key=api_key.value)
user = network.get_user(username.value)
try:
user.get_playcount()
except pylast.WSError:
page.dialog = failure_dialog
failure_dialog.open = True
page.update()
else:
self.settings["username"] = username.value
self.settings["lastfm_api_key"] = api_key.value
self.save_settings()
page.dialog = success_dialog
success_dialog.open = True
page.update()
def create_api_click(_, *args):
webbrowser.open("http://last.fm/api/account/create")
def close_failure_dialog(_):
failure_dialog.open = False
page.update()
def close_success_dialog(_):
page.window_close()
continue_button = ft.FilledButton(
"Continue", on_click=continue_click)
create_api_button = ft.OutlinedButton(
"Create API key", on_click=create_api_click)
failure_dialog = ft.AlertDialog(
title=ft.Text("Error"),
content=ft.Text("Invalid username or API key, please re-check."),
actions=[ft.TextButton(
"OK", on_click=close_failure_dialog, autofocus=True)])
success_dialog = ft.AlertDialog(
title=ft.Text("Setup successful"),
content=ft.Text(
"Last.presence will run in your taskbar as a tray icon. "
"Right-click it for settings."),
actions=[ft.TextButton(
"Finish", on_click=close_success_dialog, autofocus=True)])
page.add(
ft.Row([container_description], alignment=center),
ft.Row([username], alignment=center),
ft.Row([container_api_key], alignment=center),
ft.Row([continue_button, create_api_button], alignment=center))
def setup_lastfm(self):
"""Set up Last.fm."""
self.network = pylast.LastFMNetwork(
api_key=self.settings["lastfm_api_key"])
self.user = self.network.get_user(self.settings["username"])
logging.info(f"Connected as {self.user.name}")
def setup_rpc(self):
"""Set up Discord RPC."""
self.rpc = pypresence.Presence(self.settings["discord_rpc_presence"])
while True:
try:
self.rpc.connect()
logging.info(f"Connected to Discord RPC")
break
except pypresence.exceptions.DiscordNotFound:
logging.error("Discord not found, retrying in 10s")
time.sleep(10)
def close(self):
"""Clean things up and close cleanly."""
self.rpc.close()
self.tray_icon.stop()
logging.info("Closed RPC and tray icon cleanly")
def run_tray_icon(self):
"""Create and run tray icon that contains settings."""
def toggle_setting(setting_name, tray_item):
"""Helper function to alter and save a setting tweak."""
self.settings[setting_name] = not tray_item.checked
self.save_settings()
def show_setup(_, item):
"""Let user reconfigure username and API key."""
username = self.settings["username"]
api_key = self.settings["lastfm_api_key"]
ft.app(target=self.configuration_page)
new_username = self.settings["username"]
new_api_key = self.settings["lastfm_api_key"]
if username == new_username and api_key == new_api_key:
return
self.close()
os.execv(
sys.executable, [os.path.basename(sys.executable)] + sys.argv)
def set_rpc(_, item):
"""Allows or prevents RPC from updating while script is running."""
toggle_setting("rpc_enabled", item)
if self.settings["rpc_enabled"]:
self.update_presence(force_update=True)
else:
self.rpc.clear()
def set_startup(_, item):
"""Creates or removes startup shortcut for the script."""
if os.path.exists(self.shortcut_startup_path):
os.remove(self.shortcut_startup_path)
logging.info(f"Removed {self.shortcut_startup_path} shortcut")
return
file_path = sys.executable
with winshell.shortcut(self.shortcut_startup_path) as link:
link.path = file_path
link.working_directory = os.path.dirname(file_path)
logging.info(f"Created shortcut at {self.shortcut_startup_path}")
def set_button(_, item):
toggle_setting("profile_button_enabled", item)
self.update_presence(force_update=True)
def set_app(_, item):
"""Alters name shown to right of 'Playing' and above song name."""
app_id = self.apps[str(item)]
self.settings["discord_rpc_presence"] = app_id
self.save_settings()
self.rpc.close()
self.setup_rpc()
self.update_presence(force_update=True)
def open_log(_, item):
os.startfile("log.txt")
@staticmethod
def check_app(item):
app_id = self.apps[str(item)]
return app_id == self.settings["discord_rpc_presence"]
check_rpc = lambda _: self.settings["rpc_enabled"]
check_button = lambda _: self.settings["profile_button_enabled"]
check_startup = lambda _: os.path.exists(self.shortcut_startup_path)
app_names = []
for app in self.apps:
app_names.append(MenuItem(app, set_app, check_app, radio=True))
menu = Menu(
MenuItem(f"Connected as {lastpresence.user.name}", show_setup),
MenuItem("Enable Last.presence", set_rpc, check_rpc),
MenuItem("Run at startup", set_startup, check_startup),
Menu.SEPARATOR,
MenuItem("Application name", Menu(*app_names)),
MenuItem("Show profile button", set_button, check_button),
Menu.SEPARATOR,
MenuItem("Open log file", open_log),
MenuItem('Quit', self.close))
name = "Last.presence"
icon = Image.open(os.path.join(sys._MEIPASS, "icon.ico"))
self.tray_icon = pystray.Icon(name, icon, name, menu)
self.tray_icon.run()
def update_presence(self, force_update=False):
"""Look for current playing track and update presence accordingly."""
if not self.settings["rpc_enabled"]:
return
track = self.user.get_now_playing()
if track != self.last_track:
self.last_track = track
self.last_track_timestamp = datetime.now().timestamp()
elif not force_update:
return
self.last_track = track
if track == None:
self.rpc.clear()
logging.info("No song detected, cleared rich presence.")
return
album = track.get_album()
cover = track.get_cover_image()
duration = track.get_duration()
details = track.title.ljust(2)[:128]
state = track.artist.name.ljust(2)[:128]
large_text = None
end = None
button = None
if album:
state = f"{track.artist.name} • {album.title}"[:128]
large_text = f"Album: {album.title}"[:128]
if duration:
end = self.last_track_timestamp + (duration / 1000)
if not cover or "2a96cbd8b46e442fc41c2b86b821562f" in cover:
cover = "https://files.catbox.moe/qqh1rn.png"
if self.settings["profile_button_enabled"]:
button = [{
"label": "View listening profile",
"url": f"https://last.fm/user/{self.user.name}"}]
self.rpc.update(
details=details, state=state, end=end, large_image=cover,
large_text=large_text, buttons=button)
logging.info(f"Updated: {track.artist.name} - {track.title}")
def presence_update_loop(self):
"""Main loop responsible for updating presence."""
while True:
try:
lastpresence.update_presence()
except pypresence.exceptions.PipeClosed:
logging.warning("Restarting connection to Discord RPC")
self.setup_rpc()
lastpresence.update_presence(force_update=True)
except pylast.WSError as e:
if str(e) == "Track not found":
logging.warning(
"Track not found. It's possible you're scrobbling "
"something very recently added to Last.fm")
elif str(e).endswith("HTTP code 500"):
logging.warning(
"Connection to Last.fm API failed with HTTP code 500. "
"Your internet or Last.fm may be down")
else:
logging.warning(f"pylast.WSError '{e}'")
except pylast.NetworkError as e:
logging.warning(f"pylast.NetworkError '{e}'")
except (pylast.PyLastError, pypresence.PyPresenceException):
logging.warning(traceback.format_exc())
time.sleep(10)
if __name__ == "__main__":
lastpresence = LastPresence()
thread = threading.Thread(target=lastpresence.presence_update_loop)
thread.daemon = True
thread.start()
lastpresence.run_tray_icon()