[rhythmbox] magnatune: Code cleanup



commit a5025bfbde50ad8ec6ef1121d3f2c34bb05743c2
Author: Adam Zimmerman <adamz src gnome org>
Date:   Thu Feb 18 16:09:31 2010 -0800

    magnatune: Code cleanup
    
    - some whitespace fixes
    - make callback functions into inner functions
    - make resuming in-progress downloads work again

 plugins/magnatune/magnatune/BuyAlbumHandler.py  |    1 -
 plugins/magnatune/magnatune/MagnatuneSource.py  |  459 +++++++++++------------
 plugins/magnatune/magnatune/TrackListHandler.py |    3 +-
 plugins/magnatune/magnatune/__init__.py         |   64 ++--
 4 files changed, 252 insertions(+), 275 deletions(-)
---
diff --git a/plugins/magnatune/magnatune/BuyAlbumHandler.py b/plugins/magnatune/magnatune/BuyAlbumHandler.py
index 17e752b..40b8621 100644
--- a/plugins/magnatune/magnatune/BuyAlbumHandler.py
+++ b/plugins/magnatune/magnatune/BuyAlbumHandler.py
@@ -28,7 +28,6 @@
 import xml.sax, xml.sax.handler
 
 class BuyAlbumHandler(xml.sax.handler.ContentHandler): # Class to download the track, etc.
-
 	format_map =	{
 			'ogg'		:	'URL_OGGZIP',
 			'flac'		:	'URL_FLACZIP',
diff --git a/plugins/magnatune/magnatune/MagnatuneSource.py b/plugins/magnatune/magnatune/MagnatuneSource.py
index 4c799e4..bb081c0 100644
--- a/plugins/magnatune/magnatune/MagnatuneSource.py
+++ b/plugins/magnatune/magnatune/MagnatuneSource.py
@@ -46,6 +46,7 @@ magnatune_partner_id = "rhythmbox"
 # URIs
 magnatune_song_info_uri = "http://magnatune.com/info/song_info_xml.zip";
 magnatune_buy_album_uri = "https://magnatune.com/buy/choose?";
+magnatune_api_download_uri = "http://%s:%s download magnatune com/buy/membership_free_dl_xml?"
 
 magnatune_in_progress_dir = os.path.join(rb.user_data_dir(), 'magnatune')
 magnatune_cache_dir = os.path.join(rb.user_cache_dir(), 'magnatune')
@@ -54,8 +55,6 @@ magnatune_song_info = os.path.join(magnatune_cache_dir, 'song_info.xml')
 magnatune_song_info_temp = os.path.join(magnatune_cache_dir, 'song_info.zip.tmp')
 
 
-ALBUM_ART_URL = 'http://www.magnatune.com/music/%s/%s/cover.jpg'
-
 class MagnatuneSource(rb.BrowserSource):
 	__gproperties__ = {
 		'plugin': (rb.Plugin, 'plugin', 'plugin', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),
@@ -65,7 +64,6 @@ class MagnatuneSource(rb.BrowserSource):
 
 
 	def __init__(self):
-
 		rb.BrowserSource.__init__(self, name=_("Magnatune"))
 		self.__db = None
 
@@ -92,7 +90,6 @@ class MagnatuneSource(rb.BrowserSource):
 		self.purchase_filesize = 0 # total amount of bytes to download
 
 
-
 	def do_set_property(self, property, value):
 		if property.name == 'plugin':
 			self.__plugin = value
@@ -104,17 +101,17 @@ class MagnatuneSource(rb.BrowserSource):
 	#
 
 	def do_impl_show_entry_popup(self):
-		self.show_source_popup ("/MagnatuneSourceViewPopup")
+		self.show_source_popup("/MagnatuneSourceViewPopup")
 
 	def do_impl_get_status(self):
 		if self.__updating:
 			if self.__load_total_size > 0:
-				progress = min (float(self.__load_current_size) / self.__load_total_size, 1.0)
+				progress = min(float(self.__load_current_size) / self.__load_total_size, 1.0)
 			else:
 				progress = -1.0
 			return (_("Loading Magnatune catalog"), None, progress)
 		elif self.__downloading:
-			progress = min (self.__download_progress, 1.0)
+			progress = min(self.__download_progress, 1.0)
 			return (_("Downloading Magnatune Album(s)"), None, progress)
 		else:
 			qm = self.get_property("query-model")
@@ -137,7 +134,7 @@ class MagnatuneSource(rb.BrowserSource):
 				self.__move_data_files()
 
 			self.__activated = True
-			self.__show_loading_screen (True)
+			self.__show_loading_screen(True)
 
 			# start our catalogue updates
 			self.__update_id = gobject.timeout_add(6 * 60 * 60 * 1000, self.__update_catalogue)
@@ -145,18 +142,18 @@ class MagnatuneSource(rb.BrowserSource):
 
 			self.get_entry_view().set_sorting_type(self.__client.get_string("/apps/rhythmbox/plugins/magnatune/sorting"))
 
-		rb.BrowserSource.do_impl_activate (self)
+		rb.BrowserSource.do_impl_activate(self)
 
-	def do_impl_get_browser_key (self):
+	def do_impl_get_browser_key(self):
 		return "/apps/rhythmbox/plugins/magnatune/show_browser"
 
-	def do_impl_get_paned_key (self):
+	def do_impl_get_paned_key(self):
 		return "/apps/rhythmbox/plugins/magnatune/paned_position"
 
-	def do_impl_can_delete (self):
+	def do_impl_can_delete(self):
 		return False
 
-	def do_impl_pack_paned (self, paned):
+	def do_impl_pack_paned(self, paned):
 		self.__paned_box = gtk.VBox(False, 5)
 		self.pack_start(self.__paned_box)
 		self.__paned_box.pack_start(paned)
@@ -164,11 +161,11 @@ class MagnatuneSource(rb.BrowserSource):
 
 	def do_impl_delete_thyself(self):
 		if self.__update_id != 0:
-			gobject.source_remove (self.__update_id)
+			gobject.source_remove(self.__update_id)
 			self.__update_id = 0
 
 		if self.__notify_id != 0:
-			gobject.source_remove (self.__notify_id)
+			gobject.source_remove(self.__notify_id)
 			self.__notify_id = 0
 
 		if self.__catalogue_loader is not None:
@@ -181,7 +178,7 @@ class MagnatuneSource(rb.BrowserSource):
 
 		self.__client.set_string("/apps/rhythmbox/plugins/magnatune/sorting", self.get_entry_view().get_sorting_type())
 
-		rb.BrowserSource.do_impl_delete_thyself (self)
+		rb.BrowserSource.do_impl_delete_thyself(self)
 
 	#
 	# methods for use by plugin and UI
@@ -210,7 +207,7 @@ class MagnatuneSource(rb.BrowserSource):
 			if url not in urls:
 				gtk.show_uri(screen, url, gtk.gdk.CURRENT_TIME)
 				urls.add(url)
-	
+
 	def download_album(self):
 		try:
 			library_location = self.__client.get_list("/apps/rhythmbox/library_locations", gconf.VALUE_STRING)[0] # Just use the first library location
@@ -233,130 +230,125 @@ class MagnatuneSource(rb.BrowserSource):
 	# internal catalogue downloading and loading
 	#
 
-	def __catalogue_chunk_cb(self, result, total, parser):
-		if not result or isinstance (result, Exception):
-			if result:
-				# report error somehow?
-				print "error loading catalogue: %s" % result
-
-			try:
-				parser.close ()
-			except xml.sax.SAXParseException, e:
-				# there isn't much we can do here
-				print "error parsing catalogue: %s" % e
-
-			self.__show_loading_screen (False)
-			self.__updating = False
-			self.__catalogue_loader = None
-
-			# restart in-progress downloads
-			# (doesn't really belong here)
-			inprogress = os.listdir(magnatune_in_progress_dir)
-			inprogress = filter(lambda x: x.startswith("in_progress_"), inprogress)
-			for ip in inprogress:
-				for uri in open(ip).readlines():
-					print "restarting download from %s" % uri
-					self.__download_album(uri)
-
-		else:
-			# hack around some weird chars that show up in the catalogue for some reason
-			result = result.replace("\x19", "'")
-			result = result.replace("\x13", "-")
-
-			try:
-				parser.feed(result)
-			except xml.sax.SAXParseException, e:
-				print "error parsing catalogue: %s" % e
-
-			self.__load_current_size += len(result)
-			self.__load_total_size = total
-
-		self.__notify_status_changed()
-
-
-	def __load_catalogue(self):
-		def got_items(result, items):
-			account_type = self.__client.get_string(self.__plugin.gconf_keys['account_type'])
-			username = ""
-			password = ""
-			if account_type == 'none':
-				pass
-			elif result is not None or len(items) == 0:
-				rb.error_dialog(title = _("Couldn't get account details"),
-				                message = str(result))
-				return
-			else:
-				try:
-					username, password = items[0].secret.split('\n')
-				except ValueError: # Couldn't parse secret, possibly because it's empty
+	def __update_catalogue(self):
+		def update_cb(result):
+			self.__catalogue_check = None
+			if result is True:
+				download_catalogue()
+			elif self.__has_loaded is False:
+				load_catalogue()
+
+		def download_catalogue():
+			def find_song_info(catalogue):
+				for info in catalogue.infolist():
+					if info.filename.endswith("song_info.xml"):
+						return info.filename;
+				return None
+
+			def download_catalogue_chunk_cb(result, total):
+				if not result:
+					# done downloading, unzip to real location
+					out.close()
+
+					catalog_zip = zipfile.ZipFile(magnatune_song_info_temp)
+					catalog = open(magnatune_song_info, 'w')
+					filename = find_song_info(catalog_zip)
+					if filename is None:
+						rb.error_dialog(title=_("Unable to load catalog"),
+								message=_("Rhythmbox could not understand the Magnatune catalog, please file a bug."))
+						return
+					catalog.write(catalog_zip.read(filename))
+					catalog.close()
+					catalog_zip.close()
+
+					os.unlink(magnatune_song_info_temp)
+					self.__updating = False
+					self.__catalogue_loader = None
+					load_catalogue()
+				elif isinstance(result, Exception):
+					# complain
 					pass
-			parser = xml.sax.make_parser()
-			parser.setContentHandler(TrackListHandler(self.__db, self.__entry_type, self.__sku_dict, self.__home_dict, self.__art_dict, account_type, username, password))
-		
-			self.__catalogue_loader = rb.ChunkLoader()
-			self.__catalogue_loader.get_url_chunks(magnatune_song_info, 64*1024, True, self.__catalogue_chunk_cb, parser)
-		
-		self.__notify_status_changed()
-		self.__has_loaded = True
-
-		keyring.find_items(keyring.ITEM_GENERIC_SECRET, {'rhythmbox-plugin': 'magnatune'}, got_items)
+				else:
+					out.write(result)
+					self.__load_current_size += len(result)
+					self.__load_total_size = total
 
+				self.__notify_status_changed()
 
-	def __find_song_info(self, catalogue):
-		for info in catalogue.infolist():
-			if info.filename.endswith("song_info.xml"):
-				return info.filename;
-		return None
-
-
-	def __download_catalogue_chunk_cb (self, result, total, out):
-		if not result:
-			# done downloading, unzip to real location
-			out.close()
 
-			catalog = zipfile.ZipFile(magnatune_song_info_temp)
-			out = open(magnatune_song_info, 'w')
-			filename = self.__find_song_info(catalog)
-			if filename is None:
-				rb.error_dialog(title=_("Unable to load catalog"),
-						message=_("Rhythmbox could not understand the Magnatune catalog, please file a bug."))
-				return
-			out.write(catalog.read(filename))
-			out.close()
-			catalog.close()
-
-			os.unlink(magnatune_song_info_temp)
-			self.__updating = False
-			self.__catalogue_loader = None
-			self.__load_catalogue()
-
-		elif isinstance(result, Exception):
-			# complain
-			pass
-		else:
-			out.write(result)
-			self.__load_current_size += len(result)
-			self.__load_total_size = total
-
-		self.__notify_status_changed()
+			self.__updating = True
+			out = open(magnatune_song_info_temp, 'w')
 
+			self.__catalogue_loader = rb.ChunkLoader()
+			self.__catalogue_loader.get_url_chunks(magnatune_song_info_uri, 4*1024, True, download_catalogue_chunk_cb)
 
-	def __download_catalogue(self):
-		self.__updating = True
+		def load_catalogue():
+			def got_items(result, items):
+				account_type = self.__client.get_string(self.__plugin.gconf_keys['account_type'])
+				username = ""
+				password = ""
+				if account_type == 'none':
+					pass
+				elif result is not None or len(items) == 0:
+					rb.error_dialog(title = _("Couldn't get account details"),
+							message = str(result))
+					return
+				else:
+					try:
+						username, password = items[0].secret.split('\n')
+					except ValueError: # Couldn't parse secret, possibly because it's empty
+						pass
+				parser = xml.sax.make_parser()
+				parser.setContentHandler(TrackListHandler(self.__db, self.__entry_type, self.__sku_dict, self.__home_dict, self.__art_dict, account_type, username, password))
+
+				self.__catalogue_loader = rb.ChunkLoader()
+				self.__catalogue_loader.get_url_chunks(magnatune_song_info, 64*1024, True, catalogue_chunk_cb, parser)
+
+			def catalogue_chunk_cb(result, total, parser):
+				if not result or isinstance(result, Exception):
+					if result:
+						# report error somehow?
+						print "error loading catalogue: %s" % result
+
+					try:
+						parser.close()
+					except xml.sax.SAXParseException, e:
+						# there isn't much we can do here
+						print "error parsing catalogue: %s" % e
+
+					self.__show_loading_screen(False)
+					self.__updating = False
+					self.__catalogue_loader = None
+
+					# restart in-progress downloads
+					# (doesn't really belong here)
+					inprogress = os.listdir(magnatune_in_progress_dir)
+					inprogress = filter(lambda x: x.startswith("in_progress_"), inprogress)
+					for ip in inprogress:
+						for uri in open(os.path.join(magnatune_in_progress_dir, ip)).readlines():
+							print "restarting download from %s" % uri
+							self.__download_album(uri, ip[12:])
+				else:
+					# hack around some weird chars that show up in the catalogue for some reason
+					result = result.replace("\x19", "'")
+					result = result.replace("\x13", "-")
+
+					try:
+						parser.feed(result)
+					except xml.sax.SAXParseException, e:
+						print "error parsing catalogue: %s" % e
+
+					self.__load_current_size += len(result)
+					self.__load_total_size = total
+
+				self.__notify_status_changed()
 
-		out = open(magnatune_song_info_temp, 'w')
 
-		self.__catalogue_loader = rb.ChunkLoader()
-		self.__catalogue_loader.get_url_chunks(magnatune_song_info_uri, 4*1024, True, self.__download_catalogue_chunk_cb, out)
+			self.__notify_status_changed()
+			self.__has_loaded = True
 
+			keyring.find_items(keyring.ITEM_GENERIC_SECRET, {'rhythmbox-plugin': 'magnatune'}, got_items)
 
-	def __update_catalogue(self):
-		def update_cb (result):
-			self.__catalogue_check = None
-			if result is True:
-				self.__download_catalogue()
-			elif self.__has_loaded is False:
-				self.__load_catalogue()
 
 		self.__catalogue_check = rb.UpdateCheck()
 		self.__catalogue_check.check_for_update(magnatune_song_info, magnatune_song_info_uri, update_cb)
@@ -369,8 +361,8 @@ class MagnatuneSource(rb.BrowserSource):
 			builder.add_from_file(self.__plugin.find_file("magnatune-loading.ui"))
 			self.__info_screen = builder.get_object("magnatune_loading_scrolledwindow")
 			self.pack_start(self.__info_screen)
-			self.get_entry_view().set_no_show_all (True)
-			self.__info_screen.set_no_show_all (True)
+			self.get_entry_view().set_no_show_all(True)
+			self.__info_screen.set_no_show_all(True)
 
 		self.__info_screen.set_property("visible", show)
 		self.__paned_box.set_property("visible", not show)
@@ -387,13 +379,13 @@ class MagnatuneSource(rb.BrowserSource):
 	#
 	# internal purchasing code
 	#
-	def __auth_download(self, sku): # http://magnatune.com/info/api#purchase
+	def __auth_download(self, sku): # http://magnatune.com/info/api
 		def got_items(result, items):
 			if result is not None or len(items) == 0:
 				rb.error_dialog(title = _("Couldn't get account details"),
 				                message = str(result))
 				return
-			
+
 			try:
 				username, password = items[0].secret.split('\n')
 			except ValueError: # Couldn't parse secret, possibly because it's empty
@@ -404,82 +396,93 @@ class MagnatuneSource(rb.BrowserSource):
 				'id':	magnatune_partner_id,
 				'sku':	sku
 			}
-			url = "http://%s:%s download magnatune com/buy/membership_free_dl_xml?" % (username, password)
+			url = magnatune_api_download_uri % (username, password)
 			url = url + urllib.urlencode(url_dict)
 
 			l = rb.Loader()
-			l.get_url (url, self.__auth_data_cb, (sku, username, password))
-		
-		keyring.find_items(keyring.ITEM_GENERIC_SECRET, {'rhythmbox-plugin': 'magnatune'}, got_items)
-
+			l.get_url(url, auth_data_cb, (username, password))
 
-	def __auth_data_cb (self, data, (sku, username, password)):
-		buy_album_handler = BuyAlbumHandler(self.__client.get_string(self.__plugin.gconf_keys['format']))
-		auth_parser = xml.sax.make_parser()
-		auth_parser.setContentHandler(buy_album_handler)
-
-		if data is None:
-			# hmm.
-			return
+		def auth_data_cb(data, (username, password)):
+			buy_album_handler = BuyAlbumHandler(self.__client.get_string(self.__plugin.gconf_keys['format']))
+			auth_parser = xml.sax.make_parser()
+			auth_parser.setContentHandler(buy_album_handler)
 
-		try:
-			data = data.replace("<br>", "") # get rid of any stray <br> tags that will mess up the parser
-			# print data
-			auth_parser.feed(data)
-			auth_parser.close()
+			if data is None:
+				# hmm.
+				return
 
-			# process the URI: add authentication info, quote the filename component for some reason
-			parsed = urlparse.urlparse(buy_album_handler.url)
-			netloc = "%s:%s %s" % (username, password, parsed.hostname)
+			try:
+				data = data.replace("<br>", "") # get rid of any stray <br> tags that will mess up the parser
+				# print data
+				auth_parser.feed(data)
+				auth_parser.close()
 
-			spath = os.path.split(urllib.url2pathname(parsed.path))
-			basename = spath[1]
-			path = urllib.pathname2url(os.path.join(spath[0], urllib.quote(basename)))
+				# process the URI: add authentication info, quote the filename component for some reason
+				parsed = urlparse.urlparse(buy_album_handler.url)
+				netloc = "%s:%s %s" % (username, password, parsed.hostname)
 
-			authed = (parsed[0], netloc, path) + parsed[3:]
-			audio_dl_uri = urlparse.urlunparse(authed)
+				spath = os.path.split(urllib.url2pathname(parsed.path))
+				basename = spath[1]
+				path = urllib.pathname2url(os.path.join(spath[0], urllib.quote(basename)))
 
-			in_progress = open(os.path.join(magnatune_in_progress_dir, "in_progress_" + sku), 'w')
-			in_progress.write(str(audio_dl_uri))
-			in_progress.close()
+				authed = (parsed[0], netloc, path) + parsed[3:]
+				audio_dl_uri = urlparse.urlunparse(authed)
 
-			self.__download_album(audio_dl_uri, sku)
+				self.__download_album(audio_dl_uri, sku)
 
-		except MagnatunePurchaseError, e:
-			rb.error_dialog(title = _("Download Error"),
-					message = _("An error occurred while trying to authorize the download.\nThe Magnatune server returned:\n%s") % str(e))
+			except MagnatunePurchaseError, e:
+				rb.error_dialog(title = _("Download Error"),
+						message = _("An error occurred while trying to authorize the download.\nThe Magnatune server returned:\n%s") % str(e))
+			except Exception, e:
+				rb.error_dialog(title = _("Error"),
+						message = _("An error occurred while trying to download the album.\nThe error text is:\n%s") % str(e))
 
-		except Exception, e:
-			rb.error_dialog(title = _("Error"),
-					message = _("An error occurred while trying to download the album.\nThe error text is:\n%s") % str(e))
 
+		keyring.find_items(keyring.ITEM_GENERIC_SECRET, {'rhythmbox-plugin': 'magnatune'}, got_items)
 
 	def __download_album(self, audio_dl_uri, sku):
-		destpath = os.path.join(magnatune_in_progress_dir, sku)
-
-		shell = self.get_property('shell')
-		manager = shell.get_player().get_property('ui-manager')
-		manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(True)
-		self.__downloading = True
-		self.cancelled = False
-
-		self.__downloads[audio_dl_uri] = 0
+		def download_album_chunk(result, total):
+			if not result:
+				download_finished(total, True)
+			elif isinstance(result, Exception):
+				# probably report this somehow?
+				pass
+			elif self.cancelled:
+				download_finished(total, False)
+				return False
+			else:
+				if self.__downloads[audio_dl_uri] == 0:
+					self.purchase_filesize += total
 
-		# no way to resume downloads, sadly
-		out = open(destpath, 'w')
+				out.write(result)
+				self.__downloads[audio_dl_uri] += len(result)
 
-		dl = rb.ChunkLoader()
-		dl.get_url_chunks(audio_dl_uri, 4*1024, True, self.__download_album_chunk, (audio_dl_uri, destpath, out, sku))
+				self.__download_progress = sum(self.__downloads.values()) / float(self.purchase_filesize)
+				self.__notify_status_changed()
 
+		def download_finished(total, success):
+			try:
+				del self.__downloads[audio_dl_uri]
+				self.purchase_filesize -= total
+			except:
+				pass
 
-	def __remove_download_files (self, dest, sku):
-		sp = os.path.split(dest)
-		inprogress = os.path.join(sp[0], "in_progress_" + sku)
-		os.unlink(inprogress)
-		os.unlink(dest)
+			out.close()
+			if success:
+				threading.Thread(target=unzip_album).start()
+			else:
+				remove_download_files()
 
+			if self.purchase_filesize == 0: # All downloads are complete
+				self.__downloading = False
+				shell = self.get_property('shell')
+				manager = shell.get_player().get_property('ui-manager')
+				manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(False)
+				if success:
+					width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_LARGE_TOOLBAR)
+					icon = rb.try_load_icon(gtk.icon_theme_get_default(), "magnatune", width, 0)
+					shell.notify_custom(4000, _("Finished Downloading"), _("All Magnatune downloads have been completed."), icon, True)
 
-	def __download_finished (self, total, audio_dl_uri, dest, out, sku):
 		def unzip_album():
 			# just use the first library location
 			library_location = gio.File(uri=self.__client.get_list("/apps/rhythmbox/library_locations", gconf.VALUE_STRING)[0])
@@ -498,56 +501,33 @@ class MagnatuneSource(rb.BrowserSource):
 					self.__db.add_uri(track_uri)
 
 			album.close()
-			self.__remove_download_files(dest, sku)
-		
-		try:
-			del self.__downloads[audio_dl_uri]
-		except:
-			return 0
-		
-		out.close()
-		threading.Thread(target=unzip_album).start()
-		
-		self.purchase_filesize -= total
-		if self.purchase_filesize == 0: # All downloads are complete
-			self.__downloading = False
-			shell = self.get_property('shell')
-			width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_LARGE_TOOLBAR)
-			icon = rb.try_load_icon(gtk.icon_theme_get_default(), "magnatune", width, 0)
-			shell.notify_custom(4000, _("Finished Downloading"), _("All Magnatune downloads have been completed."), icon, True)
-			manager = shell.get_player().get_property('ui-manager')
-			manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(False)
-
-
-	def __download_album_chunk(self, result, total, (audio_dl_uri, dest, out, sku)):
-		if not result:
-			self.__download_finished (total, audio_dl_uri, dest, out, sku)
-		elif isinstance(result, Exception):
-			# probably report this somehow?
-			pass
-		elif self.cancelled:
-			try:
-				del self.__downloads[audio_dl_uri]
-				self.purchase_filesize -= total
+			remove_download_files()
 
-				self.__remove_download_files (dest, sku)
+		def remove_download_files():
+			os.unlink(in_progress)
+			os.unlink(dest)
 
-			except:
-				pass
 
-			if self.purchase_filesize == 0:
-				self.__downloading = False
+		in_progress = os.path.join(magnatune_in_progress_dir, "in_progress_" + sku)
+		dest = os.path.join(magnatune_in_progress_dir, sku)
 
-			return False
-		else:
-			if self.__downloads[audio_dl_uri] == 0:
-				self.purchase_filesize += total
+		ip = open(in_progress, 'w')
+		ip.write(str(audio_dl_uri))
+		ip.close()
 
-			out.write(result)
-			self.__downloads[audio_dl_uri] += len(result)
+		shell = self.get_property('shell')
+		manager = shell.get_player().get_property('ui-manager')
+		manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(True)
+		self.__downloading = True
+		self.cancelled = False
 
-			self.__download_progress = sum(self.__downloads.values()) / float(self.purchase_filesize)
-			self.__notify_status_changed()
+		self.__downloads[audio_dl_uri] = 0
+
+		# no way to resume downloads, sadly
+		out = open(dest, 'w')
+
+		dl = rb.ChunkLoader()
+		dl.get_url_chunks(audio_dl_uri, 4*1024, True, download_album_chunk)
 
 
 	def cancel_downloads(self):
@@ -556,22 +536,21 @@ class MagnatuneSource(rb.BrowserSource):
 		manager = shell.get_player().get_property('ui-manager')
 		manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(False)
 
-	def playing_entry_changed (self, entry):
+	def playing_entry_changed(self, entry):
 		if not self.__db or not entry:
 			return
-
 		if entry.get_entry_type() != self.__db.entry_type_get_by_name("MagnatuneEntryType"):
 			return
 
-		gobject.idle_add (self.emit_cover_art_uri, entry)
+		gobject.idle_add(self.emit_cover_art_uri, entry)
 
-	def emit_cover_art_uri (self, entry):
+	def emit_cover_art_uri(self, entry):
 		sku = self.__sku_dict[self.__db.entry_get(entry, rhythmdb.PROP_LOCATION)]
 		url = self.__art_dict[sku]
-		self.__db.emit_entry_extra_metadata_notify (entry, 'rb:coverArt-uri', url)
+		self.__db.emit_entry_extra_metadata_notify(entry, 'rb:coverArt-uri', url)
 		return False
 
-	def __move_data_files (self):
+	def __move_data_files(self):
 		# create cache and data directories
 		# (we know they don't already exist, and we know the parent dirs do)
 		os.mkdir(magnatune_in_progress_dir, 0700)
diff --git a/plugins/magnatune/magnatune/TrackListHandler.py b/plugins/magnatune/magnatune/TrackListHandler.py
index aa9681b..14bc9b6 100644
--- a/plugins/magnatune/magnatune/TrackListHandler.py
+++ b/plugins/magnatune/magnatune/TrackListHandler.py
@@ -31,7 +31,6 @@ import xml.sax, xml.sax.handler
 import datetime, re, urllib
 
 class TrackListHandler(xml.sax.handler.ContentHandler):
-
 	def __init__(self, db, entry_type, sku_dict, home_dict, art_dict, account_type, username, password):
 		xml.sax.handler.ContentHandler.__init__(self)
 		self.__db = db
@@ -65,7 +64,7 @@ class TrackListHandler(xml.sax.handler.ContentHandler):
 				# use ad-free tracks if available
 				if self.__account_type != 'none':
 					trackurl = self.fix_trackurl(trackurl)
-	
+
 				# add the track to the source
 				entry = self.__db.entry_lookup_by_location (trackurl)
 				if entry == None:
diff --git a/plugins/magnatune/magnatune/__init__.py b/plugins/magnatune/magnatune/__init__.py
index ec9d7aa..d5b2c40 100644
--- a/plugins/magnatune/magnatune/__init__.py
+++ b/plugins/magnatune/magnatune/__init__.py
@@ -75,7 +75,7 @@ class Magnatune(rb.Plugin):
 	#
 	# Core methods
 	#
-	
+
 	def __init__(self):
 		rb.Plugin.__init__(self)
 
@@ -94,21 +94,21 @@ class Magnatune(rb.Plugin):
 		width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_LARGE_TOOLBAR)
 		icon = rb.try_load_icon(theme, "magnatune", width, 0)
 
-		group = rb.rb_source_group_get_by_name ("stores")
-		self.source = gobject.new (MagnatuneSource,
- 					   shell=shell,
- 					   entry_type=self.entry_type,
- 					   source_group=group,
-					   icon=icon,
- 					   plugin=self)
+		group = rb.rb_source_group_get_by_name("stores")
+		self.source = gobject.new(MagnatuneSource,
+					  shell=shell,
+					  entry_type=self.entry_type,
+					  source_group=group,
+					  icon=icon,
+					  plugin=self)
 
 		shell.register_entry_type_for_source(self.source, self.entry_type)
 		shell.append_source(self.source, None) # Add the source to the list
-		
+
 		manager = shell.get_player().get_property('ui-manager')
 		# Add the popup menu actions
 		self.action_group = gtk.ActionGroup('MagnatunePluginActions')
-		
+
 		action = gtk.Action('MagnatunePurchaseAlbum', _('Purchase Album'),
 				_("Purchase this album from Magnatune"),
 				'gtk-add')
@@ -130,7 +130,7 @@ class Magnatune(rb.Plugin):
 		action.connect('activate', lambda a: self.shell.get_property("selected-source").cancel_downloads())
 		action.set_sensitive(False)
 		self.action_group.add_action(action)
-		
+
 		manager.insert_action_group(self.action_group, 0)
 		self.ui_id = manager.add_ui_from_string(popup_ui)
 
@@ -139,11 +139,11 @@ class Magnatune(rb.Plugin):
 
 	def deactivate(self, shell):
 		manager = shell.get_player().get_property('ui-manager')
-		manager.remove_ui (self.ui_id)
+		manager.remove_ui(self.ui_id)
 		manager.remove_action_group(self.action_group)
 		self.action_group = None
 
-		shell.get_player().disconnect (self.pec_id)
+		shell.get_player().disconnect(self.pec_id)
 
 		self.db.entry_delete_by_type(self.entry_type)
 		self.db.commit()
@@ -154,14 +154,15 @@ class Magnatune(rb.Plugin):
 		self.shell = None
 
 	def playing_entry_changed (self, sp, entry):
-		self.source.playing_entry_changed (entry)
-	
+		self.source.playing_entry_changed(entry)
+
 	def create_configure_dialog(self, dialog=None):
+		# We use a dictionary so we can modify these values from within inner functions
 		keyring_data = {
 			'id': 0,
 			'item': None
 		}
-		
+
 		def got_items(result, items):
 			def created_item(result, id):
 				if result is None: # Item successfully created
@@ -178,8 +179,8 @@ class Magnatune(rb.Plugin):
 					print "Couldn't retrieve keyring item: " + str(result)
 				fill_account_details()
 				dialog.present()
-			
-			
+
+
 			if result is None and len(items) != 0: # Got list of search results
 				keyring_data['id'] = items[0].item_id
 				keyring.item_get_info(None, keyring_data['id'], got_item)
@@ -195,15 +196,15 @@ class Magnatune(rb.Plugin):
 				print "Couldn't access keyring: " + str(result)
 				fill_account_details()
 				dialog.present()
-		
-		
+
+
 		if dialog == None:
 			def fill_account_details():
 				account_type = self.client.get_string(self.gconf_keys['account_type'])
 				builder.get_object("no_account_radio").set_active(account_type == "none")
 				builder.get_object("stream_account_radio").set_active(account_type == "stream")
 				builder.get_object("download_account_radio").set_active(account_type == "download")
-				
+
 				username = ""
 				password = ""
 				try:
@@ -213,13 +214,13 @@ class Magnatune(rb.Plugin):
 					pass
 				builder.get_object("username_entry").set_text(username)
 				builder.get_object("password_entry").set_text(password)
-				
+
 				has_account = account_type != "none"
 				builder.get_object("username_entry").set_sensitive(has_account)
 				builder.get_object("password_entry").set_sensitive(has_account)
 				builder.get_object("username_label").set_sensitive(has_account)
 				builder.get_object("password_label").set_sensitive(has_account)
-				
+
 				builder.get_object("account_changed_label").hide()
 
 			def account_type_toggled (button):
@@ -238,15 +239,15 @@ class Magnatune(rb.Plugin):
 						builder.get_object("password_label").set_sensitive(True)
 						builder.get_object("password_entry").set_sensitive(True)
 					builder.get_object("account_changed_label").show()
-			
+
 			def account_details_changed(entry):
 				username = builder.get_object("username_entry").get_text()
 				password = builder.get_object("password_entry").get_text()
 				if keyring_data['item']:
 					keyring_data['item'].set_secret('\n'.join((username, password)))
-				
+
 				builder.get_object("account_changed_label").show()
-			
+
 			def close_button_pressed(x, y):
 				try:
 					if keyring_data['id'] and keyring_data['item']:
@@ -259,11 +260,11 @@ class Magnatune(rb.Plugin):
 					rb.error_dialog(title = _("Couldn't store account information"),
 					                message = str(e))
 				dialog.hide()
-				
+
 
 			self.configure_callback_dic = {
 				"rb_magnatune_audio_combobox_changed_cb" : lambda w: self.client.set_string(self.gconf_keys['format'], self.format_list[w.get_active()]),
-				
+
 				"rb_magnatune_radio_account_toggled_cb" : account_type_toggled,
 				"rb_magnatune_username_changed_cb" : account_details_changed,
 				"rb_magnatune_password_changed_cb" : account_details_changed
@@ -274,12 +275,11 @@ class Magnatune(rb.Plugin):
 
 			# FIXME this bit should be in builder too  (what?)
 			dialog = builder.get_object('preferences_dialog')
-			
+
 			builder.get_object("audio_combobox").set_active(self.format_list.index(self.client.get_string(self.gconf_keys['format'])))
-			
+
 			builder.connect_signals(self.configure_callback_dic)
 			dialog.connect("response", close_button_pressed)
-		
+
 		keyring.find_items(keyring.ITEM_GENERIC_SECRET, {'rhythmbox-plugin': 'magnatune'}, got_items)
 		return dialog
-



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]