<commit_before># Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see
# http://www.gnu.org/licenses/agpl-3.0.html.

import logging

from django.contrib import messages
from django.contrib import auth
from django.contrib.admin.views.decorators import staff_member_required
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.http import is_safe_url
from django.utils.translation import ugettext as _

from auth.models import CustomUser as User
from externalsites import forms
from externalsites import google
from externalsites.auth_backends import OpenIDConnectInfo
from externalsites.exceptions import YouTubeAccountExistsError
from externalsites.models import get_sync_account, YouTubeAccount
from localeurl.utils import universal_url
from teams.models import Team
from teams.permissions import can_change_team_settings
from teams.views import settings_page
from utils.text import fmt
from videos.models import VideoUrl

logger = logging.getLogger('amara.externalsites.views')

class AccountFormHandler(object):
    """Handles a single form for the settings tab

    On the settings tab we show several forms for different accounts.
    AccountFormHandler handles the logic for a single form.
    """
    def __init__(self, form_name, form_class):
        self.form_name = form_name
        self.form_class = form_class
        self.should_redirect = False

    def handle_post(self, post_data, context):
        pass

    def handle_get(self, post_data, context):
        pass

@settings_page
def team_settings_tab(request, team):
    if request.method == 'POST':
        formset = forms.AccountFormset(request.user, team, request.POST)
    else:
        formset = forms.AccountFormset(request.user, team, None)

    if formset.is_valid():
        formset.save()
        if 'remove-youtube-account' in request.POST:
            account = YouTubeAccount.objects.for_owner(team).get(
                id=request.POST['remove-youtube-account'])
            account.delete()
        return redirect(settings_page_redirect_url(team, formset))

    return render(request, 'externalsites/team-settings-tab.html', {
        'team': team,
        'forms': formset,
    })

def settings_page_redirect_url(team, formset):
    redirect_path = formset.redirect_path()
    if redirect_path is not None:
        return redirect_path
    else:
        return reverse('teams:settings_externalsites', kwargs={
            'slug': team.slug,
        })

def google_callback_url():
    return universal_url(
        'externalsites:google-callback',
        protocol_override=settings.OAUTH_CALLBACK_PROTOCOL)

def google_login(request):
    state = {
        'type': 'login',
        'next': request.GET.get('next')
    }
    return redirect(google.request_token_url(
        google_callback_url(), 'online', state, ['profile', 'email']))

def handle_login_callback(request, auth_info):
    profile_info = google.get_openid_profile(auth_info.access_token)
    openid_connect_info = OpenIDConnectInfo(
        auth_info.sub, profile_info.email, auth_info.openid_id, {
            'full_name': profile_info.full_name,
            'first_name': profile_info.first_name,
            'last_name': profile_info.last_name
        }
    )
    user = auth.authenticate(openid_connect_info=openid_connect_info)
    if not user:
        messages.error(request, _("OpenID Connect error"))
        return redirect('videos.videos.index')
    auth.login(request, user)
    next_url = auth_info.state.get('next')
    if next_url and is_safe_url(next_url):
        return HttpResponseRedirect(next_url)
    else:
        return redirect('videos.videos.index')

def youtube_add_account(request):
    if 'team_slug' in request.GET:
        state = {'team_slug': request.GET['team_slug']}
    elif 'username' in request.GET:
        state = {'username': request.GET['username']}
    else:
        logging.error("youtube_add_account: Unknown owner")
        raise Http404()
    state['type'] = 'add-account'
    return redirect(google.request_token_url(
        google_callback_url(), 'offline', state,
        youtube_scopes()))

def handle_add_account_callback(request, auth_info):
    try:<commit_msg>Fixed missing package name<commit_after># Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see
# http://www.gnu.org/licenses/agpl-3.0.html.

import logging

from django.contrib import messages
from django.contrib import auth
from django.contrib.admin.views.decorators import staff_member_required
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.http import is_safe_url
from django.utils.translation import ugettext as _

from auth.models import CustomUser as User
from externalsites import forms
from externalsites import google
from externalsites.auth_backends import OpenIDConnectInfo
from externalsites.exceptions import YouTubeAccountExistsError
from externalsites.models import get_sync_account, YouTubeAccount
from localeurl.utils import universal_url
from teams.models import Team
from teams.permissions import can_change_team_settings
from teams.views import settings_page
from utils.text import fmt
from videos.models import VideoUrl

logger = logging.getLogger('amara.externalsites.views')

class AccountFormHandler(object):
    """Handles a single form for the settings tab

    On the settings tab we show several forms for different accounts.
    AccountFormHandler handles the logic for a single form.
    """
    def __init__(self, form_name, form_class):
        self.form_name = form_name
        self.form_class = form_class
        self.should_redirect = False

    def handle_post(self, post_data, context):
        pass

    def handle_get(self, post_data, context):
        pass

@settings_page
def team_settings_tab(request, team):
    if request.method == 'POST':
        formset = forms.AccountFormset(request.user, team, request.POST)
    else:
        formset = forms.AccountFormset(request.user, team, None)

    if formset.is_valid():
        formset.save()
        if 'remove-youtube-account' in request.POST:
            account = YouTubeAccount.objects.for_owner(team).get(
                id=request.POST['remove-youtube-account'])
            account.delete()
        return redirect(settings_page_redirect_url(team, formset))

    return render(request, 'externalsites/team-settings-tab.html', {
        'team': team,
        'forms': formset,
    })

def settings_page_redirect_url(team, formset):
    redirect_path = formset.redirect_path()
    if redirect_path is not None:
        return redirect_path
    else:
        return reverse('teams:settings_externalsites', kwargs={
            'slug': team.slug,
        })

def google_callback_url():
    return universal_url(
        'externalsites:google-callback',
        protocol_override=settings.OAUTH_CALLBACK_PROTOCOL)

def google_login(request):
    state = {
        'type': 'login',
        'next': request.GET.get('next')
    }
    return redirect(google.request_token_url(
        google_callback_url(), 'online', state, ['profile', 'email']))

def handle_login_callback(request, auth_info):
    profile_info = google.get_openid_profile(auth_info.access_token)
    openid_connect_info = OpenIDConnectInfo(
        auth_info.sub, profile_info.email, auth_info.openid_id, {
            'full_name': profile_info.full_name,
            'first_name': profile_info.first_name,
            'last_name': profile_info.last_name
        }
    )
    user = auth.authenticate(openid_connect_info=openid_connect_info)
    if not user:
        messages.error(request, _("OpenID Connect error"))
        return redirect('videos.videos.index')
    auth.login(request, user)
    next_url = auth_info.state.get('next')
    if next_url and is_safe_url(next_url):
        return HttpResponseRedirect(next_url)
    else:
        return redirect('videos.videos.index')

def youtube_add_account(request):
    if 'team_slug' in request.GET:
        state = {'team_slug': request.GET['team_slug']}
    elif 'username' in request.GET:
        state = {'username': request.GET['username']}
    else:
        logging.error("youtube_add_account: Unknown owner")
        raise Http404()
    state['type'] = 'add-account'
    return redirect(google.request_token_url(
        google_callback_url(), 'offline', state,
        google.youtube_scopes()))

def handle_add_account_callback(request, auth_info):
    try:
{'fraction_non_alphanumeric': 0.08476781425140112, 'fraction_numerical': 0.0032025620496397116, 'mean_word_length': 3.7608384945212006, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4482550', 'n_tokens_mistral': 2846, 'n_tokens_neox': 2801, 'n_words': 810}