File: client.py

package info (click to toggle)
maptransfer 0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 216 kB
  • ctags: 93
  • sloc: python: 817; makefile: 10
file content (387 lines) | stat: -rwxr-xr-x 12,630 bytes parent folder | download | duplicates (2)
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" MapTransfer (Client) -- upload/download maps to/from a VALVe game server

    Copyright © 2009-2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
"""


import sys

from urllib import urlopen

from os      import listdir
from os.path import join, isdir, exists

from ConfigParser import ConfigParser

from PyQt4    import Qt
from PyQt4.Qt import QLocale, QTranslator
from PyQt4    import QtCore
from PyQt4    import QtGui

from client_ui       import Ui_MainWindow
from MapList         import ServerMapList, ClientMapList
from TransferHandler import TransferHandler


class Gui(Ui_MainWindow, QtCore.QObject):
	""" The main class that handles the GUI and controls background processes. """
	
	def __init__( self, conf, steampath ):
		QtCore.QObject.__init__( self )
		Ui_MainWindow.__init__( self )
		
		self.conf = conf
		self.steampath = steampath
		
		self.baseurl = conf.get( "server", "baseurl" )
		self.main_window = QtGui.QMainWindow()
		
		self.setupUi( self.main_window )
		
		self.client_maplist   = ClientMapList( self.lstClientList )
		self.server_maplist   = ServerMapList( self.lstServerList )
		
		self.transfer_handler = TransferHandler(
			conf.get( "auth", "username" ),
			conf.get( "auth", "password" )
			)
		
		self.lblDownloadStatus = QtGui.QLabel( self.tr( "No downloads are running." ) )
		self.statusbar.addPermanentWidget( self.lblDownloadStatus )
		
		self.lblUploadStatus = QtGui.QLabel( self.tr( "No uploads are running." ) )
		self.statusbar.addPermanentWidget( self.lblUploadStatus )
		
		
		# Scan for maps directories and store them in a dict.
		# account_paths = {
		#   account_name: {
		#     game_name: game maps directory
		#   }
		# }
		
		self.account_paths = {}
		for accountdir in listdir( join( self.steampath, "steamapps" ) ):
			if not isdir( join( self.steampath, "steamapps", accountdir ) ) or \
			   accountdir in ( "common", "SourceMods" ):
				continue
			
			appspath = join( self.steampath, "steamapps", accountdir )
			
			print "Found Steam account: '%s'" % appspath
			
			for gamedir in listdir( appspath ):
				if self.conf.has_option( "gametags", gamedir ) and \
				   self.conf.has_option( "mapdirs",  gamedir ):
					mapsdir = join( appspath, gamedir, self.conf.get( "mapdirs", gamedir ) )
					if exists( mapsdir ):
						if accountdir not in self.account_paths:
							self.account_paths[accountdir] = { None: appspath }
						
						print "Map directory for '%s' is:\n    %s" % ( gamedir, mapsdir )
						self.account_paths[accountdir][ self.conf.get( "gametags", gamedir ) ] = mapsdir
					else:
						print "Map directory for '%s' does not exist" % gamedir
				else:
					print "Map directory for '%s' is unknown" % gamedir
		
		self.setup_accounts()
		self.account_changed(0)
		
		
		self.main_window.connect( self.cmbAccount,         QtCore.SIGNAL("currentIndexChanged (int)"), self.account_changed )
		self.main_window.connect( self.cmbGameServer,      QtCore.SIGNAL("currentIndexChanged (int)"), self.server_changed  )
		
		self.main_window.connect( self.btnStart,           QtCore.SIGNAL("clicked(bool)"), self.perform_transfers )
		
		self.main_window.connect( self.btnSelectAllClient, QtCore.SIGNAL("clicked(bool)"), self.choose_all_client )
		self.main_window.connect( self.btnSelectAllServer, QtCore.SIGNAL("clicked(bool)"), self.choose_all_server )
		
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_download_start,    self.status_download_start   )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_download_success,  self.status_download_success )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_download_fail,     self.status_download_fail    )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_download_finished, self.status_download_finished)
		
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_upload_start,      self.status_upload_start    )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_upload_success,    self.status_upload_success  )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_upload_fail,       self.status_upload_fail     )
		self.main_window.connect( self.transfer_handler, TransferHandler.sig_upload_finished,   self.status_upload_finished )
	
	
	def show( self ):
		""" Show the main Window. """
		self.main_window.show()
	
	
	def setup_accounts( self ):
		""" Search the steamapps directory for usable Steam accounts. """
		self.cmbAccount.clear()
		
		for accountdir in self.account_paths:
			self.cmbAccount.addItem( accountdir, QtCore.QVariant( self.account_paths[accountdir][None] ) )
	
	current_account = property(
		lambda self: str( self.cmbAccount.itemText( self.cmbAccount.currentIndex() ) ),
		doc="The name of the currently selected Steam account."
		)
	
	apps_path = property(
		lambda self: self.account_paths[self.current_account][None],
		doc="The SteamApps subdirectory of the currently selected Steam account."
		)
	
	def account_changed( self, accid ):
		""" A different account has been selected, reload the server list. """
		
		print "Selected Steam account: '%s'" % self.apps_path
		
		self.setup_servers()
		self.server_changed(0)
	
	def setup_servers( self ):
		""" Retrieve a server list and check for which game servers we have games
		    in the selected account.
		"""
		
		self.cmbGameServer.clear()
		
		# Fetch the BaseURL - it returns something like this:
		# pub:cssource:Publicserver
		# war:cssource:Warserver
		# emp:Empires:EmpiresMod v3.1.3.3.7
		
		index = urlopen( self.baseurl ).fp
		
		while True:
			line = index.readline().strip()
			if not line:
				break
			srv, game, desc = line.split( ':', 2 )
			if game in self.account_paths[self.current_account]:
				self.cmbGameServer.addItem(
					"%s (%s)" % ( desc, game ),
					QtCore.QVariant( "%s:%s" % ( srv, game ) )
					)
	
	server_info = property(
		lambda self: str( self.cmbGameServer.itemData( self.cmbGameServer.currentIndex() ).toString() ).split(':'),
		doc="The server ID and game name for the currently selected Game server."
		)
	
	server_id = property(
		lambda self: self.server_info[0],
		doc="The Server ID for the currently selected Game server."
		)
	
	server_game = property(
		lambda self: self.server_info[1],
		doc="The game directory name for the currently selected Game server."
		)
	
	def server_changed( self, srvid ):
		""" A different game server has been selected, reload map lists. """
		
		self.server_maplist.fetch( self.baseurl + self.server_id )
		maps_dir = self.account_paths[self.current_account][ self.server_game ]
		
		self.lblPath.setText( self.tr("Maps are being saved to:\n%1").arg(maps_dir) )
		
		self.client_maplist.fetch( maps_dir )
		
		# now compare the maps and highlight those that should be transferred
		self.client_maplist.mark_missing( self.server_maplist )
		self.server_maplist.mark_missing( self.client_maplist )
	
	
	
	def choose_all_client( self, checked ):
		""" Select all maps in the client view that don't exist on the server. """
		self.client_maplist.choose_missing( self.server_maplist )
		
	def choose_all_server( self, checked ):
		""" Select all maps in the server view that don't exist on the client. """
		self.server_maplist.choose_missing( self.client_maplist )
	
	
	def status_download_start( self, mapname ):
		""" Slot to react on a starting download. """
		self.lblDownloadStatus.setText( self.tr("Downloading %1").arg(mapname) )
	
	def status_download_success( self, mapname ):
		""" Slot to react on a successfully finished download. """
		item = self.server_maplist.get_map_item( mapname )
		if item:
			item.setBackgroundColor( Qt.Qt.green )
	
	def status_download_fail( self, mapname, errcode, errmsg, errdesc ):
		""" Slot to react on a failed download. """
		item = self.server_maplist.get_map_item( mapname )
		if item:
			item.setBackgroundColor( Qt.Qt.red )
		QtGui.QMessageBox.information(
			self.main_window, self.main_window.windowTitle(), self.tr(
				"Map %1 cannot be downloaded. The server said:\n%2: %3\n\n%4"
				).arg(mapname).arg(errcode).arg(errmsg).arg(errdesc)
			)
	
	def status_download_finished( self ):
		""" Slot to react when all downloads have finished. """
		self.lblDownloadStatus.setText( self.tr("All downloads finished") )
		self.server_changed(0)
	
	def status_upload_start( self, mapname ):
		""" Slot to react on a starting upload. """
		self.lblUploadStatus.setText( self.tr("Uploading %1").arg(mapname) )
	
	def status_upload_success( self, mapname ):
		""" Slot to react on a successfully finished upload. """
		item = self.server_maplist.get_map_item( mapname )
		if item:
			item.setBackgroundColor( Qt.Qt.green )
	
	def status_upload_fail( self, mapname, errcode, errmsg, errdesc ):
		""" Slot to react on a failed upload. """
		item = self.server_maplist.get_map_item( mapname )
		if item:
			item.setBackgroundColor( Qt.Qt.red )
		QtGui.QMessageBox.information(
			self.main_window, self.main_window.windowTitle(), self.tr(
				"Map %1 cannot be uploaded. The server said:\n%2: %3\n\n%4"
				).arg(mapname).arg(errcode).arg(errmsg).arg(errdesc)
			)
	
	def status_upload_finished( self ):
		""" Slot to react when all uploads have finished. """
		self.lblUploadStatus.setText( self.tr("All uploads finished") )
		self.server_changed(0)
	
	
	def perform_transfers( self, checked ):
		""" Start the background thread to transfer the selected files.
		
		    Before doing so, check if the user ordered to download files
		    we already have, and ask them what to do with these downloads.
		"""
		
		yes_to_all = False
		no_to_all  = False
		
		download = []
		upload   = []
		
		for i in range( self.server_maplist.widget.count() ):
			listitem = self.server_maplist.widget.item(i)
			if not listitem or not listitem.checked:
				continue
			
			mapname = listitem.map_name
			
			bspath = "%s/%s.bsp" % ( self.account_paths[self.current_account][self.server_game], mapname )
			
			if exists( bspath ):
				if yes_to_all == no_to_all == False:
					choice = QtGui.QMessageBox.question(
						self.main_window, self.main_window.windowTitle(),
						self.tr("Map %1 exists - overwrite it?").arg(mapname),
						( QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
						  QtGui.QMessageBox.YesToAll | QtGui.QMessageBox.NoToAll ),
						QtGui.QMessageBox.No
						)
				elif yes_to_all:
					choice = QtGui.QMessageBox.Yes
				else:
					choice = QtGui.QMessageBox.No
				
				if   choice == QtGui.QMessageBox.YesToAll:
					yes_to_all = True
				elif choice == QtGui.QMessageBox.NoToAll:
					no_to_all  = True
				
				if choice in ( QtGui.QMessageBox.No, QtGui.QMessageBox.NoToAll ):
					continue
			
			download.append({
				'mapname': mapname,
				'mapexts': listitem.map_exts
				})
		
		
		for i in range( self.client_maplist.widget.count() ):
			listitem = self.client_maplist.widget.item(i)
			if not listitem or not listitem.checked:
				continue
			
			mapname = listitem.map_name
			
			if self.server_maplist.has_map( mapname ):
				QtGui.QMessageBox.information(
					self.main_window, self.main_window.windowTitle(),
					self.tr("Map %1 already exists on the server and will not be uploaded.").arg(mapname)
					)
				continue
			
			upload.append({
				'mapname': mapname,
				'mapexts': listitem.map_exts
				})
		
		
		self.transfer_handler.perform_transfers(
			self.account_paths[self.current_account][ self.server_game ],
			self.baseurl + self.server_id,
			download=download, upload=upload
			)



if __name__ == '__main__':
	
	from sys import argv
	
	if len( argv ) > 1:
		cfg = argv[1]
	else:
		cfg = "maptransfer.cfg"
	
	if not exists( cfg ):
		print "The configuration file '%s' does not exist!" % cfg
		print "Hit enter to exit."
		raw_input()
		sys.exit(1)
	
	config = ConfigParser()
	config.read( cfg )
	
	try:
		from _winreg import OpenKey, CloseKey, QueryValueEx, HKEY_CURRENT_USER
	except ImportError:
		steam = config.get( "steam", "path" )
	else:
		print "Auto-Detecting Gamedirs..."
		
		regkey = OpenKey( HKEY_CURRENT_USER, config.get( "registry", "keypath" ) )
		steam = QueryValueEx( regkey, config.get( "registry", "keyname" ) )[0]
		CloseKey( regkey )
	
	try:
		app = QtGui.QApplication( sys.argv )
		
		locale = QLocale.system().name()
		print "loading locale", locale
		translator = QTranslator()
		translator.load("client_" + locale)
		app.installTranslator(translator)
		
		g = Gui( config, steam )
		g.show()
		app.exec_()
	finally:
		if config.getboolean( "general", "hitEnterToExit" ):
			print
			print
			print "Hit enter to exit."
			raw_input()