# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

import gdata.service
import urllib2
import re
import traceback

try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree


class YouTubeClient:

    users_feed = "http://gdata.youtube.com/feeds/users"
    std_feeds = "http://gdata.youtube.com/feeds/standardfeeds"
    video_name_re = re.compile(r', "t": "([^"]+)"')
    
    def _request(self, feed, *params):
        service = gdata.service.GDataService(server="gdata.youtube.com")
        return service.Get(feed % params)

    def recently_featured(self, time='today'):
        return self._request("%s/recently_featured", self.std_feeds).entry

    def top_rated(self):
        return self._request("%s/top_rated" % self.std_feeds).entry

    def most_viewed(self):
        return self._request("%s/most_viewed" % self.std_feeds).entry

    def videos_upload_by(self, username):
        return self._request("%s/%s/uploads", self.users_feed,
                             username).entry

    def favorite_videos(self, username):
        return self._request("%s/%s/favorites", self.users_feed,
                             username).entry

    def get_contacts(self, username):
        users = self._request("%s/%s/contacts", self.users_feed,
                              username).entry
        contacts = [ user.title.text for user in users ]
        return contacts
        
    def get_categories(self):
        feed_url = "http://gdata.youtube.com/schemas/2007/categories.cat"
        xml = self._request(feed_url)
        tree = ElementTree.fromstring(xml)
        categories = {}
        for child in tree.getchildren():
            categories[child.get('term')] = child.get('label')
        return categories
    
    def get_category(self, cid):
        feed_url = "http://gdata.youtube.com/feeds/videos/-/%s" % cid
        return self._request(feed_url).entry
        
    def get_thumbnails(self, video):
        doc = video._ToElementTree()
        urls = {}
        for c in doc.findall(".//{http://search.yahoo.com/mrss/}group"):
            for cc in c.findall("{http://search.yahoo.com/mrss/}thumbnail"):
                width = int(cc.get("width"))
                height = int(cc.get("height"))
                size = (width, height)
                url = cc.get("url")
                if size not in urls:
                    urls[size] = [url,]
                else:
                    urls[size].append(url)
        return urls

    def get_largest_thumbnail(self, video):
        thumbnails = self.get_thumbnails(video)
        sizes = thumbnails.keys()
        sizes.sort()
        return thumbnails[sizes[-1]][0]

    def get_flv_video_url(self, url):
        flv_url = ''
        doc = urllib2.urlopen(url)
        data = doc.read()

        # extract video name
        match = self.video_name_re.search(data)
        if match is not None:
            video_name = match.group(1)

            # extract video id
            url_splited = url.split("watch?v=")
            video_id = url_splited[1]     

            flv_url = "http://www.youtube.com/get_video?video_id=%s&t=%s"
            flv_url = flv_url % (video_id, video_name)
        return flv_url

if __name__ == '__main__':
    cli = YouTubeClient()
    import pdb; pdb.set_trace()
