Пример #1
0
def trigger_action_add(request, trig_id):
    trigobj = get_object(Trigger, request.user, trig_id)
    form = TriggerForm(request.user, instance=trigobj)
    action_form = TriggerActionForm(request.user)
    for field in form.visible_fields():
        field.field.widget.attrs['disabled'] = 'disabled'
    if request.method == "POST":
        action_form = TriggerActionForm(request.user, request.POST)
        if action_form.is_valid():
            action_obj = action_form.save()
            action_obj.trigger = trigobj
            action_obj.save()
            messages.add_message(request, messages.SUCCESS, _(u'添加触发器成功'))
            next = request.POST.get('next', '')
            if next == 'add':
                return HttpResponseRedirect(
                    reverse('trigger_action_add', args=(trigobj.id, )))
            return HttpResponseRedirect(reverse("trigger"))
    return render(request,
                  'trigger/trigger_add.html',
                  context={
                      "form": form,
                      "action_form": action_form,
                      "trig_title": _(u'添加触发动作'),
                  })
Пример #2
0
def start(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    original = get_original(obj, request.user.id)
    return render(request, 'mosaico/start.html', context={
        "original": original,
        "template_id": template_id,
    })
Пример #3
0
def ml_unsubscribe_list(request, list_id):
    obj = model_addresses.get_address_obj(request, list_id)
    user_id = obj.customer_id
    subject = model_addresses.get_subject(request, list_id, obj)
    cr = connections['mm-pool'].cursor()
    address_sqls.checkTable(cr, user_id)
    if request.method == "POST":
        obj2 = get_object(MailList, request.user, list_id)
        tablename = 'ml_unsubscribe_' + str(request.user.id)
        address = request.POST.get('address', '')
        id = request.POST.get('id', False)
        status = int(request.POST.get('status', False))
        if int(status) == -2:  # 删除
            sql = u"DELETE FROM {0} WHERE list_id={1} AND address='{2}'".format(
                tablename, id, address)
            cr.execute(sql)
            redis = get_redis_connection()
            redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE,
                        '{}_{}'.format(request.user.id, list_id))
            messages.add_message(request, messages.SUCCESS, _(u'删除成功'))
        return HttpResponseRedirect("/address/unsubscribe/{}/".format(list_id))
    return render(request,
                  'address/ml_unsubscribe_list.html',
                  context={
                      'subject': subject,
                      'list_id': list_id
                  })
Пример #4
0
def ajax_stat_info(request, task_id):
    obj = get_object(SendTask, request.user, task_id)
    flag = obj.get_track_stat_flag()
    show_stat_rate, show_link_rate = obj.get_rate()
    if obj.track_status == 1:
        if flag:
            info = _(u'''<span class="text-nowrap">打开率:
            <span class="myself-txt-color-red margin-right-5">%(rate)s</span>
            <code><a href="/track/trackstat/?ident=%(send_name)s&mode=1" target="_blank">查看详情</a></code>
            </span>''') % {'rate': show_stat_rate, 'send_name': obj.send_name}
        else:
            info = _(u'暂无数据') % {}
    elif obj.track_status == 2:
        if flag:
            info = _(u'''<span class="text-nowrap">打开率:
            <span class="myself-txt-color-red">%(rate)s</span></span><br>
            <span class="text-nowrap">点击率:
            <span class="myself-txt-color-blue margin-right-5">%(link_rate)s</span>
            <code><a href="/track/trackstat/?ident=%(send_name)s&mode=2" target="_blank">查看详情</a></code>
            </span>''') % {'rate': show_stat_rate, 'link_rate': show_link_rate, 'send_name': obj.send_name}
        else:
            info = _(u'暂无数据') % {}
    else:
        info = _(u'未启用') % {}
    return HttpResponse(json.dumps({'info': info}), content_type="application/json")
Пример #5
0
def template_modify(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    original = get_original(obj, request.user.id)
    if request.method == "POST":
        data = request.POST
        name = data.get('name', '')
        encoding = data.get('encoding', 'base64')
        character = data.get('character', 'utf-8')

        subject_list = data.getlist('subject_list[]', '')
        SendSubject.objects.filter(template_id=template_id).delete()
        subject_obj_list, template_subject = [], ''
        for subject in subject_list:
            if subject:
                template_subject = subject
                subject_obj_list.append(SendSubject(template_id=template_id, subject=subject))
        SendSubject.objects.bulk_create(subject_obj_list)

        obj.name = name
        obj.subject = template_subject
        obj.encoding = encoding
        obj.character = character
        obj.issync = True
        # obj.result = None
        obj.save()
        return HttpResponseRedirect(reverse("mosaico_start", args=(template_id,)))

    subject_objs = SendSubject.objects.filter(template_id=template_id)
    if request.user.lang_code == 'en-us':
        subject_vals = [
            ('{FULLNAME}', u'Recipient Name'),
            ('{RECIPIENTS}',  u'Recipient'),
            ('{DATE}',  u'Current date'),
            ('{RANDOM_NUMBER}',  u'Random 10 digits'),
            ('{SEX}', u'Gender'),
            ('{BIRTHDAY}', u'Birthday'),
            ('{PHONE}', u'Phone'),
            ('{AREA}',    u'Area'),
        ]
    else:
        subject_vals = [
            ('{FULLNAME}', u'收件人姓名'),
            ('{RECIPIENTS}',  u'收件人地址'),
            ('{DATE}',  u'当前日期'),
            ('{RANDOM_NUMBER}',  u'随机10位数字'),
            ('{SEX}', u'性别'),
            ('{BIRTHDAY}', u'生日'),
            ('{PHONE}', u'手机'),
            ('{AREA}', u'地区'),
        ]
    return render(request, template_name='mosaico/modify.html', context={
        'template_obj': obj,
        'subject_objs': subject_objs,
        'subject_vars': subject_vals,
        'encoding_types': ENCODING_TYPE,
        'character_types': CHARACTER_TYPE,
        'attachtype_types': ATTACH_TYPE,
        "original": original,
    })
Пример #6
0
def ajax_trigger_task_one(request, task_id):
    obj = get_object(TriggerTask, request.user, task_id)
    data = request.GET
    order_column = data.get('order[0][column]', '')
    order_dir = data.get('order[0][dir]', '')
    search = data.get('search[value]', '')
    colums = [
        'id', 'id', 'email', 'trigger_action', 'trigger_action', 'status',
        'create_time', 'action_time'
    ]
    lists = obj.triggertaskone_set.all()
    if search:
        lists = lists.filter(email__icontains=search)

    if order_column and int(order_column) < len(colums):
        if order_dir == 'desc':
            lists = lists.order_by('-%s' % colums[int(order_column)])
        else:
            lists = lists.order_by('%s' % colums[int(order_column)])
    try:
        length = int(data.get('length', 1))
    except ValueError:
        length = 1

    try:
        start_num = int(data.get('start', '0'))
        page = start_num / length + 1
    except ValueError:
        start_num = 0
        page = 1
    count = lists.count()
    if start_num >= count:
        page = 1
    paginator = Paginator(lists, length)
    try:
        lists = paginator.page(page)
    except (EmptyPage, InvalidPage):
        lists = paginator.page(paginator.num_pages)

    rs = {
        "sEcho": 0,
        "iTotalRecords": count,
        "iTotalDisplayRecords": count,
        "aaData": []
    }
    re_str = '<td.*?>(.*?)</td>'
    number = length * (page - 1) + 1
    for d in lists.object_list:
        t = TemplateResponse(request, 'trigger/ajax_trigger_task_one.html', {
            'd': d,
            'number': number
        })
        t.render()
        rs["aaData"].append(re.findall(re_str, t.content, re.DOTALL))
        number += 1
    return HttpResponse(json.dumps(rs, ensure_ascii=False),
                        content_type="application/json")
Пример #7
0
def task_preview(request, content_id):
    obj = get_object(SendContent, request.user, content_id)
    p = ParseEmail(obj.send_content)
    m = p.parseMailTemplate()
    text = m.get('html_text', '')
    charset = m.get('html_charset', '')
    if not text:
        text = m.get('plain_text', '')
        charset = m.get('plain_charset', '')
    return HttpResponse(text, charset=charset)
Пример #8
0
def task_view(request, task_id):
    obj = get_object(SendTask, request.user, task_id)
    # template_objs = SendTemplate.objects.filter(user=request.user, name__isnull=False)
    # template_ids = SendTaskTpl.objects.filter(task_id=task_id).values_list('template_id', flat=True)
    template_objs = SendContent.objects.filter(send_id=task_id, isvalid=True)
    return render(request, 'task/task_view.html', {
        'task_obj': obj,
        'template_objs': template_objs,
        # 'template_ids': template_ids,
    })
Пример #9
0
def ml_maillist_maintain_address(request, list_id):
    obj = get_object(MailList, request.user, list_id)
    if not obj.is_allow_export:
        raise Http404
    subject = model_addresses.get_subject(request, list_id)
    return render(request,
                  'address/ml_maillist_maintain_address.html',
                  context={
                      'subject': subject,
                      'list_id': list_id,
                  })
Пример #10
0
def start(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    original = get_original(obj, request.user.id)

    lang_code = request.user.lang_code
    cr = connections['mm-pool'].cursor()
    subject_vals, content_vals = commons.getVars(cr, request.user.id, lang_code)
    return render(request, 'mosaico/start.html', context={
        "original": original,
        "template_id": template_id,
        "subject_vals": json.dumps(dict(subject_vals)),
        "subject_list": json.dumps([key for key, value in subject_vals])
    })
Пример #11
0
def ml_subscribe_list(request, list_id):
    obj = model_addresses.get_address_obj(request, list_id)
    user_id = obj.customer_id
    if request.user.id == user_id:
        is_modify_flag = obj.is_allow_export
    else:
        is_modify_flag = False
    # obj = get_object(MailList, request.user, list_id)
    # is_modify_flag = obj.is_allow_export
    subject = model_addresses.get_subject(request, list_id, obj)
    is_subscribe = request.GET.get('is_subscribe', '')
    cr = connections['mm-pool'].cursor()
    address_sqls.checkTable(cr, user_id)
    if request.method == "POST":
        obj2 = get_object(MailList, request.user, list_id)
        tablename = 'ml_subscriber_' + str(request.user.id)
        id = request.POST.get('id', False)
        ids = request.POST.get('ids', '')
        status = int(request.POST.get('status', False))
        redis = get_redis_connection()
        if int(status) == -2:  # 单个删除
            sql = "DELETE FROM {0} WHERE address_id={1}".format(tablename, id)
            cr.execute(sql)
            messages.add_message(request, messages.SUCCESS, _(u'成功删除'))
            redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE,
                        '{}_{}'.format(request.user.id, list_id))
            return HttpResponseRedirect(
                "/address/subscribe/{}/".format(list_id))
        if int(status) == -1:  # 批量删除
            sql = "DELETE FROM {0} WHERE address_id IN ({1})".format(
                tablename, ids)
            cr.execute(sql)
            messages.add_message(request, messages.SUCCESS, _(u'成功删除'))
            redis.rpush(EDM_WEB_USER_MAIL_IMPORT_COUNT_QUEUE,
                        '{}_{}'.format(request.user.id, list_id))
            return HttpResponseRedirect(
                "/address/subscribe/{}/".format(list_id))

    var_lists = get_addr_var_fields(cr, request.user.id)
    field_lists = []
    for i in xrange(len(var_lists) - 10):
        field_lists.append(u'变量{}'.format(11 + i))
    return render(request,
                  'address/ml_subscribe_list.html',
                  context={
                      'subject': subject,
                      'list_id': list_id,
                      'is_subscribe': is_subscribe,
                      'field_lists': field_lists,
                      'is_modify_flag': is_modify_flag,
                  })
Пример #12
0
def ckupload(request, template_id):
    user = request.user
    get_object(SendTemplate, user, template_id)
    callback = request.GET.get("CKEditorFuncNum")
    if request.method == 'POST' and request.FILES['upload']:
        fileobj = request.FILES['upload']
        content_type = fileobj.content_type
        fname = fileobj.name
        fext = os.path.splitext(fname)[-1]
        if fext.lower()[1:] not in UPLOAD_JSON_SUFFIX["image"]:
            error = _(u"请上传正确的图片格式")
            res = u"<script>window.parent.CKEDITOR.tools.callFunction({},'', '{}');</script>".format(
                callback, error)
            return HttpResponse(res)
        if (file_size_conversion(fileobj.size, MB) > 1):
            error = _(u"上传图片大小不能超过1M")
            res = u"<script>window.parent.CKEDITOR.tools.callFunction({},'', '{}');</script>".format(
                callback, error)
            return HttpResponse(res)
        uuname = '{}-{}{}'.format(str(uuid.uuid1()), random.randint(1, 100000),
                                  fext)
        tplpath = os.path.join(settings.ATTACH_DATA_PATH, str(template_id))
        fpath = os.path.join(tplpath, uuname)
        create_filepath(tplpath)
        with open(fpath, 'w') as f:
            f.write(fileobj.read())
        SendAttachment.objects.create(user_id=user.id,
                                      template_id=template_id,
                                      filename=fname,
                                      filetype=content_type,
                                      filepath=uuname,
                                      attachtype='html')
        uri = "{}{}?id={}&ufile_name={}&aid=1&download=1".format(
            commons.getPicUrl(), reverse("ajax_get_network_attach"),
            template_id, uuname)
        res = r"<script>window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + uri + "', '');</script>"
        return HttpResponse(res)
    raise Http404()
Пример #13
0
def ajax_check_domain(request):
    id = request.POST.get('id', '')
    print id
    ctype = request.POST.get('ctype', '')
    obj = get_object(CustomerDomain, request.user, id)
    res = 'f'
    if ctype == 'dkim':
        res = 'Y' if valid_domain(obj.domain,
                                  'dkim',
                                  obj.dkim_public,
                                  dkim_selector=obj.dkim_selector) else 'f'
        obj.is_dkim = res
        obj.save()
    msg = {'msg': res}
    return HttpResponse(json.dumps(msg), content_type="application/json")
Пример #14
0
def task_modify(request, task_id):
    obj = get_object(SendTask, request.user, task_id)
    if obj.send_status in [2, 3, 4]:
        raise Http404
    custQtyValid, is_service_disabled = task_contexts.get_user_service(request)
    if request.method == "POST":
        return task_posts.post_task_modify(request, task_id, is_service_disabled)
    context = task_contexts.get_task_modify_context(request, task_id)
    context.update({
        'task_obj': obj,
        'c_send_maillist_ids': task_tools.get_modify_maillistid(obj),
        'custQtyValid': custQtyValid,
        'is_service_disabled': is_service_disabled,
    })
    return render(request, 'task/task_modify.html', context=context)
Пример #15
0
def template_preview(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    if obj.content_type == 1:
        charset = obj.character if obj.character else 'utf-8'
        return render(request,
                      'trigger/template_preview.html',
                      context={
                          'content': obj.content,
                          'charset': charset
                      })
    elif obj.content_type == 2:
        response = HttpResponse(obj.content.replace("\r\n", "\n"),
                                content_type='text/html')
        response['Content-Disposition'] = 'attachment; filename="eml.eml"'
        return response
Пример #16
0
def trigger_action_modify(request, trig_id, action_id):
    trigobj = get_object(Trigger, request.user, trig_id)
    obj = TriggerAction.objects.get(id=action_id)
    form = TriggerForm(request.user, instance=trigobj)
    action_form = TriggerActionForm(request.user, instance=obj)
    for field in form.visible_fields():
        field.field.widget.attrs['disabled'] = 'disabled'
    if request.method == "POST":
        data = json.loads(request.POST.get('data', ''))

    return render(request,
                  'trigger/trigger_add.html',
                  context={
                      "form": form,
                      "action_form": action_form,
                      "trig_title": _(u'修改触发器动作'),
                  })
Пример #17
0
def trigger_modify(request, trig_id):
    t_obj = get_object(Trigger, request.user, trig_id)
    form = TriggerForm(request.user, instance=t_obj)
    action_form = TriggerActionForm(request.user)
    form.fields['type'].widget.attrs['disabled'] = 'disabled'
    action_forms = []
    for action in t_obj.enable_trigger_action():
        f = TriggerActionForm(request.user, instance=action)
        action_forms.append(f)

    if request.method == "POST":
        data = json.loads(request.POST.get('data', ''))
        mailists = data.get('trigger_maillists', [])
        actions = data.get('action', [])
        for k, v in data.iteritems():
            if not v:
                continue
            if k in [
                    'end_time', 'expire_type', 'maillist_type', 'name',
                    'start_time', 'status', 'type'
            ]:
                setattr(t_obj, k, v)
        t_obj.save()
        TriggerListShip.objects.filter(trigger=t_obj).delete()
        if mailists:
            for m in mailists:
                TriggerListShip.objects.create(
                    trigger=t_obj,
                    maillist=MailList.objects.get(id=m, customer=request.user))
        if actions:
            t_obj.trigger_action.update(status='delete')
            for a in actions:
                act_obj = TriggerAction()
                act_obj.trigger = t_obj
                for k, v in a.iteritems():
                    if not v:
                        continue
                    try:
                        setattr(act_obj, k, v)
                    except BaseException, e:
                        pass
                act_obj.save()
        messages.add_message(request, messages.SUCCESS, _(u'修改成功'))
        return HttpResponse(json.dumps({'msg': u'修改成功'}, ensure_ascii=False),
                            content_type="application/json")
Пример #18
0
def trigger_show(request, trig_id):
    obj = get_object(Trigger, request.user, trig_id)
    form = TriggerForm(request.user, instance=obj)
    for field in form.visible_fields():
        field.field.widget.attrs['disabled'] = 'disabled'
    action_forms = []
    for action in obj.trigger_action.all():
        action_form = TriggerActionForm(request.user, instance=action)
        for field in action_form.visible_fields():
            field.field.widget.attrs['disabled'] = 'disabled'
        action_forms.append(action_form)
    return render(request,
                  'trigger/trigger_show.html',
                  context={
                      "form": form,
                      "action_forms": action_forms,
                      "trig_title": _(u'显示触发器'),
                  })
Пример #19
0
def template_modify(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    original = get_original(obj, request.user.id)
    if request.method == "POST":
        data = request.POST
        name = data.get('name', '')
        encoding = data.get('encoding', 'base64')
        character = data.get('character', 'utf-8')

        subject_list = data.getlist('subject_list[]', '')
        SendSubject.objects.filter(template_id=template_id).delete()
        subject_obj_list, template_subject = [], ''
        for subject in subject_list:
            if subject:
                template_subject = subject
                subject_obj_list.append(
                    SendSubject(template_id=template_id, subject=subject))
        SendSubject.objects.bulk_create(subject_obj_list)

        obj.name = name
        obj.subject = template_subject
        obj.encoding = encoding
        obj.character = character
        obj.issync = True
        # obj.result = None
        obj.save()
        return HttpResponseRedirect(
            reverse("mosaico_start", args=(template_id, )))
    lang_code = request.user.lang_code
    cr = connections['mm-pool'].cursor()
    subject_vals, content_vals = commons.getVars(cr, request.user.id,
                                                 lang_code)
    subject_objs = SendSubject.objects.filter(template_id=template_id)
    return render(request,
                  template_name='mosaico/modify.html',
                  context={
                      'template_obj': obj,
                      'subject_objs': subject_objs,
                      'subject_vars': subject_vals,
                      'encoding_types': ENCODING_TYPE,
                      'character_types': CHARACTER_TYPE,
                      'attachtype_types': ATTACH_TYPE,
                      "original": original,
                  })
Пример #20
0
def template_add(request, template_id):
    obj = get_object(SendTemplate, request.user, template_id)
    if not obj.isvalid:
        raise Http404
    form = SendTemplateForm(request.user, template_id, instance=obj)
    if request.method == "POST":
        subject_list = request.POST.getlist('subject_list', '')
        form = SendTemplateForm(request.user,
                                template_id,
                                subject_list,
                                request.POST,
                                instance=obj)
        if form.is_valid():
            obj = form.save()
            form.saveSubject(obj)
            caches.pushCheck(request.user.id, template_id)
            messages.add_message(request, messages.SUCCESS, _(u'模板修改成功'))
            next_uri = "{}?isvalid=1".format(reverse("template_list"))
            return HttpResponseRedirect(next_uri)
    reflists = RefTemplateCategory.objects.all()
    cr = connections['mm-pool'].cursor()
    lang_code = request.user.lang_code
    subject_vals, content_vals = commons.getVars(cr, request.user.id,
                                                 lang_code)
    conmmon_vals = commons.getCommons(lang_code)
    umail_vals = commons.getUnsubscibes(lang_code, request.user.id,
                                        template_id)
    share_link = commons.getShareLink(lang_code)
    return render(request,
                  template_name='template/cktemplate.html',
                  context={
                      "form": form,
                      "template_id": template_id,
                      'subject_vars': subject_vals,
                      'content_vals': json.dumps(content_vals),
                      'conmmon_vals': json.dumps(conmmon_vals),
                      'umail_vals': json.dumps(umail_vals),
                      'share_link': json.dumps(share_link),
                      'reflists': reflists,
                      'attach_list': obj.render_attach_template(),
                  })
Пример #21
0
def ml_maillist_modify(request, list_id):
    obj = get_object(MailList, request.user, list_id)
    form = MailListForm(request.user, instance=obj)
    if request.method == "POST":
        status = request.POST.get('status', '')
        form = MailListForm(request.user, request.POST, instance=obj)
        if status == 'allow':
            url = '/address/maintain/{}/'.format(list_id)
        elif status == 'notallow':
            url = '/address/?isvalid=1'
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(url)
    return render(request,
                  'address/ml_maillist_modify.html',
                  context={
                      'form': form,
                      'ml_maillist_flag': 2,
                      'list_id': list_id,
                      'edm_web_url': settings.EDM_WEB_URL,
                      'is_allow_export': obj.is_allow_export,
                  })
Пример #22
0
def send_domain(request):
    if request.method == "POST":
        domain = request.POST.get('domain', '')
        action = request.POST.get('action', '')
        id = request.POST.get('id', '')
        if request.user.service().is_umail:
            messages.add_message(request, messages.ERROR, _(u'测试帐号不允许此类操作!'))
            return HttpResponseRedirect(reverse('send_domain'))
        if id:
            obj = get_object(CustomerDomain, request.user, id)
        if action == 'track_delete':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.delete()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 删除成功!') % {'domain': trackobj.domain})
        elif action == 'track_default':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.isdefault = True
            trackobj.save()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 设置默认成功!') % {'domain': trackobj.domain})
        elif action == 'track_default_false':
            track_id = request.POST.get('track_id', '')
            trackobj = get_object(CustomerTrackDomain, request.user, track_id)
            trackobj.isdefault = False
            trackobj.save()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'跟踪域名:%(domain)s 关闭默认成功!') % {'domain': trackobj.domain})
        elif action == 'add':
            domain = domain.strip()
            if not validators.check_domains(domain):
                messages.add_message(
                    request, messages.ERROR,
                    _(u'添加失败,域名%(domain)s格式错误!') % {'domain': domain})
                return HttpResponseRedirect(reverse('send_domain'))
            if CustomerDomain.objects.filter(domain=domain,
                                             customer=request.user):
                messages.add_message(request, messages.ERROR,
                                     _(u'添加失败,发送域名重复添加!'))
            else:
                private_key, public_key = GenDkimKeys()
                public_key = 'k=rsa;p={}'.format(public_key)
                CustomerDomain.objects.create(customer=request.user,
                                              domain=domain,
                                              dkim_private=private_key,
                                              dkim_public=public_key)
                messages.add_message(request, messages.SUCCESS, _(u'发送域名添加成功'))
        elif action == 'valid_domain':
            if not validators.check_domains(obj.domain):
                messages.add_message(
                    request, messages.ERROR,
                    _(u'该域名%(domain)s格式错误,无法验证!') % {'domain': domain})
                return HttpResponseRedirect(reverse('send_domain'))
            # 判断是否有相同已验证通过的域名
            if CustomerDomain.objects.exclude(id=id).filter(
                    domain=obj.domain, status__in=['Y', 'T']):
                obj.status = 'f'
                obj.save()
                messages.add_message(
                    request, messages.ERROR,
                    _(u'该域名:%(domain)s 已被其他客户占用,无法验证!') %
                    {'domain': obj.domain})
            else:
                obj.is_spf = 'Y' if valid_domain(
                    obj.domain, 'spf', 'include:spf.bestedm.org') else 'f'
                obj.is_mx = 'Y' if valid_domain(obj.domain, 'mx',
                                                'mail.bestedm.org') else 'f'
                obj.is_dkim = 'Y' if valid_domain(
                    obj.domain,
                    'dkim',
                    obj.dkim_public,
                    dkim_selector=obj.dkim_selector) else 'f'
                res = True if obj.is_spf == 'Y' and obj.is_mx == 'Y' else False
                obj.status = 'Y' if res else 'f'
                obj.save()
                if res:
                    loglevel = messages.SUCCESS
                    obj.api_sync('add-domain')
                    add_count = gen_mailbox(obj)
                    message = _(u'域名:%(domain)s, 验证通过!并随机生成%(count)d个账号!') % {
                        'domain': obj.domain,
                        'count': add_count
                    }
                else:
                    message = _(u'域名:%(domain)s, 验证未通过!') % {
                        'domain': obj.domain
                    }
                    loglevel = messages.WARNING
                messages.add_message(request, loglevel, message)
        elif action == 'delete':
            messages.add_message(
                request, messages.SUCCESS,
                _(u'域名:%(domain)s 删除成功!') % {'domain': obj.domain})
            CustomerMailbox.objects.filter(customer=request.user,
                                           domain=obj.domain).delete()
            obj.api_sync('del-domain')
            obj.delete()
        elif action == 'gen_mailbox':
            total = 0
            for a in DefaultMailbox.objects.all():
                mailbox = '{}@{}'.format(a.account, obj.domain)
                if not CustomerMailbox.objects.filter(mailbox=mailbox,
                                                      disabled='0'):
                    m_obj = CustomerMailbox(customer=request.user,
                                            domain=obj.domain,
                                            name=a.account,
                                            mailbox=mailbox,
                                            password=get_random_string(10))
                    m_obj.save()
                    m_obj.api_sync('add-mailbox')
                    total += 1
            messages.add_message(
                request, messages.SUCCESS,
                _(u'域名:%(domain)s 成功随机生成%(count)d个账号!') % {
                    'domain': obj.domain,
                    'count': total
                })

        return HttpResponseRedirect(reverse('send_domain'))

    lists = CustomerDomain.objects.filter(customer=request.user)
    count = lists.count()
    # 共享域名以及获取发件人
    ctype = CustomerDomainMailboxRel.objects.get_content_type('domain')
    share_domain_ids = CustomerDomainMailboxRel.objects.filter(
        customer=request.user, content_type=ctype).values_list('object_id',
                                                               flat=True)
    share_lists = CustomerDomain.objects.filter(customer=request.user.parent,
                                                id__in=share_domain_ids,
                                                status__in=['Y', 'T'])
    for obj in share_lists:
        count += 1
        obj.no_index = count

    form = CustomerDomainForm()
    # 获取系统域名
    domain_list = CustomerMailbox.objects.filter(
        customer=request.user).values_list('domain', flat=True).distinct()
    sys_domain_list = CustomerDomain.objects.filter(
        domain__in=list(domain_list), customer_id=0)

    track_domain_list = CustomerTrackDomain.objects.filter(
        customer=request.user)
    return render(request,
                  template_name='core/senddomain_list.html',
                  context={
                      'lists': lists,
                      'share_lists': share_lists,
                      'form': form,
                      'sys_domain_list': sys_domain_list,
                      'track_domain_list': track_domain_list,
                  })
Пример #23
0
def mail_statistics_report_pdf_context(request, task_id):
    # key = ":django:edmweb:statistics:mail_statistics_report_pdf_context:report:{task_id}:".format(
    #     task_id=task_id)
    # context = cache.get(key, None)
    context = None
    if not context:
        obj = get_object(SendTask, request.user, task_id)
        if obj.send_status != 3:
            raise Http404
        # 任务发送数
        task_send_total = obj.get_real_send_qty()

        # 取得任务实际发送量
        value = StatTask.objects.filter(customer_id=request.user.id,
                                        task_ident=obj.send_name).aggregate(
                                            count_send=Sum('count_send'),
                                            count_error=Sum('count_error'),
                                            count_err_1=Sum('count_err_1'),
                                            count_err_2=Sum('count_err_2'),
                                            count_err_3=Sum('count_err_3'),
                                            count_err_5=Sum('count_err_5'),
                                        )
        count_send = value['count_send'] if value['count_send'] else 0
        count_error = int(
            value['count_error']) if value['count_error'] else 0  # 发送失败
        count_succes = count_send - count_error  # 发送成功数

        # 格式错误、无效
        # count_invalid = send_total - count_send
        # -------------------
        # 格式错误、无效
        count_invalid = obj.error_count
        # 一共发送数
        send_total = count_send + count_invalid
        # -------------------

        # 邮箱不存在
        count_err_1 = value['count_err_1'] if value['count_err_1'] else 0
        # 空间不足
        count_err_2 = value['count_err_2'] if value['count_err_2'] else 0
        # 用户拒收
        count_err_3 = value['count_err_3'] if value['count_err_3'] else 0
        # 垃圾拒绝发送
        count_err_5 = value['count_err_5'] if value['count_err_5'] else 0
        total_error = count_invalid + count_err_1 + count_err_2 + count_err_3 + count_err_5

        # 邮件打开
        stat_objs = TrackStat.objects.filter(task_ident=obj.send_name,
                                             customer_id=request.user.id)
        stat_obj = stat_objs[0] if stat_objs else None
        open_unique, click_unique = 0, 0
        show_stat_rate, show_link_rate, show_link_rate_suc = '0%', '0%', '0%'

        # 浏览器、操作系统、 地域 点击链接 统计
        link_objs = None
        ip_search = IpSearch()
        browser_count = {'ie': 0, 'firefox': 0, 'chrome': 0, 'other': 0}
        os_count = {'windows': 0, 'linux': 0, 'macintosh': 0, 'other': 0}
        area_list, area_lists, country_list, country_lists = [], {}, [], {}
        domain_data_click, domain_data_all = [], []
        track_id = 0
        pattern = '([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])'
        ip_compile = re.compile(pattern)
        if stat_objs:
            track_id = stat_obj.id
            # open_total = stat_obj.open_total
            open_unique = stat_obj.open_unique
            click_unique = stat_obj.click_unique
            show_stat_rate = statistics_tools.get_rate(stat_obj.open_unique,
                                                       count_succes)
            show_link_rate = statistics_tools.get_rate(click_unique,
                                                       open_unique)
            show_link_rate_suc = statistics_tools.get_rate(
                click_unique, count_succes)

            link_objs = TrackLink.objects.filter(track_id=track_id).order_by(
                '-click_unique', '-click_total')[:50]
            cr = connections['mm-track'].cursor()
            tablename = '{}_track_email'.format(request.user.id)

            sql = u""" SELECT email FROM {0} WHERE track_id={1} AND click_total > 0; """.format(
                tablename, track_id)
            cr.execute(sql)
            domain_data_click = statistics_tools.get_domain_data(cr.fetchall())

            sql = u""" SELECT email FROM {0} WHERE track_id={1} AND open_total > 0; """.format(
                tablename, track_id)
            cr.execute(sql)
            domain_data_all = statistics_tools.get_domain_data(cr.fetchall())

            # 地域分布
            sql = u"""
            SELECT browser, os, ip_first, ip_last, open_total, click_total, email
            FROM {0} WHERE track_id={1};
            """.format(tablename, track_id)
            cr.execute(sql)
            rows = cr.fetchall()

            for row in rows:
                if row[0].lower().startswith('msie'):
                    browser_count['ie'] += 1
                elif row[0].lower().startswith('firefox'):
                    browser_count['firefox'] += 1
                elif row[0].lower().startswith('chrome'):
                    browser_count['chrome'] += 1
                else:
                    browser_count['other'] += 1

                if row[1].lower().startswith('windows'):
                    os_count['windows'] += 1
                elif row[1].lower().startswith('linux'):
                    os_count['linux'] += 1
                elif row[1].lower().startswith('macintosh'):
                    os_count['macintosh'] += 1
                else:
                    os_count['other'] += 1

                ip = ''
                if row[2]:
                    ip = row[2]
                elif row[3]:
                    ip = row[3]
                if not ip:
                    continue

                m = ip_compile.search(ip)
                if m:
                    ip = m.group(0)
                else:
                    continue

                ip_info = ip_search.Find(ip)
                country, area = statistics_tools.split_ip_info(ip_info)
                if not country:
                    continue
                if country not in country_list:
                    country_list.append(country)
                    country_lists.update({country: [row[4], 1]})
                else:
                    country_lists.update({
                        country: [
                            country_lists[country][0] + row[4],
                            country_lists[country][1] + 1,
                        ]
                    })

                if not area:
                    continue

                if area not in area_list:
                    area_list.append(area)
                    area_lists.update({area: [row[4], 1]})
                else:
                    area_lists.update({
                        area: [
                            area_lists[area][0] + row[4],
                            area_lists[area][1] + 1,
                        ]
                    })

        area_sort_tmp = sorted(area_lists.items(),
                               key=lambda e: e[1][0],
                               reverse=True)[:10]
        country_sort_tmp = sorted(country_lists.items(),
                                  key=lambda e: e[1][0],
                                  reverse=True)[:10]
        area_data, country_data = {}, {}
        area_sort, country_sort = [], []
        for d in area_sort_tmp:
            if d[0] in AREA_CODE.keys():
                area_data.update({
                    AREA_CODE[d[0]]: int(d[1][0]),
                })
            area_sort.append((d[0], int(d[1][0]), int(d[1][1])))
        for d in country_sort_tmp:
            if d[0] in JC_CODE_COUNTRY:
                country_data.update({
                    JC_CODE_COUNTRY[d[0]]: int(d[1][0]),
                })
            country_sort.append((d[0], int(d[1][0]), int(d[1][1])))
        area_max = statistics_tools.get_gfc_max_data(
            area_sort_tmp[0][1][0]) if area_sort_tmp else 5000
        country_max = statistics_tools.get_gfc_max_data(
            country_sort_tmp[0][1][0]) if area_sort_tmp else 5000

        context = {
            'task_obj':
            obj,
            'task_id':
            task_id,
            'task_send_total':
            task_send_total,
            'send_total':
            send_total,
            'count_send':
            count_send,
            'count_succes':
            count_succes,
            'count_succes_rate':
            statistics_tools.get_rate(count_succes, count_send - count_err_5),
            'count_error':
            count_error,
            'count_error_rate':
            statistics_tools.get_rate(count_error - count_err_5,
                                      count_send - count_err_5),
            'total_error':
            total_error,
            'count_invalid': {
                'value': count_invalid,
                'width': statistics_tools.get_width(count_invalid,
                                                    total_error),
                'rate': statistics_tools.get_rate(count_invalid, total_error)
            },
            'count_err_1': {
                'value': count_err_1,
                'width': statistics_tools.get_width(count_err_1, total_error),
                'rate': statistics_tools.get_rate(count_err_1, total_error)
            },
            'count_err_2': {
                'value': count_err_2,
                'width': statistics_tools.get_width(count_err_2, total_error),
                'rate': statistics_tools.get_rate(count_err_2, total_error)
            },
            'count_err_3': {
                'value': count_err_3,
                'width': statistics_tools.get_width(count_err_3, total_error),
                'rate': statistics_tools.get_rate(count_err_3, total_error)
            },
            'count_err_5': {
                'value': count_err_5,
                'width': statistics_tools.get_width(count_err_5, total_error),
                'rate': statistics_tools.get_rate(count_err_5, total_error)
            },
            'stat_obj':
            stat_obj,
            'show_stat_rate':
            show_stat_rate,
            'open_unique':
            open_unique,
            'open_unique_rate':
            statistics_tools.get_rate(open_unique, count_succes),
            'no_open':
            count_succes - open_unique,
            'no_open_rate':
            statistics_tools.get_rate(count_succes - open_unique,
                                      count_succes),
            'click_unique':
            click_unique,
            'show_link_rate':
            show_link_rate,
            'show_link_rate_suc':
            show_link_rate_suc,
            'no_click':
            count_succes - click_unique,
            'no_click_rate':
            statistics_tools.get_rate(count_succes - click_unique,
                                      count_succes),
            'link_objs':
            link_objs,
            'track_id':
            track_id,
            'domain_data_click':
            domain_data_click,
            'domain_data_all':
            domain_data_all,
            'area_sort':
            area_sort,
            'country_sort':
            country_sort,
            'area_data':
            area_data,
            'country_data':
            country_data,
            'area_max':
            area_max,
            'country_max':
            country_max,
            'os_count':
            os_count,
            'browser_count':
            browser_count,
            'filename':
            u"{}_{}.pdf".format(obj.send_name, task_id)
        }
        # cache.set(key, context, 300)
    return context
Пример #24
0
def trigger_task_one(request, task_id):
    obj = get_object(TriggerTask, request.user, task_id)
    return render(request,
                  'trigger/trigger_task_one.html',
                  context={'obj': obj})
Пример #25
0
def ajax_template_info(request, task_id):
    obj = get_object(SendTask, request.user, task_id)
    html = obj.show_template_list()
    return HttpResponse(json.dumps({'info': html}), content_type="application/json")
Пример #26
0
def core_mailbox_add(request):
    domain = request.GET.get('domain', '')
    is_share = request.GET.get('is_share', '')
    if is_share == '1':
        is_not_share = False
        domains = CustomerDomain.objects.filter(domain=domain,
                                                customer=request.user.parent)
        if not domains:
            raise Http404
    else:
        is_not_share = True
        domains = CustomerDomain.objects.filter(
            domain=domain, customer_id__in=[0, request.user.id])
        if not domains:
            raise Http404
    # 判读是不是系统域名
    is_sys = True if domains[0].customer_id == 0 else False
    lists = CustomerMailbox.objects.filter(customer=request.user,
                                           domain=domain).order_by('-id')
    is_customer_add = True if lists.count() < 20 else False

    if request.method == "POST":
        action = request.POST.get('action', '')
        id = request.POST.get('id', '')
        if request.user.service().is_umail:
            messages.add_message(request, messages.ERROR, _(u'测试帐号不允许此类操作!'))
            return HttpResponseRedirect(
                '/core/mailbox/add/?domain={}'.format(domain))

        if action == 'sub_del' and id:  # 删除共享发件人
            obj = get_object(CustomerMailbox, request.user.parent, id)
            ctype = CustomerDomainMailboxRel.objects.get_content_type(
                'mailbox')
            CustomerDomainMailboxRel.objects.filter(customer=request.user,
                                                    content_type=ctype,
                                                    object_id=id).delete()

            box_ids = CustomerDomainMailboxRel.objects.filter(
                customer=request.user,
                content_type=ctype).values_list('object_id', flat=True)
            box_count = CustomerMailbox.objects.filter(
                customer=request.user.parent, domain=domain,
                id__in=box_ids).count()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'删除账号( %(mailbox)s )成功') % {'mailbox': obj.mailbox})
            if box_count:
                return HttpResponseRedirect(
                    '/core/mailbox/add/?domain={}&is_share={}'.format(
                        domain, is_share))
            else:
                domain_obj = CustomerDomain.objects.filter(
                    customer=request.user.parent, domain=domain).first()
                if domain_obj:
                    domain_ctype = CustomerDomainMailboxRel.objects.get_content_type(
                        'domain')
                    CustomerDomainMailboxRel.objects.filter(
                        customer=request.user,
                        content_type=domain_ctype,
                        object_id=domain_obj.id).delete()
                return HttpResponseRedirect(reverse('send_domain'))

        password = request.POST.get('input_password', '')
        domain = request.POST.get('domain', '')
        mailbox = request.POST.get('input_mailbox', '').strip()
        ids = request.POST.get('ids', '')

        if action == 'sub_alter' and id:
            obj = get_object(CustomerMailbox, request.user.parent, id)
            obj.password = password
            obj.save()
            obj.api_sync('set-mailbox-pass')
            messages.add_message(request, messages.SUCCESS, _(u'修改账号密码成功'))
            return HttpResponseRedirect(
                '/core/mailbox/add/?domain={}&is_share={}'.format(
                    domain, is_share))

        if id:
            obj = get_object(CustomerMailbox, request.user, id)
        if action == 'del':
            messages.add_message(
                request, messages.SUCCESS,
                _(u'删除账号( %(mailbox)s )成功') % {'mailbox': obj.mailbox})
            obj.api_sync('del-mailbox')
            obj.delete()
        elif action == 'alter':
            obj.password = password
            obj.save()
            obj.api_sync('set-mailbox-pass')
            messages.add_message(request, messages.SUCCESS, _(u'修改账号密码成功'))
        elif action == 'add':
            #系统域名禁止添加账号
            if is_sys:
                raise Http404
            num = random.randint(10, 32)
            password = get_random_string(num)
            obj = CustomerMailbox(customer=request.user,
                                  domain=domain,
                                  name=mailbox,
                                  mailbox='{}@{}'.format(mailbox, domain),
                                  password=password,
                                  disabled='0')
            obj.api_sync('add-mailbox')
            obj.save()
            messages.add_message(request, messages.SUCCESS, _(u'新增账号成功'))
        elif action == 'muldel':
            ids = ids.split(',')
            for d in CustomerMailbox.objects.filter(id__in=ids):
                d.api_sync('del-mailbox')
                d.delete()
            messages.add_message(request, messages.SUCCESS, _(u'批量删除成功'))
        return HttpResponseRedirect(
            '/core/mailbox/add/?domain={}'.format(domain))

    return render(request,
                  template_name='core/core_mailbox_add.html',
                  context={
                      'domain': domain,
                      'is_sys': is_sys,
                      'is_customer_add': is_customer_add,
                      'is_not_share': is_not_share,
                  })
Пример #27
0
def ml_maillist(request):
    isvalid = request.GET.get('isvalid', '')
    if request.method == "POST":
        cr = connections['mm-pool'].cursor()
        tablename = 'ml_subscriber_' + str(request.user.id)
        id = request.POST.get('id', False)
        ids_str = request.POST.get('ids', False)
        status = int(request.POST.get('status', False))
        id_del = int(request.POST.get('id_del', '0'))
        if int(status) == -3:  # 恢复地址池
            obj = get_object(MailList, request.user, id)
            obj.isvalid = True
            obj.save()
            messages.add_message(
                request, messages.SUCCESS,
                _(u'恢复地址池(%(subject)s)成功') % {"subject": obj.subject})
        if int(status) == -2:  # 删除
            obj = get_object(MailList, request.user, id)
            if obj.is_allow_export:
                obj.isvalid = False
                obj.save()
                messages.add_message(request, messages.SUCCESS, _(u'删除成功'))
            else:
                messages.add_message(request, messages.ERROR,
                                     _(u'不能删除  U-Mail租用数据'))
        # if int(status) == -1:  # 清空
        #     address_sqls.deleteAddress(cr, tablename, id)
        #     messages.add_message(request, messages.SUCCESS, _(u'清空地址成功'))
        if int(status) == -9:  # 合并分类
            ids = ids_str.split(',')
            ids = list(
                MailList.objects.filter(
                    id__in=ids, customer=request.user).values_list('id',
                                                                   flat=True))
            ids_str = ','.join(map(lambda s: str(s), ids))

            ## 合并到新分类
            new_category_name = request.POST.get('new_category_name',
                                                 "").strip()
            new_category_name = new_category_name or u"新分类"
            is_category = request.POST.get('is_category', "").strip()

            _exists = MailList.objects.filter(id__in=ids,
                                              is_allow_export=False).exists()
            if _exists:
                messages.add_message(request, messages.ERROR,
                                     _(u'合并分类失败,不能合并  U-Mail租用数据'))
            else:
                if is_category == '2':
                    mergeNewMaillist(request.user.id, ids, ids_str, id_del,
                                     new_category_name)
                else:
                    mergeMaillist(request.user.id, id, ids, ids_str, id_del)
                messages.add_message(request, messages.SUCCESS, _(u'合并分类成功'))
        if int(status) == -10:  # 删除分类
            ids = ids_str.split(',')
            _exists = MailList.objects.filter(id__in=ids,
                                              is_allow_export=False).exists()
            if _exists:
                messages.add_message(request, messages.ERROR,
                                     _(u'不能删除  U-Mail租用数据'))
            else:
                MailList.objects.filter(id__in=ids).update(isvalid=False)
                messages.add_message(request, messages.SUCCESS, _(u'删除分类成功'))
        if int(status) == 20:  # 预入库
            obj = get_object(MailList, request.user, id)
            # 行业 ID
            category_id = 29
            ctype = ContentType.objects.get_for_model(obj)
            tag_ids = TaggedItem.objects.filter(content_type=ctype,
                                                object_id=int(id)).values_list(
                                                    'tag_id', flat=True)
            # _exists = Tag.objects.filter(category_id=category_id, id__in=tag_ids).exists()
            _exists = Tag.objects.filter(id__in=tag_ids).exists()
            if not _exists:
                # messages.add_message(request, messages.ERROR, u'预入库必须具备一个行业标签')
                messages.add_message(request, messages.ERROR, u'预入库必须具备一个标签')
                return HttpResponseRedirect(
                    '/address/?isvalid={}'.format(isvalid))

            admin_id = request.session.get('admin_id', '')
            obj.status = '2'
            obj.manager_id = int(admin_id)
            obj.in_date = time.strftime("%Y-%m-%d %H:%M:%S")
            obj.save()
            messages.add_message(request, messages.SUCCESS, u'预入库成功')
        if int(status) == 21:  # 批量预入库
            admin_id = request.session.get('admin_id', '')
            ids = ids_str.split(',')
            objs = MailList.objects.filter(customer=request.user,
                                           status='1',
                                           id__in=ids,
                                           is_allow_export=True)
            other_ids = []
            if objs:
                # category_id = 29
                ctype = ContentType.objects.get_for_model(objs[0])
                for obj in objs:
                    tag_ids = TaggedItem.objects.filter(
                        content_type=ctype,
                        object_id=obj.id).values_list('tag_id', flat=True)
                    # _exists = Tag.objects.filter(category_id=category_id, id__in=tag_ids).exists()
                    _exists = Tag.objects.filter(id__in=tag_ids).exists()
                    if not _exists:
                        continue
                    other_ids.append(obj.id)

            MailList.objects.filter(
                customer=request.user,
                status='1',
                id__in=other_ids,
                is_allow_export=True).update(
                    status='2',
                    manager_id=int(admin_id),
                    in_date=time.strftime("%Y-%m-%d %H:%M:%S"))
            messages.add_message(request, messages.SUCCESS, u'预入库成功')
        if int(status) == -99:  # 单个删除共享地址池
            ShareMailList.objects.filter(maillist_id=id,
                                         user_id=request.user.id).delete()
            messages.add_message(request, messages.SUCCESS, _(u'删除共享联系人成功'))
        return HttpResponseRedirect('/address/?isvalid={}'.format(isvalid))
    return render(request,
                  'address/ml_maillist.html',
                  context={'isvalid': isvalid})
Пример #28
0
def ajax_mail_statistics_report(request, task_id):
    data = request.GET
    order_column = data.get('order[0][column]', '')
    order_dir = data.get('order[0][dir]', '')
    search = data.get('search[value]', '')

    obj = get_object(SendTask, request.user, task_id)
    ident = obj.send_name
    stat_objs = TrackStat.objects.filter(task_ident=obj.send_name,
                                         customer_id=request.user.id)
    lists = TrackLink.objects.filter(track__in=stat_objs)

    colums = [
        'id', 'link', 'click_unique', 'click_total', 'click_first',
        'click_last'
    ]

    if lists.exists() and order_column and int(order_column) < len(colums):
        if order_dir == 'desc':
            lists = lists.order_by('-%s' % colums[int(order_column)])
        else:
            lists = lists.order_by('%s' % colums[int(order_column)])
    try:
        length = int(data.get('length', 1))
    except ValueError:
        length = 1

    try:
        start_num = int(data.get('start', '0'))
        page = start_num / length + 1
    except ValueError:
        start_num = 0
        page = 1
    count = lists.count()
    if start_num >= count:
        page = 1

    paginator = Paginator(lists, length)

    try:
        lists = paginator.page(page)
    except (EmptyPage, InvalidPage):
        lists = paginator.page(paginator.num_pages)

    rs = {
        "sEcho": 0,
        "iTotalRecords": count,
        "iTotalDisplayRecords": count,
        "aaData": []
    }
    re_str = '<td.*?>(.*?)</td>'
    number = length * (page - 1) + 1
    for obj in lists.object_list:
        t = TemplateResponse(request,
                             'statistics/ajax_mail_statistics_report.html', {
                                 'obj': obj,
                                 'number': number,
                                 'ident': ident
                             })
        t.render()
        rs["aaData"].append(re.findall(re_str, t.content, re.DOTALL))
        number += 1
    return HttpResponse(json.dumps(rs, ensure_ascii=False),
                        content_type="application/json")
Пример #29
0
def ajax_stat_success_info(request, task_id):
    obj = get_object(SendTask, request.user, task_id)
    info = obj.show_stat_success_info()
    return HttpResponse(json.dumps({'info': info}), content_type="application/json")