Skip to content

Commit

Permalink
Update for 0.3
Browse files Browse the repository at this point in the history
0.3 Update : Playlists map edition (beta)
  • Loading branch information
OwOchle authored Mar 28, 2021
1 parent 34bf672 commit f85d3ad
Show file tree
Hide file tree
Showing 9 changed files with 333 additions and 32 deletions.
41 changes: 41 additions & 0 deletions addMap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import json
from requests import get


def getmap(code):
headers = {
'User-Agent': 'Playlist Manager DOS/0.1 (https://github.com/Moreo18/Playlist-Manager-DOS)'}
url = 'https://beatsaver.com/api/maps/detail/'
req = get(url + code, headers=headers)
if req.status_code == 404:
print(f'Sorry, the map {code} seems to be inaccessible, either it does not exist, either Beat Saver is unavailable.\n')
return None, None

mapinf = json.loads(req.content)
print(f'\nAdded {mapinf["name"]}, Mapper : {mapinf["metadata"]["levelAuthorName"]}, Rating : {int((mapinf["stats"]["rating"] * 100))}%')
return mapinf['metadata']['songName'], mapinf['hash']


def addmap(PLpath, playlistfile):
pl = open(PLpath + playlistfile).read()
pl = json.loads(pl)
if not 'songs' in pl:
pl['songs'] = []
print(' ')
print(pl['playlistTitle'] + ' :')
while True:
nmap = input('Enter the code of the map you want to add to your playlist or type Exit to stop editing the playlist (you can add multiple maps by separating codes with commas)\n')
if nmap.upper() == 'EXIT':
break
else:
nmap = nmap.replace(' ', '').split(',')
for item in nmap:
title, hashm = getmap(item)
if not title or not hashm:
continue
for item2 in pl['songs']:
if item2['hash'] == hashm.upper():
print('The map is already in playlist')
pl['songs'].append({'songName': title, 'hash': hashm.upper()})
with open(PLpath + playlistfile, 'w') as f:
json.dump(pl, f)
2 changes: 1 addition & 1 deletion checkPath.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ def chech_path(path):
if not os.path.exists(path + 'Playlists'):
print('Cannot find Playlists folder, please check the path.\nPress Enter to close.')
input()
exit(1)
exit(1)
68 changes: 68 additions & 0 deletions editInfo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import json
import os
from base64 import b64encode
from ShowB64Image import *


def edit_info(PLpath, plfilepath):
plfile = open(PLpath + plfilepath, 'r', encoding='utf-8')
pl = json.loads(plfile.read())
plfile.close()
print(f'\n\nThe current playlist title is "{pl["playlistTitle"]}"')
name = input('Type the new title or press Enter to keep the old one\n')
if name != '':
pl["playlistTitle"] = name

print(f'The current playlist author is "{pl["playlistAuthor"]}"')
author = input('Type the new author or press Enter to keep the old one\n')

if author != '':
pl["playlistAuthor"] = author

print(f'The current description is "{pl["playlistDescription"]}"')
desc = input('Type the new description or press Enter to keep the old one\n')

if desc != '':
pl["playlistDescription"] = desc

images = os.listdir('./Images')
print('\n')
print('If there is one, the current image should open in your default image gallery')
if pl['image']:
try:
show_base64_image(pl['image'])
except Exception:
print('Something went wrong when trying to open the image')
for item in range(len(images)):
print(f'{item + 1}: {images[item - 1]}')
cim = input('Type the number of the image you want, leave empty if you want to keep the old one or type 0 to delete the cover : ')
if cim == '':
im = ''

else:
cont = True
while cont:
try:
cim = int(cim) - 1
if cim + 1 == 0:
pl.pop('image')
print('Cover removed')
cont = False
elif cim + 1 <= 0 or cim + 1 > len(images):
print('The number you entered is not in range\nPlease enter another one : ')
input()
else:
cont = False
except ValueError:
print('Please enter a correct value : ')
input()
if cim != -1:
im = b64encode(open(f'./Images/{images[item]}', 'rb').read())
else:
im = ''

if im != '':
pl['image'] = f'data:image/png;base64,{im}'

plfile = open(PLpath + plfilepath, 'w', encoding='utf-8')
json.dump(pl, plfile)
1 change: 1 addition & 0 deletions getHash.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from requests import get
import sys


def gethash(path):
try:
# Open the file to use it in hash encoding and difficulties
Expand Down
59 changes: 35 additions & 24 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import json
from plDownloading import *
from checkPath import *
from PLnew import *
from EditInfo import *
from newPl import *
from editInfo import *
from os import mkdir
from addMap import addmap
from remMap import *

try:
mkdir('Images')
Expand Down Expand Up @@ -46,55 +48,64 @@
print(f'{n}: {item["title"]}')
n += 1

pldl = input('Type the number of the playlist you want to select or type "new" to create a new playlist\n')
try:
while True:
if pldl != 'new':
pldl = int(pldl) - 1
if pldl + 1 <= 0 or pldl + 1 >= n:
print('The number you entered is not in range.')
pldl = input('Please retry\n')
loop = True
selpl = input('Type the number of the playlist you want to select, type "new" to create a new playlist or type "refresh" to refresh all your songs\n')
while loop:
try:
while loop:
if selpl.upper() == 'EXIT':
exit(0)
if selpl.upper() != 'NEW':
selpl = int(selpl) - 1
if selpl + 1 <= 0 or selpl + 1 >= n:
print('The number you entered is not in range.')
selpl = input('Please retry\n')
else:
loop = False
else:
break
else:
break
except ValueError:
print('Please enter a correct value.\nPress Enter to close.')
input()
exit(1)
loop = False
except ValueError:
selpl = input('Please enter a correct value\n')

if pldl == 'new':

if selpl == 'new':
pl_create(PLpath)
else:
while True:
print('\n\nWhat do you want to do with this playlist :')
print('delete, addmap, removemap, editinfo, download, exit')
commands = ['DELETE', 'ADDMAP', 'REMOVEMAP', 'EDITINFO', 'DOWNLOAD', 'EXIT']
commands = ['DELETE', 'ADDMAP', 'REMOVEMAP', 'EDITINFO', 'DOWNLOAD', 'EXIT', 'REFRESH']
incom = input()
if incom.upper() not in commands:
print('The command doesn\'t seem right')
else:
if incom.upper() == 'DOWNLOAD':
pldownload(maps, playlists, pldl, PLpath, CMpath)
pldownload(maps, playlists, selpl, PLpath, CMpath)

elif incom.upper() == 'DELETE':
while True:
delcheck = input(f'Are you sure you want to delete "{playlists[pldl]["title"]}" (y/n)')
delcheck = input(f'Are you sure you want to delete "{playlists[selpl]["title"]}" (y/n)')
if delcheck.upper() == 'Y':
os.remove(PLpath + f'{playlists[pldl]["fileName"]}')
os.remove(PLpath + f'{playlists[selpl]["fileName"]}')
print('Playlist deleted\nPress Enter to close.')
input()
exit()
elif delcheck.upper() == 'N':
break
else:
print('Please enter a correct command\n\n')
print('Please enter a correct letter\n\n')

elif incom.upper() == 'EXIT':
exit(0)

elif incom.upper() == 'EDITINFO':
edit_info(PLpath, playlists[pldl]['fileName'])
edit_info(PLpath, playlists[selpl]['fileName'])

elif incom.upper() == 'ADDMAP':
addmap(PLpath, playlists[selpl]['fileName'])

elif incom.upper() == 'REMOVEMAP':
remmap(PLpath, playlists[selpl]['fileName'])

else:
print('This command is not yet implemented')
48 changes: 48 additions & 0 deletions mapDownload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import io
import zipfile
from requests import get
import json
import sys


def download_beatmap(hash, CMpath):
# headers and getting directDownload link
headers = {
'User-Agent': 'Playlist Manager DOS/0.1 (https://github.com/Moreo18/Playlist-Manager-DOS)'}
url1 = 'https://beatsaver.com/api/maps/by-hash/'
req = get(url1 + hash, headers=headers)

try:
dD = json.loads(req.content)

except json.decoder.JSONDecodeError as e:
print('request code : ' + str(req.status_code))
print(e)
print("line : " + str(sys.exc_info()[2].tb_lineno))
print(req.content)

except Exception as e:
print(e)
print(sys.exc_info()[2].tb_lineno)

dD = json.loads(req.content)
name = dD["name"].replace(':', ' ').replace('*', ' ').replace('/', ' ').replace('\\', ' ').replace('<', ' ')\
.replace('>', ' ').replace('|', ' ').replace('?', ' ').replace('"', ' ')
req2 = get(f'https://beatsaver.com{dD["directDownload"]}', headers=headers)
path = CMpath + f'{dD["key"]} ({name} - {dD["uploader"]["username"]})'

# try to extract zip to beat saber folder
try:
zip = zipfile.ZipFile(io.BytesIO(req2.content))
zip.extractall(path)

except zipfile.BadZipfile as e:
print('request code : ' + str(req2.status_code))
print(e)
print("line : " + str(sys.exc_info()[2].tb_lineno))
print(req2.content)
print(f'https://beatsaver.com{dD["directDownload"]}')

except Exception as e:
print(e)
print(sys.exc_info()[2].tb_lineno)
34 changes: 34 additions & 0 deletions newPl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import json
import os
from base64 import b64encode


def pl_create(PLpath):
# Creating the file and starting writing in it
name = input('Enter the name of the playlist you want to create : ')
file = open(f'{PLpath}{name}.json', 'w+', encoding='utf-8')
playlist = {"playlistTitle": name, 'playlistAuthor': input('Enter author\'s name : '),
'playlistDescription': input('Enter description : ')}
images = os.listdir('./Images')
print('\n')
for item in range(len(images)):
print(f'{item + 1}: {images[item - 1]}')
cim = input('Type the number of the image you want (leave empty if you don\'t want an image) : ')
if cim == '':
pass
else:
cont = True
while cont:
try:
cim = int(cim)-1
if cim + 1 <= 0 or cim + 1 > len(images):
print('The number you entered is not in range\nPlease enter another one : ')
input()
else:
cont = False
except ValueError:
print('Please enter a correct value : ')
input()
im = b64encode(open(f'./Images/{images[item]}', 'rb').read())
playlist['image'] = f'data:image/png;base64,{im}'
json.dump(playlist, file)
10 changes: 3 additions & 7 deletions plDownloading.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from mapdownload import *
from mapDownload import *


def pldownload(maps, playlists, pldl, PLpath, CMpath):
Expand All @@ -12,22 +12,18 @@ def pldownload(maps, playlists, pldl, PLpath, CMpath):
pldl = open(pldl).read()
pldl = json.loads(pldl)
todl = []
todlnbr = 0

# Checks if maps in playlists are already downloaded
for item in pldl['songs']:
if item['hash'].lower() not in maps:
todl.append(item)

# Count maps
for item in todl:
todlnbr += 1
ndl = 1

# Downloading map using downloadbeatmap fonction in mapdownload.py
# Downloading map using downloadbeatmap fonction in mapDownload.py
if todl:
for item in todl:
print('\nNow Downloading : ' + item['songName'] + f' {ndl}/{todlnbr}')
print('\nNow Downloading : ' + item['songName'] + f' {ndl}/{len(todl)}')
download_beatmap(item['hash'], CMpath)
ndl += 1
print(f'\n\nPlaylist {title} downloaded')
Expand Down
Loading

0 comments on commit f85d3ad

Please sign in to comment.