-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
288 lines (256 loc) · 8.88 KB
/
main.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
281
282
283
284
285
286
287
288
import os
import configparser
import fileRename
import FileSorter
import initFileSorter
import logging
import sys
import threading
import time
import atexit
import json
import ast
scriptDir = os.path.dirname(os.path.realpath(__file__))
jobs = []
class threadedSorter():
def __init__(self, runInterval, rootDir):
self.enabled = True
self.runInterval = runInterval
self.verbosity = -3
self.rootDir = rootDir
self.includeSysFiles = False
self.thisSorter = None
def targetDir(self):
self.rootDir = os.getcwd()
def thread_func(self):
while self.enabled:
for index in range(self.runInterval*60):
if self.enabled:
time.sleep(1)
else:
print("Thread Killed")
break
if self.enabled:
FileSorter.inputArgs("Logs",self.verbosity,0,False,0,self.includeSysFiles,self.rootDir)
def launch(threadedSorter):
threadedSorter.thisSorter = threading.Thread(target=threadedSorter.thread_func, args=())
threadedSorter.thisSorter.start()
def kill(threadedSorter):
threadedSorter.enabled = False
def loadJobs():
if os.path.isfile("./jobs.json"):
f = open("./jobs.json", "r")
jobsSnapshot = json.loads(f.read())
for jobSave in jobsSnapshot:
jobSave = jobsSnapshot[jobSave]
runInterval = jobSave['runInterval']
rootDir = jobSave['rootDir']
newJob = threadedSorter(runInterval,rootDir)
launch(newJob)
jobs.append(newJob)
def scheduleNewSorter():
print("Are you certain you wish to sort this directory?")
if input("Press Y to continue: ") not in ['y','Y']:
return None
if not os.path.isfile(os.getcwd()+ os.sep + 'fileSortConfiguration' + os.sep + 'fileSort.config'):
print("The directory you gave is not set up. Configuration file not found. Please first set it up. ")
print(os.getcwd()+ os.sep + 'fileSortConfiguration' + os.sep + 'fileSort.config not found.' )
input("Press enter to continue: ")
return None
print("Please enter the interval you wish to run the file sorter at, as an \
integer number of minutes. Please note that this app must be open for it to run. ")
while True:
interval = input("Interval(Min): ")
try:
interval = int(interval)
break
except ValueError:
print("Please enter a valid integer. ")
newJob = threadedSorter(interval,os.getcwd())
launch(newJob)
jobs.append(newJob)
def removeScheduledSorter():
counter = 1
for sorter in jobs:
print(str(counter)+": "+str(sorter.rootDir))
counter = counter + 1
print(str(counter) + ": Back")
while True:
userInput = input("Choice: ")
try:
userInput = int(userInput)
except ValueError:
pass
if userInput in range(1,counter-1+1):
break
elif userInput == counter:
return None
else:
print("Invalid input. Please enter a corresponding integer. ")
print("Are you certain you wish to NOT sort this directory?")
if input("Press Y to continue: ") not in ['y','Y']:
sorter = jobs[userInput-1]
kill(sorter)
time.sleep(10)
jobs.remove(sorter)
input("Press enter to return to main menu: ")
def scheduler():
if jobs is not []:
print("Scheduled:")
for job in jobs:
print(job.rootDir)
print("Choices:\n\
1. Schedule another sorter for target folder\n\
2. UNschedule an existing sorter\n\
3. Back")
while True:
userChoice = input("Choice Num > ")
try:
userChoice = int(userChoice)
except ValueError:
pass
if userChoice in range(1,3+1):
break
else:
print("Invalid input. Please enter a corresponding integer. ")
if userChoice == 1:
scheduleNewSorter()
elif userChoice == 2:
removeScheduledSorter()
elif userChoice == 3:
return None
else:
print("Invalid choice option.")
def sortFiles():
print("Are you certain you wish to sort this directory?")
if input("Press Y to continue: ") not in ['y','Y']:
return None
if not os.path.isfile(os.getcwd()+ os.sep + 'fileSortConfiguration' + os.sep + 'fileSort.config'):
print("The directory you gave is not set up. Configuration file not found. Please first set it up. ")
print(os.getcwd()+ os.sep + 'fileSortConfiguration' + os.sep + 'fileSort.config not found.' )
input("Press enter to continue: ")
return None
FileSorter.inputArgs("", 1, 0, True, 0, False, os.getcwd())
FileSorter.main()
print("\n\n\nThe above output will BE CLEARED once you continue. Please INSPECT the output text, especially the warnings and errors. \
When automated, the above data would be saved in the logs. ")
input("Press enter to continue: ")
return None
def setupSorter(advanced):
if advanced:
print("Would you like to also sort any other folder that is not a subdirectory of the target folder?")
while True:
choice = input("y/[N] > ")
if choice in ["y","Y","yes","Yes","YES"]:
includeDir = []
while True:
print("Please enter the FULL path of another folder to sort. Enter" + '"!skip" to skip.')
while True:
userEntry = input("Dir:")
if os.path.isdir(userEntry):
includeDir.append(userEntry)
break
elif userEntry == '!skip':
break
else:
print("Invalid Directory. ")
print("Would you like to add another folder? ")
choice = None
while choice not in ["y","Y","yes","Yes","YES","n","N","no","No","NO",""]:
choice = input("y/[N] > ")
if choice in ["y","Y","yes","Yes","YES"]:
pass
elif choice in ["n","N","no","No","NO",""]:
break
if includeDir == []:
includeDir = None
break
elif choice in ["n","N","no","No","NO",""]:
includeDir = None
break
initFileSorter.setArgs(os.getcwd(), True, includeDir)
initFileSorter.interactiveMain(advanced)
else:
initFileSorter.setArgs(os.getcwd(), True, None)
initFileSorter.interactiveMain(advanced)
input("Press enter to continue: ")
def main():
print("Target Folder:")
print(os.getcwd()+"\n")
print("Main Menu:\n\
1. Rename files\n\
2. Setup the file sorter\n\
3. Setup the file sorter [Advanced Setup]\n\
4. Sort the files\n\
5. Schedule the file sorter\n\
6. Change target folder\n\
7. Exit\n\
")
while True:
userChoice = input("Choice Num > ")
try:
userChoice = int(userChoice)
except ValueError:
pass
if userChoice in range(1,7+1):
break
else:
print("Invalid input. Please enter a corresponding integer. ")
if userChoice == 1:
os.system('clear')
fileRename.main()
elif userChoice == 2:
setupSorter(False)
elif userChoice == 3:
setupSorter(True)
elif userChoice == 4:
sortFiles()
elif userChoice == 5:
scheduler()
elif userChoice == 6:
fileRename.changeWorkingDir()
elif userChoice == 7:
saveJobs()
killJobs()
sys.exit()
else:
print("Invalid choice option.")
def saveJobs():
print("Saving Jobs to "+scriptDir + os.sep +"jobs.json")
jobsSnapshot = {}
counter=1
for job in jobs:
jobsSnapshot["Job"+str(counter)] = { 'enabled' : job.enabled,
'runInterval':job.runInterval,
'verbosity':job.verbosity,
'rootDir':job.rootDir,
'includeSysFiles':job.includeSysFiles}
counter = counter +1
output = json.dumps(jobsSnapshot)
if os.path.isfile(scriptDir + os.sep +"jobs.json"):
os.remove(scriptDir + os.sep +"jobs.json")
with open(scriptDir + os.sep +"jobs.json", "w") as outfile:
outfile.write(output)
def killJobs():
print("Killing Jobs")
jobsSnapshot = {}
counter=1
for job in jobs:
kill(job)
if __name__ == '__main__':
try:
loadJobs()
if os.name =='posix':
os.system('clear')
else:
os.system('cls')
while True:
main()
if os.name =='posix':
os.system('clear')
else:
os.system('cls')
except KeyboardInterrupt:
saveJobs()
killJobs()
sys.exit()