Example #1
0
    def do_handle(self, *args, **options):

        self.stdout.write('Started.\n')
        logger.info("Start")

        meta_diff = datetime.datetime.now() - datetime.timedelta(days=getattr(settings, 'MESSAGE_DAYS_AGE',1))
        
        t_start = time.time() 
        
        mailing = []
        
        for user in User.objects.filter(pm_inbox__unread=True, pm_inbox__notified__isnull=True, pm_inbox__message__created__lt=meta_diff).distinct():
            messages = user.pm_inbox.filter(unread=True, notified__isnull=True, message__created__lt=meta_diff)
            count = messages.count()
            logger.debug("There are %s messages for %s" % (count, user))
            set_user_language(user)
            subject = ungettext('You have %(count)d unread message', 'You have %(count)d unread messages', count) % {
                'count': count,
            }
            message = render_to_string('djangopm/mail/unread_messages.mail', {'message_count': count,
                                                                        'user': user,
                                                                        'messages':  messages.all()})
            mailing.append((subject, message, None, [ user.email ]))
            messages.update(notified=datetime.datetime.now())
       
        if len(mailing)>0:
            logger.debug("Notify %d users" % len(mailing))
            send_mass_mail(mailing, True)
        logger.info("End")
        
        self.stdout.write('Completed in %d seconds. Notified %s.\n' % (int(time.time() - t_start), len(mailing)))
        
        return "Notify %d users" % len(mailing)
Example #2
0
def join_accept(request, id, reject=False):
    logger.debug("Team petition management %s [%s]" % (id, str(reject)))
    joinreq = get_object_or_404(JoinRequest, id=id)
    team = joinreq.team

    if not team.can_manage(request.user):
        raise Http403

    set_user_language(joinreq.user)

    subject = getattr(settings, "EMAIL_SUBJECT_PREFIX", "") + _("Request to join the %(team)s team") % {
        "team": team.language.name
    }

    if reject:
        message = render_to_string("teams/join_reject.mail", {"team": team.language.name, "project": team.project.name})
    else:
        message = render_to_string("teams/join_accept.mail", {"team": team.language.name, "project": team.project.name})
        team.members.add(joinreq.user)

    set_user_language(request.user)

    em = EmailMessage(subject=subject, body=message, to=[joinreq.user.email])
    try:
        em.send()
    except Exception, e:
        logger.error(e)
Example #3
0
def toggle_mark(request, slug):
    res = {}
    if request.method == "POST":
        try:
            file = POFile.objects.get(slug=slug)
        except:
            return XMLResponse({'message': _('File not found.')})
        
        if not file.release.enabled or not file.release.project.enabled:
            return XMLResponse({'message': _('Sorry, you are not supposed to change anything on a disabled component.')})

        team = Team.objects.get(project=file.component.project, language=file.language)
        if not team.is_member(request.user):
            return XMLResponse({'message': _('You are not a member of this team.')})
            
        res['id'] = file.slug
        if file.assigns.all():
            assign = file.assigns.get()
        else:
            assign = False
        if (team.can_manage(request.user) or
            (assign and (assign.translate==request.user or assign.review==request.user))):
            # to avoid mark collision
            current_mark = request.POST.get('mark')
            if current_mark != None and current_mark != '' and int(current_mark) == file.status:
                st = None
                if file.status == 0:
                    file.status = 1
                    st = 'ST_TRAN'
                elif file.status == 1:
                    file.status = 2
                    st = 'ST_REV'
                elif file.status == 2:
                    file.status = 3
                    st = 'ST_COMPL'
                if st:
                    file.save()
                    file.log.create(action=LOG_ACTION[st],user=request.user)
                    
                    if file.status == 1:
                        if assign and assign.review:
                            set_user_language(assign.review)
                            send_pm(assign.review, subject=_("File %s ready for review.") % smart_unicode(file))                    
        else:
            return XMLResponse({'message': _('You are not authorized to perform this action.')})

        page = render_to_string('files/file_list_row.html',
                                {'pofile': file, 'team': team},
                                context_instance = RequestContext(request))
        res['content_HTML'] = page
        return XMLResponse(res)
    else:
        raise Http403
Example #4
0
 def process_notifications(self):
     try:
         mlist = []
         prefix = getattr(settings, 'EMAIL_SUBJECT_PREFIX','')
         for id in self.notifications.keys():
             user = User.objects.get(pk=id)
             files = "\n".join(["%s" % smart_unicode(f) for f in self.notifications.get(id)])
             set_user_language(user)
             subject = prefix + self.subject
             message = render_to_string(self.template, {'files': files})
             mlist.append((subject, message, None, [user.email]))
         send_mass_mail(mlist, True)
     except Exception, e:
         if self.logger: self.logger.error(e)
Example #5
0
 def __process_notifications(self):
     logger.debug("Init")
     mlist = []
     try:
         for id in self.notifications.keys():
             user = User.objects.get(pk=id)
             with UserLanguage(user) as user_lang:
                 subject = getattr(settings, 'EMAIL_SUBJECT_PREFIX','') + _("Files submitted")
                 message = render_to_string('updater/confirmcommit.mail', {'files': self.notifications.get(id)})
                 mlist.append((subject, message, None, [user.email]))
         send_mass_mail(mlist, True)
         set_user_language(self.current)
         self.notifier.process_notifications()
     except Exception, e:
         logger.error(str(e))
         logger.exception('__process_notifications')
Example #6
0
    def do_handle(self, *args, **options):

        self.stdout.write('Started.\n')
        logger.info("Start")

        meta_diff = datetime.datetime.now() - datetime.timedelta(days=getattr(settings, 'MESSAGE_DAYS_AGE',2))
        prefix = getattr(settings,'EMAIL_SUBJECT_PREFIX','')
        NOW = datetime.datetime.now()
        
        t_start = time.time() 
        
        mailing = []
        
        for user in User.objects.all():
            if user.message_set.all():
                try:
                    user.message_set.filter(status__created__lt=meta_diff).delete()
                except:
                    pass
                try:
                    mlist = user.message_set.filter(status__notified__isnull=True)
                    if mlist:
                        logger.debug("There are messages for %s" % user)
                        for m in user.message_set.all():
                            if m.status.all():
                                s = m.status.get()
                            else:
                                # to avoid two sql calls
                                s = UserMessages(message=m)
                            s.notified=NOW
                            s.save()
                        count = user.message_set.all().count()
                        set_user_language(user)
                        subject = ungettext('You have %(count)d unread message', 'You have %(count)d unread messages', count) % {
                            'count': count,
                        }            
                        message = render_to_string('updater/unread_messages.mail', {'message_count': count,
                                                                                    'user': user,
                                                                                    'messages': mlist})
                        mailing.append((subject, message, None, [ user.email ]))
                    else:
                        logger.debug("No messages for %s" % user)
                except FieldDoesNotExist, e:
                    # we should repair this for future lookups
                    logger.debug("Create message status")
                    for m in user.message_set.filter(status__isnull=True):
                        m.status.create() 
Example #7
0
    def do_handle(self, *args, **options):

        self.stdout.write('Started.\n')
        logger.info("Start")
        t_start = time.time() 
        rsp = None
        perm = Permission.objects.get(codename='can_commit')
        prefix = getattr(settings,'EMAIL_SUBJECT_PREFIX','')    
        
        for team in Team.objects.all():
            logger.debug(team)
            submits = POFileSubmit.objects.by_project_and_language(team.project,
                                                                   team.language)
            logger.debug("Count %d" % submits.count())
            if submits.count()>0:
                users = team.coordinators.all()
                ulist = User.objects.filter(id__in=[u.id for u in team.members.all()],
                                            user_permissions=perm,
                                            is_superuser=False)
                # I dont want users see other addresses
                sendm = []
                userlist = list(users)
                userlist.extend(list(ulist))
                for u in userlist:
                    set_user_language(u)
                    subject = prefix + _("Submission queue status report for %(project)s - %(team)s" % 
                               {'project': team.project.name, 'team': team.language.name})
                    message = render_to_string('updater/queuestatus.mail', {'files': submits})
                    sendm.append((subject, message, None, [ u.email ]))
                    
                logger.debug("Notify %d users" % len(sendm))
                rsp = "Notify %d users" % len(sendm)
                send_mass_mail(sendm, True)        

        logger.info("End")
        self.stdout.write('Completed in %d seconds.\n' % int(time.time() - t_start))
        
        return rsp
Example #8
0
 def check_notification(self, pofile_new, pofile_old, add_coord = True):
     try:
         new_sum = pofile_new.fuzzy + pofile_new.untrans
         actual_sum = pofile_old.fuzzy + pofile_old.untrans
         
         if new_sum > actual_sum:
             self.add_notification(pofile_new, add_coord)
             pofile_new.log.create(user=self.user, action=LOG_ACTION['ACT_UPDATE'])
             
         if new_sum > 0 and pofile_new.status > 0:
             pofile_new.status = 0
             pofile_new.log.create(user=self.user, action=LOG_ACTION['ST_UNREV'])
                 
         elif new_sum == 0 and pofile_new.status < 2:
             # lets try to guess the status
             if pofile_new.assigns.all():
                 assign = pofile_new.assigns.get()
                 if pofile_new.status == 0:
                     if assign.translate:
                         if POFileLog.objects.filter(
                                                     user=assign.translate,
                                                     pofile=pofile_new,action=LOG_ACTION['ACT_UPLOAD']).count()>0:
                             pofile_new.status = 1
                             pofile_new.log.create(user=self.user, action=LOG_ACTION['ST_TRAN'])
                             if assign.review:
                                 set_user_language(assign.review)
                                 assign.review.message_set.create(message=_("File %s ready for review.") % smart_unicode(pofile_new))
                 elif pofile_new.status == 1:
                     if assign.review:
                         if POFileLog.objects.filter(
                                                     user=assign.review,
                                                     pofile=pofile_new,action=LOG_ACTION['ACT_UPLOAD']).count()>0:
                             pofile_new.status = 2
                             pofile_new.log.create(user=self.user, action=LOG_ACTION['ST_REV'])
     except Exception, e:
         if self.logger: self.logger.error(e)
Example #9
0
def join_request(request, teamid):
    logger.debug("Team join request %s" % (teamid))
    use_captcha = getattr(settings, "JOIN_USE_CAPTCHA", True)

    if use_captcha:
        from recaptcha.client import captcha

    captcha_error = ""
    captcha_valid = True

    team = get_object_or_404(Team, id=teamid)

    back = HttpResponseRedirect(
        reverse("team_detail", kwargs={"project": team.project.slug, "lang": team.language.code})
    )

    if team.is_member(request.user):
        messages.warning(request, _("You are already a member of this team."))
        return back
    elif request.user in [r.user for r in team.join_requests.all()]:
        messages.warning(request, _("You have already sent a join request."))
        return back

    if request.method == "POST":
        if use_captcha:
            captcha_response = captcha.submit(
                request.POST.get("recaptcha_challenge_field", None),
                request.POST.get("recaptcha_response_field", None),
                settings.RECAPTCHA_PRIVATE_KEY,
                request.META.get("REMOTE_ADDR", None),
            )
            captcha_valid = captcha_response.is_valid

        if not captcha_valid:
            captcha_error = "&error=%s" % captcha_response.error_code
        else:
            team.join_requests.create(user=request.user)

            if request.user.get_full_name():
                username = "******" % (request.user.get_full_name(), request.user.username)
            else:
                username = request.user.username
            sendm = []
            sender = request.user.email
            for coord in team.coordinators.all():
                set_user_language(coord)
                subject = getattr(settings, "EMAIL_SUBJECT_PREFIX", "") + _("Request to join the team")
                message = render_to_string(
                    "teams/join.mail",
                    {"username": username, "team": team.language.name, "project": team.project.name, "teamid": teamid},
                )
                sendm.append(
                    EmailMessage(subject=subject, body=message, to=[coord.email], headers={"Reply-To": sender})
                )
            set_user_language(request.user)

            try:
                send_mass_mail_em(sendm)
            except Exception, e:
                logger.error(e)
            messages.success(request, _("Your request to join this team has been received."))
            return HttpResponseRedirect(
                reverse("team_detail", kwargs={"project": team.project.slug, "lang": team.language.code})
            )
Example #10
0
                        elif str(e).count('callback_ssl_server_trust_prompt')>0:
                            self.__unlock_submits(self.files)
                            logger.error("Fail trust SSL")
                            raise AuthException(_('SSL Validation error. If the problem persist contact the repository administrator.'))
                        else:
                            self.__unlock_submits(component)
                            exceps.append(str(e))
                        
            if len(exceps)>0 or len(failedSubmits) > 0:
                #raise Exception("\n".join(exceps))
                raise SubmitException("\n".join(exceps), failedSubmits)
                        
        finally:
            #thread.start_new_thread(self.__process_notifications, ())
            self.__process_notifications()
            set_user_language(self.user)

        logger.debug("end")

def get_repository_location(project, release=None, component=None, lang=None):
    return os.path.join(getattr(settings,'REPOSITORY_LOCATION'), get_repository_path(project, release, component, lang))

def get_repository_path(project, release=None, component=None, lang=None):
    parts = []
    parts.append(project.slug)
    if release is not None: parts.append(release.slug)
    if component is not None: parts.append(component.slug)
    if lang is not None: parts.append(lang.code)
    return os.path.join(*parts)
    #return os.path.join(project.slug, release.slug, component.slug, lang.code)