#!/usr/bin/env python
#
# A basic script for exporting a list of your currently open tabs in Safari.
# Still rather rough at the moment, but it works.
# Requires appscript to be installed.
#
# James Frost (frosty@sucs.org)
# 2008-05-26

import sys, os
from appscript import *

# This is the file your tabs will be saved to.
SAVE_FILE = "saftabs.html"

# Details for uploading the file, using scp and a key
# (comment out line 72 if you don't want to upload)
server='foo.com' 
user='bob' 
remote_root='/home/bob/public_html' 

# Uploads the file via scp.
def upload(thePath):
	path, filename = os.path.split(thePath)
	cmd = 'scp %s %s@%s:%s' % 
					(thePath, user, server, os.path.join(remote_root,filename)) 
	failure = os.system(cmd) 
	if failure: print "Running %s failed..."%cmd; return

# Creates the HTML file containing the URLs
def export_to_HTML(urls):
	global SAVE_FILE, user
	
	f = open(SAVE_FILE, "w")
	f.write("""<html>
	<head>
	<title>""" + capitalize(user) + """'s Safari Tabs</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<meta name="ROBOTS" content="NOINDEX" />
	<meta name="ROBOTS" content="NOFOLLOW" />
	</head>
	<body>
	<h1>Safari Tabs (""" + str(len(urls)) + """)</h1>
	<p><ul>""")
	
	for url, title in urls:
		f.write(u'<li><a href="%s" title="%s">%s</a></li>\n' % (url, title, title))
	f.write("""</ul><p>
	</body></html>""")
	f.close()

# Get the actual tab names and urls from Safari, using appscript
def get_tabs():	
	safari = app('safari')
	urls = []
	urlcount = 0
	
	for window in safari.windows():
		try:
			for tab in window.tabs():
				urls.append((tab.URL().encode('ascii', 'xmlcharrefreplace'), tab.name().encode('ascii', 'xmlcharrefreplace')))
		except Exception, e:
			# print e
			# print "window has no tabs"
			pass
	return urls

if __name__ == '__main__':
	# TODO: Add option to not upload the file
	# TODO: Add ability to specify filename as argument
	export_to_HTML(get_tabs())
	upload(SAVE_FILE)