#!/usr/bin/env python

# Comicthumb alpha
# Create thumbnails for comic book archives (cbz, cbt and cbr)
#
# Copyright (c) 2006 Christoph Wolk <christoph.wolk@googlemail.com>
#
# Released under the GNU General Public License
#
# Known Issues:
# - errors with interlaced pngs
# - files in rars with whitespace at the beginning/end will probably cause errors 
#   (probably a very pathological case)
# - generally no error handling whatsoever
# - No archives-within-archives possible (and these will probably be a major PITA)
#
# Features to be added
# - cover guessing should be improved
# - add some image manipulation stuff (configurable) like a watermark or borders

import os
import sys
import zipfile
import tarfile
import StringIO
import re
import locale
import shutil
try:
	import Image
except:
	sys.exit(1)
	
THUMB_SIZE = 128

if len(sys.argv) == 4:
	if sys.argv[3].isdigit():
		THUMB_SIZE = int(sys.argv[3])

# get paths
locale.setlocale(locale.LC_COLLATE, os.getenv('LC_COLLATE'))
in_file_path = sys.argv[1]
out_file_path = sys.argv[2]

# still need a temporary dir for rars currently
if not os.path.exists('/tmp/comicthumb/'):
	os.makedirs('/tmp/comicthumb/')
	os.chmod('/tmp/comicthumb/', 0700)

def firstImage (filelist):
	exts=re.compile('jpg$|png$|jpeg$|gif$', re.IGNORECASE)
	for file in filelist:
		if exts.search(file):
			return file
	return False

# try to find the cover, if nothing good is found take first
def guessCover (filelist):
	# very basic, should not get eg backcover if possible
	p = re.compile('cover|front', re.IGNORECASE)
	coverlist = filter(p.search, filelist)
	firstcover=firstImage(coverlist)
	if firstcover:
		return firstcover 
	else:
		return firstImage(filelist)

try:
	if zipfile.is_zipfile(in_file_path):
		type = 'cbz'
		zip = zipfile.ZipFile(in_file_path, "r")
		zipfiles = zip.namelist()
		zipfiles.sort(locale.strcoll)
		cover=guessCover(zipfiles)
		image=Image.open(StringIO.StringIO(zip.read(cover)))
		zip.close()
	elif tarfile.is_tarfile(in_file_path):
		type = 'cbt'
		file = open(in_file_path, 'rb')
		tar = tarfile.open(in_file_path, "r")
		tarfiles = tar.getnames()
		tarfiles.sort(locale.strcoll)
		cover=guessCover(tarfiles)
		picture=StringIO.StringIO(tar.extractfile(cover).read())
		image=Image.open(picture)
		tar.close()
	elif open(in_file_path, 'rb').read(4) == 'Rar!':
		type = 'cbr'
		if os.popen("unrar h").close():
			print "You need to install unrar to thumbnail rar files."
			sys.exit(1)
		rarfiles=os.popen('unrar vb "' + in_file_path + '"').readlines()
		for i in range(len(rarfiles)):
			rarfiles[i]=rarfiles[i].rstrip("\n")
		rarfiles.sort(locale.strcoll)
		cover = guessCover(rarfiles)
		os.popen('unrar p -inul "' + in_file_path + '" "' + cover + '" > /tmp/comicthumb/temp.jpg', "r").close()
		image=Image.open("/tmp/comicthumb/temp.jpg")
	
	if image.size[0] > image.size[1]:
		x = THUMB_SIZE
		y = THUMB_SIZE * image.size[1] / image.size[0]
	else:
		x = THUMB_SIZE * image.size[0] / image.size[1]
		y = THUMB_SIZE
	image = image.resize((x, y), Image.ANTIALIAS)
	image = image.convert('RGB')
	
	try:
		if os.path.exists('../share/pixmaps/comix/' + type + '.png'):
			overlay_path = '../share/pixmaps/comix/' + type + '.png'
		elif os.path.exists('/usr/local/share/pixmaps/comix/' + type + '.png'):
			overlay_path = '/usr/local/share/pixmaps/comix/' + type + '.png'
		elif os.path.exists('/usr/share/pixmaps/comix/' + type + '.png'):
			overlay_path = '/usr/share/pixmaps/comix/' + type + '.png'
		
		overlay_image=Image.open(overlay_path)
		image_canvas = Image.new('RGBA', (image.size[0], image.size[1]), (0, 0, 0, 0))
		image_canvas.paste(overlay_image, (image.size[0] - 35, image.size[1] - 30))
		image = Image.composite(image_canvas, image, image_canvas)
	except:
		pass
	
	image.save(out_file_path, 'PNG')
	exit_flag = 0
except:
	exit_flag = 1

if os.path.isdir('/tmp/comicthumb/'):
	shutil.rmtree('/tmp/comicthumb/')
sys.exit(exit_flag)
