This repository has been archived by the owner on Aug 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SaveNLoad.py
269 lines (228 loc) · 9.93 KB
/
SaveNLoad.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
# -*- coding: utf-8 -*-
"""
This script is used to automatically type the contents of WC3 saves made using
Guhun's save system for RP maps.
===========
Created on Thu Oct 20 19:51:07 2016
@author: SonGuhun
v2.3.0
"""
# =============================================================================
# Import Python and 3rd party modules
# =============================================================================
import os # Used to delete files
import time
import traceback # Error reporting/printing
import subprocess # Used to execute powershell script
import platform # Used to retrieve windows version
# Required for sending a GET request for update checks
from multiprocessing import freeze_support
from requests import exceptions as req_error
# =============================================================================
# Import other SaveNLoadModules
# =============================================================================
from keypress import Save
from globalVariables import WC3_PATH, SAVE_PATH, SPEED, WAIT_TIME, CHANGE_KEYBD, \
SCRIPT_PATH, CHECK_UPDATES, AUTO_UPDATES
import updater
import handlers
# =============================================================================
# Define version class
# =============================================================================
class VersionClass:
def __init__(self, major, minor, patch, suffix=''):
self.major = major
self.minor = minor
self.patch = patch
self.suffix = suffix
def asList(self):
return [self.major, self.minor, self.patch]
def asDict(self):
return {'MAJOR': self.major,
'MINOR': self.minor,
'PATCH': self.patch}
def asString(self):
result = 'v' + '.'.join([str(x) for x in self.asList()])
if self.suffix:
return result + "-" + self.suffix
return result
def __lt__(self, other):
for i in range(len(self.asList())):
if self.asList()[i] != other.asList()[i]:
return self.asList()[i] < other.asList()[i]
return False
def __eq__(self, other):
return self.asList() == other.asList()
def __le__(self, other):
return self < other or self == other
def versionFromString(string):
string = string[1:]
parts = string.split('-')
if len(parts) > 1:
parts = [int(x) for x in parts[0].split('.')] + [parts[1]]
else:
parts = [int(x) for x in parts[0].split('.')]
return VersionClass(*parts)
version = VersionClass(2, 4, 0)
# =============================================================================
# Functions
# =============================================================================
def validateWindowsVersion(valid_versions, print_message=True):
win_version = platform.win32_ver()[0]
if win_version in valid_versions:
if print_message:
print "Windows", win_version, "Detected"
return True
else:
if print_message:
print "Windows", win_version, "Detected - Auto Keyboard Change Unsupported"
return False
def pollRequest():
try:
with open(PATH_TO_SAVES+'load.txt') as f:
save_name = f.read()[69:-43]
print 'Load call issued: ' + save_name
os.remove(PATH_TO_SAVES+'load.txt')
return save_name
except Exception as err:
if isinstance(err, IOError):
if err.errno == 2:
return None
elif err.errno == 32:
print "Warcraft III is still processing the request file."
# If this continues, then the program might not have permission to access the file
return None
else:
return err
else:
return err
def main(save_name):
save = Save(PATH_TO_SAVES, save_name)
if not save.type:
return 'Could not find specified save folder under any directory'
if not save.getSize():
return 'Save data not found under requested name'
if not save.getVersion():
return 'Error when retrieving save data'
elif save.version < version.major:
print "Legacy save information detected"
elif save.version > version.major:
return "Incompatible save information. Please update SaveNLoad"
try:
if WINDOWS_VERSION and CHANGE_KEYBD: # Execute powershell to change keyboard layout
print("Attempting to change user's language list...")
p = handlers.PopenWrapper(handlers.KillPowershell, [], {},
['powershell', '-windowstyle', 'hidden',
'-ExecutionPolicy', 'ByPass', '-File',
SCRIPT_PATH+'ChangeLanguageList.ps1'],
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
creationflags=CREATE_NO_WINDOW)
print p.stdout.readline()[:-1]
save.loadData(SPEED, WAIT_TIME)
# Send input to subprocess stdin to reset user language list
if WINDOWS_VERSION and CHANGE_KEYBD:
print ("Restoring user's language list...")
p.communicate("Anything")
del handlers.processDict[id(p)]
if p.returncode:
print("Error upon restoring user's language list. Code: "+str(p.returncode))
else:
print("Sucessfully restored user's language list.")
except Exception as err:
traceback.print_exc()
return err
return None
# =============================================================================
# Main
# =============================================================================
if __name__ == '__main__':
freeze_support()
separator = '\n' + "="*10
CREATE_NO_WINDOW = 0x08000000
# =============================================================================
# ==Check for updates
# =============================================================================
try:
if CHECK_UPDATES:
print "Attemtping to retrieve latest version..."
print "...(Press Ctrl+C to cancel)..."
newestVersion = updater.getNewestVersion()
if newestVersion:
print
if versionFromString(newestVersion) <= version:
print 'SaveNLoad is up-to-date.'
else:
if AUTO_UPDATES:
updater.autoUpdate()
else:
print 'New version is available: Check "Updates" shortcut.'
print
if raw_input("Would you like to download the newest version now? y/n: ") in ('Y', 'y'):
if not subprocess.call(['START', SCRIPT_PATH+'Updates.url'], shell=True):
print "Could not find Updates.url file"
else:
print 'Automatic update checks are disabled.'
except req_error.ConnectionError:
print '...Could not connect to the host server.'
traceback.print_exc()
except KeyboardInterrupt:
print '...Version retrieval interrupted by user.'
try:
if AUTO_UPDATES and os.path.exists(updater.ZIP_DOWNLOAD_PATH+'/Update.zip'):
os.remove(updater.ZIP_DOWNLOAD_PATH+'/Update.zip')
os.rmdir(updater.ZIP_DOWNLOAD_PATH)
except WindowsError:
traceback.print_exc()
print
print 'Failed to remove temporary update files'
print separator
# =============================================================================
# ==SIGNAL AND EXIT HANDLING
# =============================================================================
handlers.initiateExitHandlers()
print separator
# =============================================================================
# ==CHECK WINDOWS VERSION AND CLEAR EXISTING REQUESTS
# =============================================================================
# Print Version
print "Save/Load Typing Script", version.asString()
print "By: Guhun"
# Check for Windows 8 or newer
WINDOWS_VERSION = validateWindowsVersion(('8', '10', '8.1'))
PATH_TO_SAVES = WC3_PATH+SAVE_PATH
# Clear leftover load requests
try:
os.remove(PATH_TO_SAVES+'load.txt')
print 'Unexpected Load Request File. Deleting File'
except WindowsError as error:
if error.winerror == 2: # file not found
pass
else:
print 'Unexpected Load Request File was present, but there was an error deleting it.'
# =============================================================================
# ==MAIN LOOP
# =============================================================================
print
print 'Executable directory: ' + SCRIPT_PATH
print 'Save files directory: ' + PATH_TO_SAVES
print separator[1:]
while handlers.CONTINUE_FLAG:
time.sleep(1)
requested_save = pollRequest()
if isinstance(requested_save, Exception):
print requested_save
elif not requested_save:
pass
else:
exception = main(requested_save)
if exception:
print exception
print 'Load Process Finished'
print separator
# =============================================================================
#
# =============================================================================
# a = requests.get('https://api.github.com/repos/Son-Guhun/SaveNLoad/releases/latest',
# verify=SCRIPT_PATH+'cacert.pem')
# check = a.json()
# print check['tag_name']