Ejemplo n.º 1
0
 def get_language_code_display(self):
     if self.language_code:
         try:
             language_code_display = translation.get_language_label(self.language_code)
         except KeyError:
             logger.error("Error with language code {} in activity record {}".format(self.id, self.language_code))
             try:
                 language_code_display = translation.get_language_label(self.language_code.lower())
             except KeyError:
                 logger.error("Error with language code {} in activity record {} can not be fixed".format(self.id, self.language_code))
                 language_code_display = 'Unknown language'
         return language_code_display
     else:
         return ''
Ejemplo n.º 2
0
    def send_messages(self, note, user_list):
        subject = fmt(_(u'%(user)s added a note while editing %(title)s'),
                      user=unicode(note.user),
                      title=self.video.title_display())

        tasks_url = universal_url('teams:team_tasks',
                                  kwargs={
                                      'slug': self.team.slug,
                                  })
        filter_query = '?team_video={0}&assignee=anyone&lang={1}'
        filter_query = filter_query.format(self.team_video.pk,
                                           self.language_code)
        data = {
            'note_user': unicode(note.user),
            'body': note.body,
            'tasks_url': tasks_url + filter_query,
            'video': self.video.title_display(),
            'language': translation.get_language_label(self.language_code),
        }
        email_template = ("messages/email/"
                          "task-team-editor-note-notifiction.html")
        message_template = 'messages/task-team-editor-note.html'

        for user in user_list:
            send_templated_email(user,
                                 subject,
                                 email_template,
                                 data,
                                 fail_silently=not settings.DEBUG)

            Message.objects.create(user=user,
                                   subject=subject,
                                   message_type="S",
                                   content=render_to_string(
                                       message_template, data))
Ejemplo n.º 3
0
def all_languages_page(request, team):
    video_language_counts = dict(team.get_video_language_counts())
    completed_language_counts = dict(team.get_completed_language_counts())

    all_languages = set(video_language_counts.keys() +
                        completed_language_counts.keys())
    languages = [
        (lc,
         get_language_label(lc),
         video_language_counts.get(lc, 0),
         completed_language_counts.get(lc, 0),
        )
        for lc in all_languages
        if lc != ''
    ]
    languages.sort(key=lambda row: (-row[2], row[1]))

    data = {
        'team': team,
        'languages': languages,
        'breadcrumbs': [
            BreadCrumb(team, 'teams:dashboard', team.slug),
            BreadCrumb(_('Languages')),
        ],
    }
    return team.new_workflow.render_all_languages_page(
        request, team, data,
    )
Ejemplo n.º 4
0
def send_reject_notification(task_pk, sent_back):
    raise NotImplementedError()
    from teams.models import Task
    from videos.models import Action
    from messages.models import Message
    try:
        task = Task.objects.select_related(
            "team_video__video", "team_video", "assignee", "subtitle_version").get(
                pk=task_pk)
    except Task.DoesNotExist:
        return False

    if task.new_review_base_version:
        user = task.new_review_base_version.author
    else:
        user = version.author
    if not user.is_active:
        return False
    version = task.get_subtitle_version()
    subject = ugettext(u"Your subtitles were not accepted")
    task_language = get_language_label(task.language)
    reviewer = task.assignee
    video = task.team_video.video
    subs_url = "%s%s" % (get_url_base(), reverse("videos:translation_history", kwargs={
        'video_id': video.video_id,
        'lang': task.language,
        'lang_id': version.subtitle_language.pk,

    }))
    reviewer_message_url = "%s%s?user=%s" % (
        get_url_base(), reverse("messages:new"), reviewer.username)

    context = {
        "team":task.team,
        "title": version.subtitle_language.get_title(),
        "user":user,
        "task_language": task_language,
        "url_base":get_url_base(),
        "task":task,
        "reviewer":reviewer,
        "note":task.body,
        "sent_back": sent_back,
        "subs_url": subs_url,
        "reviewer_message_url": reviewer_message_url,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-rejected.txt"
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string(template_name,context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = "messages/email/team-task-rejected.html"
    email_res =  send_templated_email(user, subject, template_name, context)
    Action.create_rejected_video_handler(version, reviewer)
    return msg, email_res
Ejemplo n.º 5
0
 def __init__(self, team, subtitle_version):
     self.video = subtitle_version.video
     self.language = get_language_label(subtitle_version.language_code)
     self.date = subtitle_version.created
     self.video_page_url = subtitle_version.video.get_absolute_url(
     ) + '?team={}'.format(team.slug)
     self.language_page_url = subtitle_version.subtitle_language.get_absolute_url(
     ) + '?team={}'.format(team.slug)
Ejemplo n.º 6
0
 def create_for_subtitle_language_changed(self, user, subtitle_language, old_language_code):
     with transaction.atomic():
         change = SubtitleLanguageChange.objects.create(
                     old_language=translation.get_language_label(old_language_code))
         return self.create_for_video('language-changed', subtitle_language.video,
                                      user=user, created=dates.now(),
                                      language_code=subtitle_language.language_code,
                                      related_obj_id=change.id)
Ejemplo n.º 7
0
def language_page(request, team, language_code):
    try:
        language_label = get_language_label(language_code)
    except KeyError:
        raise Http404
    if permissions.can_change_language_managers(team, request.user):
        form = request.POST.get('form')
        if request.method == 'POST' and form == 'add':
            add_manager_form = forms.AddLanguageManagerForm(
                team, language_code, data=request.POST)
            if add_manager_form.is_valid():
                add_manager_form.save()
                member = add_manager_form.cleaned_data['member']
                msg = fmt(_(u'%(user)s added as a manager'), user=member.user)
                messages.success(request, msg)
                return redirect('teams:language-page', team.slug,
                                language_code)
        else:
            add_manager_form = forms.AddLanguageManagerForm(team,
                                                            language_code)

        if request.method == 'POST' and form == 'remove':
            remove_manager_form = forms.RemoveLanguageManagerForm(
                team, language_code, data=request.POST)
            if remove_manager_form.is_valid():
                remove_manager_form.save()
                member = remove_manager_form.cleaned_data['member']
                msg = fmt(_(u'%(user)s removed as a manager'),
                          user=member.user)
                messages.success(request, msg)
                return redirect('teams:language-page', team.slug,
                                language_code)
        else:
            remove_manager_form = forms.RemoveLanguageManagerForm(
                team, language_code)
    else:
        add_manager_form = None
        remove_manager_form = None

    data = {
        'team': team,
        'language_code': language_code,
        'language': language_label,
        'managers': (team.members
                     .filter(languages_managed__code=language_code)),
        'add_manager_form': add_manager_form,
        'remove_manager_form': remove_manager_form,
        'breadcrumbs': [
            BreadCrumb(team, 'teams:dashboard', team.slug),
            BreadCrumb(_('Languages'), 'teams:all-languages-page', team.slug),
            BreadCrumb(language_label),
        ],
    }
    return team.new_workflow.render_language_page(
        request, team, language_code, data,
    )
Ejemplo n.º 8
0
def dashboard(request, team):
    member = team.get_member(request.user)
    main_project = get_main_project(team)
    if not member:
        raise PermissionDenied()

    video_qs = team.videos.all().order_by('-created')
    if main_project:
        video_qs = video_qs.filter(teamvideo__project=main_project)

    newest_members = (team.members.all().order_by('-created').select_related(
        'user')[:NEWEST_MEMBERS_PER_PAGE])

    top_languages = [(get_language_label(lc), count)
                     for lc, count in team.get_completed_language_counts()
                     if count > 0]
    top_languages.sort(key=lambda pair: pair[1], reverse=True)

    member_history = team.new_workflow.fetch_member_history(request.user)
    member_history = member_history[:MAX_DASHBOARD_HISTORY]

    context = {
        'team':
        team,
        'team_nav':
        'dashboard',
        'projects':
        Project.objects.for_team(team),
        'selected_project':
        main_project,
        'top_languages':
        top_languages,
        'newest_members': [m.user for m in newest_members],
        'videos':
        video_qs[:NEWEST_VIDEOS_PER_PAGE],
        'more_video_count':
        max(0,
            video_qs.count() - NEWEST_VIDEOS_PER_PAGE),
        'video_search_form':
        teams_forms.VideoFiltersForm(team),
        'member_profile_url':
        member.get_absolute_url(),
        'member_history':
        member_history,
        'member_history_template':
        team.new_workflow.member_history_template,
        'no_languages_yet': (False if request.user.is_anonymous else len(
            request.user.get_languages()) == 0),
        'dashboard_videos':
        get_dashboard_videos(team, request.user, main_project),
    }

    return render(request, 'future/teams/simple/dashboard.html', context)
Ejemplo n.º 9
0
def to_localized_display(language_code):
    '''
    Translates from a language code to the language name
    in the locale the user is viewing the site. For example:
    en -> Anglaise (if user is viewing with 'fr'
    en -> English
    It uses the django internal machinery to figure out what
    language the request cicle is in, currently set on the
    localurl middleware.
    IF anything is wrong, will log the missing error and
    will return a '?'.
    '''
    try:
        return get_language_label(language_code)
    except KeyError:
        logger.error('Uknown language code to be translated',
                     extra={
                         'language_code': unicode(language_code),
                     })
    return '?'
Ejemplo n.º 10
0
 def __init__(self, video):
     original_languages = []
     other_languages = []
     for lang in video.all_subtitle_languages():
         public_tip = lang.get_tip(public=False)
         if public_tip is None or public_tip.subtitle_count == 0:
             # no versions in this language yet
             continue
         language_name = get_language_label(lang.language_code)
         status = self._calc_status(lang)
         tags = self._calc_tags(lang)
         url = lang.get_absolute_url()
         item = LanguageListItem(language_name, status, tags, url)
         if lang.language_code == video.primary_audio_language_code:
             original_languages.append(item)
         else:
             other_languages.append(item)
     original_languages.sort(key=lambda li: li.name)
     other_languages.sort(key=lambda li: li.name)
     self.items = original_languages + other_languages
Ejemplo n.º 11
0
def team_task_assigned(task_pk):
    from teams.models import Task
    from messages.models import Message
    try:
        task = Task.objects.select_related("team_video__video", "team_video",
                                           "assignee").get(
                                               pk=task_pk,
                                               assignee__isnull=False)
    except Task.DoesNotExist:
        return False
    task_type = Task.TYPE_NAMES[task.type]
    subject = ugettext(u"You have a new task assignment on Amara!")
    user = task.assignee
    if not team_sends_notification(
            task.team, 'block_task_assigned_message') or not user.is_active:
        return False
    task_language = None
    if task.language:
        task_language = get_language_label(task.language)
    context = {
        "team": task.team,
        "user": user,
        "task_type": task_type,
        "task_language": task_language,
        "url_base": get_url_base(),
        "task": task,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-assigned.txt"
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string(template_name, context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = "messages/email/team-task-assigned.html"
    email_res = send_templated_email(user, subject, template_name, context)
    return msg, email_res
Ejemplo n.º 12
0
    def __init__(self, user, video, allow_transcription=True, *args, **kwargs):
        allow_all_languages = kwargs.pop('allow_all_languages', False)
        self.video = video
        self.user = user
        self._sl_created = False

        super(SubtitlesUploadForm, self).__init__(*args, **kwargs)

        if allow_all_languages:
            all_languages = ALL_LANGUAGE_CHOICES
        else:
            all_languages = get_language_choices(with_empty=True)
        self.fields['language_code'].choices = all_languages
        self.fields['primary_audio_language_code'].choices = all_languages

        choices = [(language_code, get_language_label(language_code))
                   for language_code in video.languages_with_versions()]
        if allow_transcription:
            choices.append(('', 'None (Direct from Video)'))

        self.fields['from_language_code'].choices = choices
Ejemplo n.º 13
0
 def get_language_names(self):
     """Get a list of language names that the user speaks."""
     return [
         translation.get_language_label(lc) for lc in self.get_languages()
     ]
Ejemplo n.º 14
0
def compute_statistics(team, stats_type):
    """computes a bunch of statistics for the team, either at
    the video or member levels.
    """
    from views import TableCell
    summary = ''
    graph = ''
    graph_recent = ''
    summary_recent = ''
    graph_additional = ''
    graph_additional_recent = ''
    summary_additional = ''
    summary_additional_recent = ''
    summary_table = ''
    if stats_type == 'videosstats':
        (complete_languages, incomplete_languages) = team.get_team_languages()
        languages = complete_languages + incomplete_languages
        unique_languages = set(languages)
        total = 0
        numbers = []
        y_title = "Number of edited subtitles"
        for l in unique_languages:
            count_complete = complete_languages.count(l)
            count_incomplete = incomplete_languages.count(l)
            numbers.append(
                (get_language_label(l), count_complete + count_incomplete,
                 "Published: %s, total edits:" % count_complete))
            total += count_complete + count_incomplete
        summary = 'Top languages (all time)'
        title = ""
        graph = plot(numbers,
                     title=title,
                     graph_type='HorizontalBar',
                     labels=True,
                     max_entries=20,
                     y_title=y_title)

        (complete_languages_recent, incomplete_languages_recent,
         new_languages) = team.get_team_languages(since=30)
        languages_recent = complete_languages_recent + incomplete_languages_recent
        unique_languages_recent = set(languages_recent)
        summary_recent = "Top languages (past 30 days)"
        numbers_recent = []
        total_recent = 0
        for l in unique_languages_recent:
            count_complete_recent = complete_languages_recent.count(l)
            count_incomplete_recent = incomplete_languages_recent.count(l)
            numbers_recent.append(
                (get_language_label(l),
                 count_complete_recent + count_incomplete_recent,
                 "Published: %s, total edits:" % count_complete_recent))
            total_recent += count_complete_recent + count_incomplete_recent
        title_recent = ""
        graph_recent = plot(numbers_recent,
                            title=title_recent,
                            graph_type='HorizontalBar',
                            labels=True,
                            max_entries=20,
                            y_title=y_title)

        summary_table = []
        summary_table.append([
            TableCell("", header=True),
            TableCell("all time", header=True),
            TableCell("past 30 days", header=True)
        ])
        summary_table.append([
            TableCell("videos added", header=True),
            TableCell(str(team.videos_count)),
            TableCell(str(team.videos_count_since(30)))
        ])
        summary_table.append([
            TableCell("languages edited", header=True),
            TableCell(str(len(unique_languages))),
            TableCell(str(len(unique_languages_recent)))
        ])
        summary_table.append([
            TableCell("subtitles edited", header=True),
            TableCell(str(total)),
            TableCell(str(total_recent))
        ])

    elif stats_type == 'teamstats':
        languages = list(team.languages())
        unique_languages = set(languages)
        summary = u'Members by language (all time)'
        numbers = []
        for l in unique_languages:
            numbers.append((get_language_label(l), languages.count(l),
                            get_language_label(l)))
        title = ''
        graph = plot(numbers,
                     graph_type='HorizontalBar',
                     title=title,
                     max_entries=25,
                     labels=True,
                     total_label="Members: ")
        languages_recent = list(team.languages(members_joined_since=30))
        unique_languages_recent = set(languages_recent)
        summary_recent = u'New members by language (past 30 days)'
        numbers_recent = []
        for l in unique_languages_recent:
            numbers_recent.append(
                (get_language_label(l), languages_recent.count(l),
                 get_language_label(l), "%s://%s%s" %
                 (DEFAULT_PROTOCOL, Site.objects.get_current().domain,
                  reverse('teams:members', args=[], kwargs={'slug': team.slug})
                  + "?sort=-joined&lang=%s" % l)))
        title_recent = ''
        graph_recent = plot(numbers_recent,
                            graph_type='HorizontalBar',
                            title=title_recent,
                            max_entries=25,
                            labels=True,
                            xlinks=True,
                            total_label="Members: ")

        summary_table = []
        summary_table.append([
            TableCell("", header=True),
            TableCell("all time", header=True),
            TableCell("past 30 days", header=True)
        ])
        summary_table.append([
            TableCell("members joined", header=True),
            TableCell(str(team.members_count)),
            TableCell(str(team.members_count_since(30)))
        ])
        summary_table.append([
            TableCell("member languages", header=True),
            TableCell(str(len(unique_languages))),
            TableCell(str(len(unique_languages_recent)))
        ])

        active_users = {}
        for sv in team.active_users():
            if sv[0] in active_users:
                active_users[sv[0]].add(sv[1])
            else:
                active_users[sv[0]] = set([sv[1]])

        most_active_users = active_users.items()
        most_active_users.sort(reverse=True, key=lambda x: len(x[1]))
        if len(most_active_users) > 20:
            most_active_users = most_active_users[:20]

        active_users_recent = {}
        for sv in team.active_users(since=30):
            if sv[0] in active_users_recent:
                active_users_recent[sv[0]].add(sv[1])
            else:
                active_users_recent[sv[0]] = set([sv[1]])

        most_active_users_recent = active_users_recent.items()
        most_active_users_recent.sort(reverse=True, key=lambda x: len(x[1]))
        if len(most_active_users_recent) > 20:
            most_active_users_recent = most_active_users_recent[:20]

        def displayable_user(user, users_details):
            user_details = users_details[user[0]]
            return ("%s %s (%s)" %
                    (user_details[1], user_details[2], user_details[3]),
                    len(user[1]), "%s %s (%s)" %
                    (user_details[1], user_details[2], user_details[3]),
                    "%s://%s%s" %
                    (DEFAULT_PROTOCOL, Site.objects.get_current().domain,
                     reverse("profiles:profile",
                             kwargs={'user_id': str(user[0])})))

        user_details = User.displayable_users(
            map(lambda x: int(x[0]), most_active_users))
        user_details_dict = {}
        for user in user_details:
            user_details_dict[user[0]] = user

        most_active_users = map(
            lambda x: displayable_user(x, user_details_dict),
            most_active_users)

        summary_additional = u'Top contributors (all time)'
        graph_additional = plot(most_active_users,
                                graph_type='HorizontalBar',
                                title='',
                                labels=True,
                                xlinks=True,
                                total_label="Contributions: ")

        user_details_recent = User.displayable_users(
            map(lambda x: int(x[0]), most_active_users_recent))
        user_details_dict_recent = {}
        for user in user_details_recent:
            user_details_dict_recent[user[0]] = user

        most_active_users_recent = map(
            lambda x: displayable_user(x, user_details_dict_recent),
            most_active_users_recent)

        summary_additional_recent = u'Top contributors (past 30 days)'
        graph_additional_recent = plot(most_active_users_recent,
                                       graph_type='HorizontalBar',
                                       title='',
                                       labels=True,
                                       xlinks=True,
                                       total_label="Contributions: ")

    statistics = {
        'computed_on':
        datetime.utcnow().replace(
            tzinfo=utc).strftime("%A %d. %B %Y %H:%M:%S UTC"),
        'summary':
        summary,
        'summary_recent':
        summary_recent,
        'activity_tab':
        stats_type,
        'graph':
        graph,
        'graph_recent':
        graph_recent,
        'graph_additional':
        graph_additional,
        'graph_additional_recent':
        graph_additional_recent,
        'summary_additional':
        summary_additional,
        'summary_additional_recent':
        summary_additional_recent,
        'summary_table':
        summary_table,
    }
    return statistics
Ejemplo n.º 15
0
def _reviewed_notification(task_pk, status):
    from teams.models import Task
    from videos.models import Action
    from messages.models import Message
    try:
        task = Task.objects.select_related("team_video__video", "team_video",
                                           "assignee").get(pk=task_pk)
    except Task.DoesNotExist:
        return False

    subject = ugettext(u"Your subtitles have been reviewed")
    if status == REVIEWED_AND_PUBLISHED:
        subject += ugettext(" and published")

    if task.review_base_version:
        user = task.review_base_version.user
    else:
        user = task.subtitle_version.user

    task_language = get_language_label(task.language)
    reviewer = task.assignee
    video = task.team_video.video
    subs_url = "%s%s" % (get_url_base(),
                         reverse("videos:translation_history",
                                 kwargs={
                                     'video_id': video.video_id,
                                     'lang': task.language,
                                     'lang_id':
                                     task.subtitle_version.language.pk,
                                 }))
    reviewer_message_url = "%s%s?user=%s" % (
        get_url_base(), reverse("messages:new"), reviewer.username)

    reviewer_profile_url = "%s%s" % (get_url_base(),
                                     reverse("profiles:profile",
                                             kwargs={'user_id': reviewer.id}))
    perform_task_url = "%s%s" % (get_url_base(),
                                 reverse("teams:perform_task",
                                         kwargs={
                                             'slug': task.team.slug,
                                             'task_pk': task_pk
                                         }))

    context = {
        "team": task.team,
        "title": task.subtitle_version.language.get_title(),
        "user": user,
        "task_language": task_language,
        "url_base": get_url_base(),
        "task": task,
        "reviewer": reviewer,
        "note": task.body,
        "reviewed_and_pending_approval":
        status == REVIEWED_AND_PENDING_APPROVAL,
        "sent_back": status == REVIEWED_AND_SENT_BACK,
        "reviewed_and_published": status == REVIEWED_AND_PUBLISHED,
        "subs_url": subs_url,
        "reviewer_message_url": reviewer_message_url,
        "reviewer_profile_url": reviewer_profile_url,
        "perform_task_url": perform_task_url,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-reviewed.txt"
        msg = Message()
        msg.subject = subject
        msg.content = render_to_string(template_name, context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = "messages/email/team-task-reviewed.html"
    Meter('templated-emails-sent-by-type.teams.task-reviewed').inc()
    email_res = send_templated_email(user, subject, template_name, context)

    if status == REVIEWED_AND_SENT_BACK:
        if task.type == Task.TYPE_IDS['Review']:
            Action.create_declined_video_handler(task.subtitle_version,
                                                 reviewer)
        else:
            Action.create_rejected_video_handler(task.subtitle_version,
                                                 reviewer)
    elif status == REVIEWED_AND_PUBLISHED:
        Action.create_approved_video_handler(task.subtitle_version, reviewer)
    elif status == REVIEWED_AND_PENDING_APPROVAL:
        Action.create_accepted_video_handler(task.subtitle_version, reviewer)

    return msg, email_res
Ejemplo n.º 16
0
def approved_notification(task_pk, published=False):
    """
    On approval, it can be sent back (published=False) or
    approved and published
    """
    from teams.models import Task
    from activity.models import ActivityRecord
    from messages.models import Message
    from teams.models import TeamNotificationSetting
    try:
        task = Task.objects.select_related("team_video__video", "team_video",
                                           "assignee",
                                           "subtitle_version").get(pk=task_pk)
        if not team_sends_notification(task.team, 'block_approved_message'):
            return False
    except Task.DoesNotExist:
        return False
    # some tasks are being created without subtitles version, see
    # https://unisubs.sifterapp.com/projects/12298/issues/552092/comments
    users_to_notify = set()
    version = task.get_subtitle_version()
    if task.new_review_base_version:
        user = task.new_review_base_version.author
    else:
        user = version.author
    if user.is_active:
        users_to_notify.add(user)

    if published:
        subject = ugettext(u"Your subtitles have been approved and published!")
        template_txt = "messages/team-task-approved-published.txt"
        template_html = "messages/email/team-task-approved-published.html"
        # Not sure whether it is the right place to send notification
        # but should work around the approval when there is no new sub version
        TeamNotificationSetting.objects.notify_team(
            task.team.pk,
            TeamNotificationSetting.EVENT_SUBTITLE_APPROVED,
            video_id=version.video.video_id,
            language_pk=version.subtitle_language.pk,
            version_pk=version.pk)
        subtitler = task.get_subtitler()
        if subtitler is not None and \
           subtitler.is_active:
            users_to_notify.add(subtitler)

    else:
        template_txt = "messages/team-task-approved-sentback.txt"
        template_html = "messages/email/team-task-approved-sentback.html"
        subject = ugettext(
            u"Your subtitles have been returned for further editing")

    reviewer = task.assignee
    ActivityRecord.objects.create_for_version_approved(version, reviewer)
    if len(users_to_notify) > 0:
        task_language = get_language_label(task.language)
        video = task.team_video.video
        subs_url = "%s%s" % (get_url_base(),
                             reverse("videos:translation_history",
                                     kwargs={
                                         'video_id': video.video_id,
                                         'lang': task.language,
                                         'lang_id':
                                         version.subtitle_language.pk,
                                     }))
        reviewer_message_url = "%s%s?user=%s" % (
            get_url_base(), reverse("messages:new"), reviewer.username)

        context = {
            "team": task.team,
            "title": version.subtitle_language.get_title(),
            "task_language": task_language,
            "url_base": get_url_base(),
            "task": task,
            "reviewer": reviewer,
            "note": task.body,
            "subs_url": subs_url,
            "reviewer_message_url": reviewer_message_url,
        }
        for user in users_to_notify:
            context['user'] = user
            msg = None
            if user.notify_by_message:
                msg = Message()
                msg.message_type = 'S'
                msg.subject = subject
                msg.content = render_to_string(template_txt, context)
                msg.user = user
                msg.object = task.team
                msg.save()

            email_res = send_templated_email(user, subject, template_html,
                                             context)
Ejemplo n.º 17
0
def _reviewed_notification(task_pk, status):
    from teams.models import Task
    from activity.models import ActivityRecord
    from messages.models import Message
    try:
        task = Task.objects.select_related("team_video__video", "team_video",
                                           "assignee").get(pk=task_pk)
    except Task.DoesNotExist:
        return False

    notification_setting_name = {
        REVIEWED_AND_PUBLISHED: 'block_reviewed_and_published_message',
        REVIEWED_AND_PENDING_APPROVAL:
        'block_reviewed_and_pending_approval_message',
        REVIEWED_AND_SENT_BACK: 'block_reviewed_and_sent_back_message',
    }[status]

    version = task.get_subtitle_version()

    if task.new_review_base_version:
        user = task.new_review_base_version.author
    else:
        user = version.author
    if not team_sends_notification(
            task.team, notification_setting_name) or not user.is_active:
        return False

    subject = ugettext(u"Your subtitles have been reviewed")
    if status == REVIEWED_AND_PUBLISHED:
        subject += ugettext(" and published")
    if status == REVIEWED_AND_SENT_BACK:
        subject = ugettext(u"Needed: additional changes on your subtitles!")

    task_language = get_language_label(task.language)
    reviewer = task.assignee
    video = task.team_video.video
    subs_url = "%s%s" % (get_url_base(),
                         reverse("videos:translation_history",
                                 kwargs={
                                     'video_id': video.video_id,
                                     'lang': task.language,
                                     'lang_id': version.subtitle_language.pk,
                                 }))
    reviewer_message_url = "%s%s?user=%s" % (
        get_url_base(), reverse("messages:new"), reviewer.username)

    reviewer_profile_url = "%s%s" % (get_url_base(),
                                     reverse("profiles:profile",
                                             kwargs={'user_id': reviewer.id}))
    perform_task_url = "%s%s" % (get_url_base(),
                                 reverse("teams:perform_task",
                                         kwargs={
                                             'slug': task.team.slug,
                                             'task_pk': task_pk
                                         }))

    context = {
        "team": task.team,
        "title": version.subtitle_language.get_title(),
        "user": user,
        "task_language": task_language,
        "url_base": get_url_base(),
        "task": task,
        "reviewer": reviewer,
        "note": task.body,
        "reviewed_and_pending_approval":
        status == REVIEWED_AND_PENDING_APPROVAL,
        "sent_back": status == REVIEWED_AND_SENT_BACK,
        "reviewed_and_published": status == REVIEWED_AND_PUBLISHED,
        "subs_url": subs_url,
        "reviewer_message_url": reviewer_message_url,
        "reviewer_profile_url": reviewer_profile_url,
        "perform_task_url": perform_task_url,
    }
    msg = None
    if user.notify_by_message:
        template_name = "messages/team-task-reviewed.txt"
        msg = Message()
        msg.message_type = 'S'
        msg.subject = subject
        msg.content = render_to_string(template_name, context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = "messages/email/team-task-reviewed.html"
    email_res = send_templated_email(user, subject, template_name, context)

    if status == REVIEWED_AND_SENT_BACK:
        if task.type == Task.TYPE_IDS['Review']:
            ActivityRecord.objects.create_for_version_declined(
                version, reviewer)
        else:
            ActivityRecord.objects.create_for_version_rejected(
                version, reviewer)
    elif status == REVIEWED_AND_PUBLISHED:
        ActivityRecord.objects.create_for_version_approved(version, reviewer)
    elif status == REVIEWED_AND_PENDING_APPROVAL:
        ActivityRecord.objects.create_for_version_accepted(version, reviewer)

    return msg, email_res
Ejemplo n.º 18
0
def current_language_name(context):
    return get_language_label(context['LANGUAGE_CODE'])
Ejemplo n.º 19
0
 def get_language_codes_and_names(self):
     """Get a list of language codes/names that the user speaks."""
     return [(lc, translation.get_language_label(lc))
             for lc in self.get_languages()]
Ejemplo n.º 20
0
def approved_notification(task_pk, published=False):
    """
    On approval, it can be sent back (published=False) or
    approved and published
    """
    from teams.models import Task
    from videos.models import Action
    from messages.models import Message
    try:
        task = Task.objects.select_related(
            "team_video__video", "team_video", "assignee", "subtitle_version").get(
                pk=task_pk)
        if not _team_sends_notification(task.team, 'block_approved_message'):
            return False
    except Task.DoesNotExist:
        return False
    # some tasks are being created without subtitles version, see
    # https://unisubs.sifterapp.com/projects/12298/issues/552092/comments

    if published:
        subject = ugettext(u"Your subtitles have been approved and published!")
        template_txt = "messages/team-task-approved-published.txt"
        template_html ="messages/email/team-task-approved-published.html"
    else:
        template_txt = "messages/team-task-approved-sentback.txt"
        template_html ="messages/email/team-task-approved-sentback.html"
        subject = ugettext(u"Your subtitles have been returned for further editing")
    version = task.get_subtitle_version()
    if task.new_review_base_version:
        user = task.new_review_base_version.author
    else:
        user = version.author
    task_language = get_language_label(task.language)
    reviewer = task.assignee
    video = task.team_video.video
    subs_url = "%s%s" % (get_url_base(), reverse("videos:translation_history", kwargs={
        'video_id': video.video_id,
        'lang': task.language,
        'lang_id': version.subtitle_language.pk,

    }))
    reviewer_message_url = "%s%s?user=%s" % (
        get_url_base(), reverse("messages:new"), reviewer.username)

    context = {
        "team":task.team,
        "title": version.subtitle_language.get_title(),
        "user":user,
        "task_language": task_language,
        "url_base":get_url_base(),
        "task":task,
        "reviewer":reviewer,
        "note":task.body,
        "subs_url": subs_url,
        "reviewer_message_url": reviewer_message_url,
    }
    msg = None
    if user.notify_by_message:
        template_name = template_txt
        msg = Message()
        msg.subject = subject
        msg.content = render_to_string(template_name,context)
        msg.user = user
        msg.object = task.team
        msg.save()

    template_name = template_html
    Meter('templated-emails-sent-by-type.teams.approval-result').inc()
    email_res =  send_templated_email(user, subject, template_name, context)
    Action.create_approved_video_handler(version, reviewer)
    return msg, email_res
Ejemplo n.º 21
0
    def clean(self):
        if self.video.is_writelocked:
            raise forms.ValidationError(_(
                u'Somebody is subtitling this video right now. Try later.'))

        from_language_code = self.cleaned_data.get('from_language_code')
        language_code = self.cleaned_data['language_code']
        subtitle_language = self.video.subtitle_language(language_code)

        if from_language_code:
            # If this is a translation, we'll retrieve the source
            # language/version here so we can use it later.
            self.from_sl = self.video.subtitle_language(from_language_code)
            if self.from_sl is None:
                raise forms.ValidationError(
                    _(u'Invalid from language: %(language)s') % {
                        'language': get_language_label(from_language_code),
                    })
            self.from_sv = self.from_sl.get_tip(public=True)
            if self.from_sv is None:
                raise forms.ValidationError(
                    _(u'%(language)s has no public versions') % {
                        'language': get_language_label(from_language_code),
                    })
        else:
            self.from_sl = None
            self.from_sv = None

        # If this SubtitleLanguage already exists, we need to verify a few
        # things about it before we let the user upload a set of subtitles to
        # it.
        if subtitle_language:
            # Verify that it's not writelocked.
            self._verify_not_writelocked(subtitle_language)

            # Make sure there are no translation conflicts.  Basically, fail if
            # any of the following are true:
            #
            # 1. The user specified that this was a translation, but the
            #    existing SubtitleLanguage is *not* a translation.
            # 2. The user specified that this was a translation, and the
            #    existing language is a translation, but of a different language
            #    than the user gave.
            self._verify_no_translation_conflict(subtitle_language,
                                                 from_language_code)

        # If we are translating from another version, check that the number of
        # subtitles matches the source.
        self._verify_translation_subtitle_counts(from_language_code)

        # Videos that are part of a team have a few more restrictions.
        team_video = self.video.get_team_video()
        if team_video:
            # You can only upload to a language with a subtitle/translate task
            # open if that task is assigned to you, or if it's unassigned and
            # you can assign yourself.
            self._verify_no_blocking_subtitle_translate_tasks(team_video,
                                                              language_code)

            # You cannot upload at all to a language that has a review or
            # approve task open.
            self._verify_no_blocking_review_approve_tasks(team_video,
                                                          language_code)

            # Finally ensure that the teams "who can translate/transcribe"
            # settings don't prevent this upload.
            self._verify_team_policies(team_video, language_code,
                                       from_language_code)

        return self.cleaned_data
Ejemplo n.º 22
0
 def get_language_code_display(self):
     if self.language_code:
         return translation.get_language_label(self.language_code)
     else:
         return ''