# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# This file is part of clive.
#
# clive is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# clive is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with clive.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################

## The classes that wrap various host log in functionalities

__all__ = ['Login']

from clive.passwd import Passwd
from clive.modules import Modules
from clive.opts import Options
from clive.error import CliveError

## The log in class
class Login:

    ## Constructor
    def __init__(self, opener, proxy, say):
        self._opts = Options()._opts
        self._opener = opener
        self._proxy = proxy
        self._say = say
        (self._URLGrabber, self._URLGrabError) = \
            Modules().getinst('urlgrabber')

    def _get_passwd(self, name):
        (usern,passw)= Passwd().get_entry(name, self._opts.passwd_passphrase)
        return (usern,passw)

    ## Youtube: log-in and confirm age
    def youtube(self):
        if not self._opts.youtube_login: return
        (usern,passw) = self._opts.youtube_login.split(':')
        if usern == 'passwd':
            (usern,passw) = self._get_passwd(passw)
        self._say('youtube: attempt to login...')
        url = 'http://youtube.com/login?'
        url += ('current_form=loginform&username=%s&' \
            'password=%s&action_login=log+in' % (usern,passw))
        data = self._urlopen(url)
        if 'login was incorrect' in data.lower():
            self._say('youtube: incorrect login')
            raise SystemExit
        url = 'http://youtube.com/verify_age?action_confirm=Confirm'
        self._urlopen(url)
        self._say('youtube: login ok')

    ## Metacafe: disable family filter
    def metacafe(self):
        url = 'http://metacafe.com/family_filter?filters=0'
        self._urlopen(url, read=0)

    ## Dailymotion: log-in
    def dmotion(self):
        if not self._opts.dmotion_login: return
        (usern,passw) = self._opts.dmotion_login.split(':')
        if usern == 'passwd':
            (usern,passw) = self._get_passwd(passw)
        self._say('dmotion: attempt to login...')
        url='http://dailymotion.com/login?username=%s&password=%s' % (
            usern,passw)
        data = self._urlopen(url)
        if 'wrong login data' in data.lower():
            self._say('dmotion: incorrect login')
            raise SystemExit
        self._say('dmotion: known-bug: probably ok, try again if ' +
            'extraction fails')

    def _urlopen(self, url, read=1):
        data = ''
        try:
            g = self._URLGrabber(
                http_headers = (('accept-encoding', 'gzip'),),
                user_agent = self._opts.http_agent,
                proxies = self._proxy,
                opener = self._opener)
            o = g.urlopen(url)
            if read:
                data = o.read()
                if o.hdr.get('content-encoding') == 'gzip':
                    m = Modules()
                    gzip = m.getinst('gzip')
                    StringIO = m.getinst('StringIO')
                    data = gzip.GzipFile(fileobj=StringIO(data)).read()
            return data
        except self._URLGrabError, err:
            self._say('%s [%s]' % (err.strerror,url), is_error=1)
            raise SystemExit
