def generate_metadata_files(video_dir):
	"""Generate TiVo metadata files for all videos in a directory."""
	
	for dirname, dirnames, filenames in os.walk(video_dir):
		for filename in filenames:
			# All non-text files are assumed to be videos.
			if filename.endswith(".txt"):
				continue
			
			extension = os.path.splitext(filename)[1]
			
			if not extension:
				continue
			
			metadata_filename = filename + ".txt"
			
			if os.path.exists(os.path.join(dirname, metadata_filename)):
				continue
			
			title, file_comments = pytivo_utilities.parse_filename(filename)
			
			metadata = {}
			metadata['title'] = title
			metadata['vProgramGenre'] = 'Movies'
			metadata['isEpisode'] = 'false'
			
			request = urllib2.Request("http://www.omdbapi.com/?%s" % urllib.urlencode( { 't' : title } ))
			opener = urllib2.build_opener()
			f = opener.open(request)
			api_data = json.load(f)
			
			if api_data and api_data['Response'] == 'True':
				metadata['title'] = api_data['Title']
				metadata['year'] = metadata['movieYear'] = api_data['Year']
				metadata['description'] = api_data['Plot']
				metadata['mpaaRating'] = pytivo_utilities.movie_rating_code_from_rating(api_data['Rated'])
				
				multiple_value_keys = { "Actors" : "vActor", "Director" : "vDirector", "Writer" : "vWriter", "Genre" : "vProgramGenre" }
				
				for (json_field, metadata_field) in multiple_value_keys.items():
					if json_field in api_data:
						metadata[metadata_field] = []
					
						for entry in api_data[json_field].split(', '):
							metadata[metadata_field].append(entry)
			
			metadata_file_handle = open(os.path.join(dirname, metadata_filename), 'w')
			metadata_file_handle.write(pytivo_utilities.metadata_dict_to_string(metadata).encode('utf8'))
			metadata_file_handle.close()
def generate_commentary_streams(video_dir):
	"""Create a second (hardlinked) video file for each commentary track."""
	
	for dirname, dirnames, filenames in os.walk(video_dir):
		for filename in filenames:
			# All non-text files are assumed to be videos.
			if filename.endswith(".txt"):
				continue
			
			extension = os.path.splitext(filename)[1]
			
			if not extension:
				continue
			
			if " - Commentary #" in filename:
				# Already generated by this tool.
				continue
			
			title, file_comments = pytivo_utilities.parse_filename(filename)
			
			if not file_comments:
				# No commentary tracks noted
				continue
			
			metadata_filename = filename + ".txt"
			
			if os.path.exists(metadata_filename):
				metadata = pytivo_utilities.parse_metadata_text(open(os.path.join(dirname, metadata_filename)).read().decode("utf-8"))
			else:
				metadata = {}
			
			if 'title' not in metadata:
				metadata['title'] = [ title ]
			
			commentary_count = 0
			
			file_comments = file_comments.split(', ')
			
			for comment in file_comments:
				if comment.find("Commentary") == 0:
					if "Commentary" == comment:
						commentary_count = 1
					else:
						commentary_count = int(comment.split(' x ')[1])
			
			original_title = metadata['title'][0]
			
			for i in range(1, commentary_count + 1):
				commentary_filename = '%s - Commentary #%s%s' % (title, i, extension)
				
				if commentary_filename not in filenames:
					try:
						os.link(os.path.join(dirname, filename), os.path.join(dirname, commentary_filename))
					except OSError:
						print "Could not create %s" % os.path.join(dirname, commentary_filename)
						continue
				
				metadata['title'] = '%s - Commentary #%s' % (original_title, i)
				
				commentary_metadata_file_handle = open(os.path.join(dirname, commentary_filename) + ".txt", 'w')
				commentary_metadata_file_handle.write((u"%sOverride_mapAudio 0.%s : commentary\n" % (pytivo_utilities.metadata_dict_to_string(metadata), i + 1)).encode('utf8'))
				commentary_metadata_file_handle.close()