Skip to content

Commit 50afe3f

Browse files
committed
Major refactoring for readability
1 parent d200fba commit 50afe3f

2 files changed

Lines changed: 64 additions & 68 deletions

File tree

AutoStructureFilesForDFplayer.py

Lines changed: 63 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,22 @@
1919
MP3FILEMARKER = ".mp3"
2020

2121

22-
def playerFSnumbers(indx, maxCnt):
23-
"""Returns a DFplayerMini-compatible way of numbering
24-
files which is 001, 002, ... 255"""
25-
if indx > maxCnt:
26-
quitWithMessage("Error: player cannot process more than 100 folders")
27-
return str(indx).zfill(len(str(maxCnt)))
28-
29-
3022
def replace_special_chars_in_path(line_of_playlist):
3123
"""Make sure .m3u file's special characters are converted
3224
Replace most common UTF8 special characters"""
3325
return unquote(line_of_playlist)
3426

3527

36-
def quitWithMessage(messageString):
28+
def quit_with_message(message):
3729
"""Quits script gracefully with message"""
38-
print(messageString)
39-
input("Press Enter to quit...")
30+
print(message)
31+
input("Press Enter to quit...\n")
4032
sys.exit()
4133

4234

4335
def find_m3u_filemarker(playlist_line):
4436
"""relevant lines do not begin with # (sharp)
4537
relevant lines may begin with file:/// which has to be stripped"""
46-
4738
if playlist_line.find(M3UINFOMARKER) == 0:
4839
return None
4940

@@ -56,84 +47,89 @@ def find_m3u_filemarker(playlist_line):
5647
return playlist_line
5748

5849

50+
def get_name_from_id(indx, max_cnt):
51+
"""Returns a DFplayerMini-compatible way of numbering
52+
files which is 001, 002, ... 255"""
53+
if indx > max_cnt:
54+
quit_with_message("Error: player cannot process more than %s items" % max_cnt)
55+
return str(indx).zfill(len(str(max_cnt)))
56+
57+
5958
def get_target_file_name(index):
60-
name = playerFSnumbers(index, MAXFILECNT)
59+
name = get_name_from_id(index, MAXFILECNT)
6160
return os.sep + name + MP3FILEMARKER
6261

6362

64-
print("\
65-
Starting Conversion script for structuring files for DFplayerMini.\n\
66-
This script analyzes .m3u playlists and restructures their contents to a format\n\
67-
readable by the DFmini mp3 module.\n")
63+
def compile_list_of_playlists():
64+
"""if Playlist folder exists, print playlists to be evaluated."""
65+
_list_of_playlists = os.listdir(PLAYLISTFLDRNAME)
66+
for _playlist in _list_of_playlists:
67+
if (_playlist.lower()).find(M3UFILETYPE) == -1:
68+
msg = "--- ERROR --- PlayListM3U folder contains unsupported file types: %s\n\
69+
make sure you only place .m3u files here! Aborting." % _playlist
70+
quit_with_message(msg)
71+
_list_of_playlists.sort()
72+
print("Folder with playlists found. Trying to create DFplayer folders and files for: %s" % _list_of_playlists)
73+
return _list_of_playlists
74+
75+
76+
def create_folder(name):
77+
try:
78+
os.makedirs(name)
79+
except:
80+
quit_with_message("Couldn't create folder %s. Is directory read-only?" % name)
81+
82+
83+
print("Starting Conversion application for structuring files for DFplayerMini.\n\
84+
This script analyzes .m3u playlists and restructures their contents to a format readable by the DFmini mp3 module.\n")
6885

6986
# get current working directory
7087
myPath = os.getcwd()
7188
# create directories for playlists and target folders
7289
plPath = os.path.join(os.sep, myPath, PLAYLISTFLDRNAME)
7390
crdPath = os.path.join(os.sep, myPath, CARDFLDRNAME)
74-
listOfPlaylists = None
91+
list_of_playlists = None
7592

7693
print("Hooked to current working directory: %s" % myPath)
7794

78-
# Check for playlist path
79-
if not os.path.exists(PLAYLISTFLDRNAME):
80-
print("\
81-
Did not find folder containing m3u playlists.\n\
82-
Trying to create folder 'PlayListsM3U' for you.")
83-
try:
84-
os.makedirs(PLAYLISTFLDRNAME)
85-
except:
86-
quitWithMessage("Couldn't create folder. Is directory read-only?")
87-
quitWithMessage("\
88-
Playlist folder successfully created: %s\n\
89-
Please move your playlists to this place before restarting the script." % PLAYLISTFLDRNAME)
95+
# Handle playlist folder
96+
if os.path.exists(PLAYLISTFLDRNAME):
97+
list_of_playlists = compile_list_of_playlists()
9098
else:
91-
# if Playlist folder exists, print playlists to be evaluated.
92-
listOfPlaylists = os.listdir(PLAYLISTFLDRNAME)
93-
for line in listOfPlaylists:
94-
if (line.lower()).find(M3UFILETYPE) == -1:
95-
msg = "--- ERROR --- PlayListM3U folder contains other file types than .m3u Playlists: %s\n\
96-
make sure you only place .m3u files here! Aborting." % line
97-
quitWithMessage(msg)
98-
listOfPlaylists.sort()
99-
print("Folder containing playlists found. Will try creating DFplayer folders and files for:")
100-
print(listOfPlaylists)
101-
102-
# Check for album(folder) path
99+
print("Did not find folder containing m3u playlists. Trying to create one for you...")
100+
create_folder(PLAYLISTFLDRNAME)
101+
quit_with_message("\
102+
SUCCESS: Created folder %s\n\
103+
Please move your playlists here and run the application again." % PLAYLISTFLDRNAME)
104+
105+
# Handle SD card output folder
103106
if os.path.exists(CARDFLDRNAME):
104-
# if Playlist folder exists, print playlists to be evaluated.
105-
listOfCardFolders = os.listdir(CARDFLDRNAME)
106-
print("Folder containing SDcard MP3 folders found. Will modify folder structure based on playlist input.")
107-
print("Existing folders: " + str(listOfCardFolders))
107+
print("SDcard MP3 folders found. Will modify contents based on playlist input.\n\
108+
Existing folders: %s\n" % str(os.listdir(CARDFLDRNAME)))
108109
else:
109-
print("\
110-
Did not find folder containing SD card MP3 folders.\n\
111-
Trying to create folder 'SDcardFolders' for you.\n \
112-
You will find the files to transfer to your DFplayerMini's SD card in this folder.")
113-
try:
114-
os.makedirs(CARDFLDRNAME)
115-
except:
116-
quitWithMessage("--- ERROR --- Couldn't create folder. Is directory read-only?")
110+
print("Did not find folder containing SD card MP3 folders.\n\
111+
Trying to create folder %s for you.\n\
112+
You will find the files to transfer to your DFplayerMini's SD card there" % CARDFLDRNAME)
113+
create_folder(CARDFLDRNAME)
114+
117115

118-
if not listOfPlaylists:
119-
quitWithMessage("--- ERROR --- No playlists found in folder. Place .m3u file(s) here, please. Aborting.")
116+
if not list_of_playlists:
117+
quit_with_message("--- ERROR --- No playlists found in %s.\n\
118+
Place .m3u file(s) here, please. Aborting." % PLAYLISTFLDRNAME)
120119
# create folders with correct naming to contain mp3 files
121120
folderIndex = 0
122121
target_folder_name = ""
123122
line_lower = ''
124123
# Go through all .m3u files in .m3u folder
125-
for playlist in listOfPlaylists:
124+
for playlist in list_of_playlists:
126125
folderIndex += 1
127126
# get folderIndexes right according to player's needs
128-
target_folder_name = playerFSnumbers(folderIndex, MAXFLDRCNT)
127+
target_folder_name = get_name_from_id(folderIndex, MAXFLDRCNT)
129128
target_folder_path = os.sep.join([crdPath, target_folder_name])
130129
if os.path.exists(target_folder_name):
131-
print("Folder '%s' already exists. Will auto-overwrite contents." % target_folder_name)
130+
print("Output Folder '%s' already exists. Will auto-overwrite contents." % target_folder_name)
132131
else:
133-
try:
134-
os.makedirs(target_folder_path)
135-
except:
136-
quitWithMessage("--- ERROR --- Couldn't create folder. Is directory read-only?")
132+
create_folder(target_folder_path)
137133
# playlist open and show
138134
# try to find out if playlist has been renamed already, returns -1 if not
139135
if playlist.find(target_folder_name, 0, 2) == -1:
@@ -143,7 +139,7 @@ def get_target_file_name(index):
143139
os.rename(os.sep.join([plPath, playlist], os.sep.join([plPath, new_name])))
144140
playlist = new_name
145141
except:
146-
quitWithMessage(" --- ERROR --- Couldn't rename playlist " + str(playlist) + ". Aborting.")
142+
quit_with_message(" --- ERROR --- Couldn't rename playlist " + str(playlist) + ". Aborting.")
147143
playlistFile = open(os.sep.join([plPath, playlist]), "r")
148144
file_index = 0
149145
for line in playlistFile.readlines():
@@ -155,10 +151,10 @@ def get_target_file_name(index):
155151
try:
156152
shutil.copy2(line, os.sep.join([target_folder_path, target_file_name]))
157153
except:
158-
quitWithMessage(
154+
quit_with_message(
159155
"--- ERROR --- Couldn't copy file\n" + str(line) + " to:\n" + str(
160156
target_folder_path) + "\nAborting.")
161157
print(
162158
"...completed for folder %d of %d: %s with %d files" % (
163-
folderIndex, len(listOfPlaylists), playlist, file_index))
164-
quitWithMessage("--- SUCCESS --- All actions completed successfully.")
159+
folderIndex, len(list_of_playlists), playlist, file_index))
160+
quit_with_message("--- SUCCESS --- All actions completed successfully.")

integration_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ def execute_target(tmp_path):
1515
os.system(TARGET)
1616

1717

18-
# executest the script "Software Under Test"
1918
@pytest.fixture
2019
def copy_target_to_temp(tmp_path):
2120
"""places SUT in temporary path to prepare for execution"""
@@ -53,6 +52,7 @@ def test_creates_playlist_folder(tmp_path, copy_target_to_temp):
5352

5453

5554
def test_creates_sdcard_folder(tmp_path, copy_target_to_temp):
55+
execute_target(tmp_path) # creates playlist folder, then terminates
5656
execute_target(tmp_path)
5757
d = tmp_path / SDCARDFOLDER
5858
assert d.exists()

0 commit comments

Comments
 (0)