-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backend.py
280 lines (225 loc) · 9.03 KB
/
Backend.py
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
from datetime import datetime
import os
import json
import logging
import re
import urllib.request
import dotenv # pip install dotenv_python
from flask import Flask, redirect, request, url_for, jsonify # pip install flask[async]
from spotipy import oauth2, Spotify # pip install spotipy
if not os.path.exists(".env"):
with open(".env", "w+") as f:
f.write(
"# To get SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET\n"
"# You need to create an application here\n"
"# https://developer.spotify.com/dashboard\n"
'# click "Create app"\n'
'# and set the "Redirect URI" to "http://localhost:3000/callback/"\n'
'# click "save"\n'
"# return to the dashboard and click on your app\n"
"# Click on settings\n"
'# You can already see the "Client ID"\n'
'# Click on "View client secret" and its your Client Secret\n'
'\n'
'# If you are lazy, contact me and I will give you my application creds\n'
'# You can contact me on my website with the "Want to send me a message?" text box\n'
"\n"
"SPOTIFY_CLIENT_ID = Client ID\n"
"SPOTIFY_CLIENT_SECRET =Client SECRET\n"
"SPOTIFY_CLIENT_URI = http://localhost:3000/callback/\n"
"SPOTIFY_SCOPE = user-read-playback-state user-read-currently-playing user-modify-playback-state app-remote-control\n"
"BACKEND_FLASK_PORT = 3000"
)
if not os.path.exists(rf"C:\Users\zakar\AppData\Roaming\astolfo\scripts\Spotify.lua"):
with open(rf"C:\Users\zakar\AppData\Roaming\astolfo\scripts\Spotify.lua", "w+") as f:
with urllib.request.urlopen("https://raw.githubusercontent.com/Appolon24800/AstolfoSpotify/main/Spotify.lua") as content:
f.write(content.read())
dotenv.load_dotenv()
logging.getLogger("werkzeug").setLevel(logging.ERROR)
os.system("cls")
os.system("title Astolfo backend (Spotify - ChatBridge)")
oldtrack = ""
oldmessage = ""
logfile = rf"C:\Users\{os.getlogin()}\AppData\Roaming\.minecraft\logs\latest.log"
app = Flask("Astolfo Client - Backend (chat_bridge & spotify)")
CLIENT_ID = os.environ.get("SPOTIFY_CLIENT_ID")
CLIENT_SECRET = os.environ.get("SPOTIFY_CLIENT_SECRET")
REDIRECT_URI = os.environ.get("SPOTIFY_CLIENT_URI")
FLASK_PORT = os.environ.get("BACKEND_FLASK_PORT")
SCOPE = os.environ.get("SPOTIFY_SCOPE")
if (
not CLIENT_ID
or not CLIENT_SECRET
or not REDIRECT_URI
or len(CLIENT_ID) != 32
or len(CLIENT_SECRET) != 32
or not "/callback/" in REDIRECT_URI
):
input()
raise ValueError("Invalid Spotify credentials. Check the '.env' file")
sp_oauth = oauth2.SpotifyOAuth(
CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, scope=SCOPE, cache_path=".cache"
)
def saveinfo(info):
with open(".cache", "w+") as f:
json.dump(info, f)
def getinfo():
try:
with open(".cache", "r+") as f:
return json.load(f)
except:
saveinfo({})
return {}
@app.route("/")
async def home():
return "<a>Astolfo python Backend for 'chat_bridge' and 'spotify'</a> <br> <a href='https://appolon.dev'>Made by appolon</a>"
@app.route("/login")
@app.route("/login/")
async def login():
return redirect(sp_oauth.get_authorize_url())
@app.route("/callback")
@app.route("/callback/")
async def callback():
code = request.args.get("code", None)
info = sp_oauth.get_access_token(code)
if not code or not info:
return
saveinfo(info)
return f"Success, you can now use the script. URL: 'http://localhost:{FLASK_PORT}/spotify'"
@app.route("/spotify/rewind")
@app.route("/spotify/rewind/")
async def spotify_rewind():
info = getinfo()
if not info or "access_token" not in info:
return redirect(url_for("login"))
if sp_oauth.is_token_expired(info):
try:
new_info = sp_oauth.refresh_access_token(info.get("refresh_token"))
access_token = new_info["access_token"]
info["access_token"] = access_token
info["expires_at"] = new_info["expires_at"]
saveinfo(info)
sp = Spotify(auth=access_token)
except Exception as e:
return jsonify({"Track": None, "Error": str(e)})
else:
sp = Spotify(auth=info["access_token"])
sp.previous_track()
return ""
@app.route("/spotify/skip")
@app.route("/spotify/skip/")
async def spotify_skip():
global oldtrack
info = getinfo()
if not info or "access_token" not in info:
return redirect(url_for("login"))
if sp_oauth.is_token_expired(info):
try:
new_info = sp_oauth.refresh_access_token(info.get("refresh_token"))
access_token = new_info["access_token"]
info["access_token"] = access_token
info["expires_at"] = new_info["expires_at"]
saveinfo(info)
sp = Spotify(auth=access_token)
except Exception as e:
return jsonify({"Track": None, "Error": str(e)})
else:
sp = Spotify(auth=info["access_token"])
sp.next_track()
return ""
@app.route("/spotify/pause")
@app.route("/spotify/pause/")
async def spotify_pause():
global oldtrack
info = getinfo()
if not info or "access_token" not in info:
return redirect(url_for("login"))
if sp_oauth.is_token_expired(info):
try:
new_info = sp_oauth.refresh_access_token(info.get("refresh_token"))
access_token = new_info["access_token"]
info["access_token"] = access_token
info["expires_at"] = new_info["expires_at"]
saveinfo(info)
sp = Spotify(auth=access_token)
except Exception as e:
return jsonify({"Track": None, "Error": str(e)})
else:
sp = Spotify(auth=info["access_token"])
trackinfo = sp.current_playback()
if trackinfo["is_playing"]:
sp.pause_playback()
else:
sp.start_playback()
return ""
@app.route("/spotify")
@app.route("/spotify/")
async def spotify():
global oldtrack
info = getinfo()
if not info or "access_token" not in info:
return redirect(url_for("login"))
if sp_oauth.is_token_expired(info):
try:
new_info = sp_oauth.refresh_access_token(info.get("refresh_token"))
access_token = new_info["access_token"]
info["access_token"] = access_token
info["expires_at"] = new_info["expires_at"]
saveinfo(info)
sp = Spotify(auth=access_token)
except Exception as e:
return jsonify({"Track": None, "Error": str(e)})
else:
sp = Spotify(auth=info["access_token"])
trackinfo = sp.current_playback()
if trackinfo is not None and "item" in trackinfo:
item = trackinfo.get("item")
try:
if oldtrack != item.get("name"):
print(f"\033[32m[\033[92mSpotify\033[32m]\033[0m '{item.get('name')}' by '{item['artists'][0].get('name')}'")
oldtrack = item.get("name")
return jsonify(
{
"Track": item.get("name"),
"TrackImage": trackinfo["item"]["album"]["images"][0]["url"],
"TrackID": item.get("id"),
"Artists": [
{
"Name": artist.get("name"),
"ID": artist.get("id"),
"Url": artist["external_urls"]["spotify"],
}
for artist in item.get("artists")
],
"Device": {
"Name": trackinfo["device"]["name"],
"Volume": trackinfo["device"]["volume_percent"],
"Type": trackinfo["device"]["type"],
},
"Playing": trackinfo["is_playing"],
"Duration": item.get("duration_ms"),
"Progress": trackinfo.get("progress_ms"),
}
)
except Exception as e:
return jsonify({"Track": None, "Error": e})
else:
return jsonify({"Track": None})
@app.route("/mc_chat", methods=["POST"])
@app.route("/mc_chat/", methods=["POST"])
async def mc_chat():
global oldmessage
message = request.args.get("msg")
if message:
message = (
re.sub(r"¥.{3}", "", message).replace("?C%AB", "✫").replace("?6%AC", "-")
)
time = datetime.now().strftime("[%H:%M:%S]")
if oldmessage != message:
print(f"\033[31m[\033[91mChatBridge\033[31m]\033[0m {message}")
oldmessage = message
with open(logfile, "a", encoding="utf-8") as f:
f.write(f"{time} [Astolfo HTTP Bridge]: [CHAT] {message}\n")
return ""
if __name__ == "__main__":
app.run("0.0.0.0", port=FLASK_PORT)