-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedis.py
More file actions
234 lines (191 loc) · 7.85 KB
/
Copy pathRedis.py
File metadata and controls
234 lines (191 loc) · 7.85 KB
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
import redis.asyncio as redis
from fastapi import Request, HTTPException
import json
# import logging
# logger = logging.getLogger("uvicorn.error")
async def CreateEmptyPlaylist(redis_client, playlist,user):
try:
playlist_name = playlist.get("name")
playlist_image = playlist.get("image")
playlist_desc= playlist.get("desc")
playlist_songs= playlist.get("songs")
playlist_id= playlist.get("id")
playlist_time= playlist.get("Time")
playlist_isPlaying= playlist.get("isPlaying")
key = f"user:{user}:playlist:{playlist_id}"
existing = await redis_client.get(key)
if existing:
# Playlist exists, load it
playlist = json.loads(existing)
else:
# Playlist doesn't exist, create new list and add playlist name to index
playlist = {"id": playlist_id,
"image": playlist_image,
"name": playlist_name,
"desc": playlist_desc,
"songs": playlist_songs,
"Time": playlist_time,
"isPlaying": playlist_isPlaying}
await redis_client.sadd(f"user:{user}:playlists:set", playlist_id)
# Save updated playlist back to Redis
await redis_client.set(key, json.dumps(playlist))
except Exception as e:
print(f"Error storing data: {e}")
async def EditPlaylist(redis_client, playlist, user, original_name=None):
try:
playlist_name = playlist.get("name")
# Use original name for lookup if provided
lookup_name = original_name or playlist_name
key = f"user:{user}:playlist:{lookup_name}"
existing = await redis_client.get(key)
if not existing:
return {"type": "error", "message": "Playlist not found"}
# If name changed, delete old key and create new one
new_key = f"user:{user}:playlist:{playlist_name}"
if key != new_key:
await redis_client.delete(key)
# Save updated playlist
updated_playlist = {
"id": playlist.get("id"),
"image": playlist.get("image"),
"name": playlist_name,
"desc": playlist.get("desc"),
"songs": playlist.get("songs", []),
"Time": playlist.get("Time", 0),
"isPlaying": playlist.get("isPlaying", False)
}
await redis_client.set(new_key, json.dumps(updated_playlist))
return {"type": "success", "message": "updated", "playlist": updated_playlist}
except Exception as e:
return {"type": "error", "message": str(e)}
async def delete_playlist(user: str, playlist_id: str, redis_client):
if not playlist_id or not user:
raise HTTPException(status_code=400, detail="Missing playlistId or user")
playlist_key = f"user:{user}:playlist:{playlist_id}"
# Check if playlist exists
if not await redis_client.exists(playlist_key):
raise HTTPException(status_code=404, detail="Playlist not found")
# Delete playlist data
await redis_client.delete(playlist_key)
# Remove from playlist set
await redis_client.srem(f"user:{user}:playlists:set", playlist_id)
return {
"status": "success",
"deleted": True,
"playlist_id": playlist_id
}
async def storeData(redis_client,playlist_id,new_song,user):
try:
key = f"user:{user}:playlist:{playlist_id}"
existing = await redis_client.get(key)
if existing:
playlist = json.loads(existing)
print("playlist value: ",playlist)
playlist["songs"].append(new_song)
playlist["Time"] = playlist["Time"] + new_song["duration"]
else:
# playlist = {
# "Time": None,
# "desc": "",
# "id": None,
# "image": None,
# "isPlaying": False,
# "name": playlist_name,
# "songs": [new_song]
# }
print("no playlists")
# await redis_client.sadd("playlists:set", playlist_name)
print("Playlist after adding song:",playlist)
await redis_client.set(key, json.dumps(playlist))
return {"type":"success"}
except Exception as e:
print(e)
return {"type": "error", "message": str(e)}
async def persistMusics(redis_client,searchedMusics,user):
try:
key = f"user:{user}:searched"
print(searchedMusics)
await redis_client.set(key, json.dumps(searchedMusics), ex=432000)
except Exception as e:
print(e)
async def getpersistMusics(redis_client, user):
try:
key = f"user:{user}:searched"
existing = await redis_client.get(key)
if existing is None:
return []
# Redis may return bytes or str depending on client config
if isinstance(existing, bytes):
existing = existing.decode("utf-8")
print(existing)
return json.loads(existing)
except Exception as e:
print("Error:", e)
return []
async def deletepersistMusics(redis_client, user):
try:
key = f"user:{user}:searched"
await redis_client.delete(key)
return {"success": True}
except Exception as e:
print("Error:",e)
return {"success": False }
# async def CreateEmptyPlaylist(redis_client,playlist):
# try:
# playlist_name = playlist.get("name")
# key = f"playlist:{playlist_name}"
# existing = await redis_client.get(key)
# if existing:
# return "playlist exists"
# else:
# playlist=[]
# await redis_client.sadd("playlists:set", playlist_name)
# await redis_client.set(key, json.dumps(playlist))
# except Exception as e:
# print(e)
async def get_all_playlists_as_array(redis_client,user):
try:
print(user)
playlist_id = await redis_client.smembers(f"user:{user}:playlists:set")
print(playlist_id)
playlists = []
for name_bytes in playlist_id:
playlist_id = name_bytes.decode() if isinstance(name_bytes, bytes) else name_bytes
key = f"user:{user}:playlist:{playlist_id}"
data = await redis_client.get(key)
if data:
playlist_data = json.loads(data)
else:
playlist_data = []
playlists.append({"id":playlist_id,"value": playlist_data})
print(playlists)
except Exception as e:
print("error",e)
return playlists
async def save_migrate_data_into_redis_temp(redis_client, data, client_id):
try:
# Define the Redis hash key
key = "hashMap:migratePlaylist"
# Use HSET to store the data for the given client_id in the hash map
await redis_client.hset(key, client_id, json.dumps(data)) # Serialize data using JSON
print(f"Data for client {client_id} successfully saved to Redis.")
return {"status": "success", "message": "Data saved to Redis."}
except Exception as e:
print(f"Error saving data for client {client_id}: {e}")
return {"status": "error", "message": str(e)}
except Exception as e:
print("error".e)
async def get_migrate_data_from_redis_temp(redis_client, client_id):
try:
key = "hashMap:migratePlaylist"
# Use HGET to retrieve the data for the given client_id
data = await redis_client.hget(key, client_id)
if data:
deserialized_data = json.loads(data) # Deserialize JSON back to Python object
await redis_client.hdel(key, client_id)
return deserialized_data
else:
return None # No data found for the given client_id
except Exception as e:
print(f"Error retrieving data for client {client_id}: {e}")
return None