Example #1
0
    def post(self, request, *args, **kwargs):
        data = request.POST.copy()
        openid = data.get('wechatuser')
        wechatuser = WechatUser.objects.get(openid=openid)
        data.update({'wechatuser': wechatuser.id})
        article_id = data.get('article')
        judge = data.get('judge', '')
        if judge:
            data.update({'judge_datetime': datetime.datetime.now()})
            data.update({'remind_date': datetime.datetime.now().date()})
        try:
            instance = Judgement.objects.get(wechatuser__id=wechatuser.id,
                                             article__id=article_id)
        except Judgement.DoesNotExist:
            instance = None
        form = JudgementForm(data, instance=instance)
        res = {'status': 'ok'}
        if form.is_valid():
            form.save()
            ArticlePostedResults.objects.filter(pk=article_id).update(
                is_judgement=1)
        else:
            debug('judgement_created', form.errors)
            res.update({'status': 'error'})

        return self.render_to_json_response(res)
Example #2
0
    def post(self, request, *args, **kwargs):
        data = request.data
        debug('notification_url', data)
        invoice_id = data.get('id')
        status = data.get('status')
        exceptionStatus = lower(str(data.get('exceptionStatus')))
        order = MemberOrder.objects.get(invoice_id=invoice_id)
        order.status = status
        order.exception_status = exceptionStatus
        order.save()
        user = order.user
        MemberOrderNotificationRecord.objects.create(
            order=order,
            user=user,
            invoice_id=invoice_id,
            status=status,
            exception_status=exceptionStatus,
            origin=data)

        client = Client(api_uri=settings.BITPAY_API_URL)
        invoice_data = client.get_invoice(invoice_id)
        debug('notification_url_invoice_data', invoice_data)
        if invoice_data.get('status') == 'confirmed':  # 确认等级中
            #         if invoice_data.get('status') == 'complete'#确认等级慢
            user.is_member = True
            user.member_last_date = order.end_date
            user.save()
        return Response({'invoice_id': order.invoice_id})
Example #3
0
def build_words_weight():
    st = time.time()
    bigvs = BigVs.objects.all()
    def _build(b):
        data = ArticlePostedResults.active_objects.filter(bigv__v_id=b.v_id, is_correct__in=(0, 1)).values('is_correct').annotate(count=Count('is_correct')).order_by('is_correct')
        sum_c , w, c = 0, 0, 0
        for d in data:
            if d['is_correct'] == 1:
                c = d['count']
            sum_c += d['count']
        if sum_c:
            w = c * 1.0 / sum_c
            c = w * 200
            sum_c = 200
        data = Judgement.objects.filter(article__bigv=b, judge__isnull=False).values('judge').annotate(count=Count('judge')).order_by('judge')
        for d in data:
            if d['judge'] == 'right':
                c += d['count']
            sum_c += d['count']
        if sum_c:
            w = int(round(c * 1.0 / sum_c * 100))
            b.words_weight = w
            b.save()
            print b.name, c, sum_c, w
    pool = Pool(8)
    pool.map(_build, bigvs)
    pool.close()
    pool.join()
    ed = time.time()
    debug('build_words_weight', ed - st)
Example #4
0
    def load_plugins(self, plugins):
        """load_plugins(plugins: list<str>) -> list

		Load each plugin name passed in `plugins`
		Return a list of successfully loaded plugins.

		"""
        loaded = []
        for plugin_name in plugins:
            # TODO: Support loading multiple
            plug_path = self.get_plugin_path(plugin_name)
            if not plug_path:
                self.error(self.active_user, 'The plugin "plugin_%s.py" could not be found.' % plugin_name)
                continue

            try:
                if self._load_plugin(plugin_name, plug_path):
                    loaded.append(plugin_name)
            except:
                traceback.print_exc()
                print "\n"
                self._unload_plugin(plug_path)
                utils.debug("plugins", "There was an error importing the plugin. A report has been logged.")

                utils.confirmdir("errors")
                with file(os.path.join(".", "errors", "PluginError-%s.log" % self.module), "a+") as pluglog:
                    print >> pluglog, "\n Plugin error log for: ", plugin_name
                    traceback.print_exc(None, pluglog)
                continue

        return loaded
Example #5
0
    def post_refund_success(self, order, domain):
#        OPENTM202723917
        data = {
                "touser":order.openid
                , "template_id":self.adv.refund_success_template_id
                , "url":"http://{0}/product/refund_success/?trade_no={1}".format(domain, order.orderid)
                , "topcolor":"#000000"
                , "data":{
                   "first": {
                       "value":"您好,您购买的{0}已退款成功!\n".format(order.product.name),
                       "color":"#000000"
                   },
                   "keyword1":{
                       "value":order.orderid,
                       "color":"#000000"
                   },
                   "keyword2": {
                       "value":"{0}元".format(order.price),
                       "color":"#000000"
                   },
                   "remark":{
                       "value":"\n感谢您的光临~",
                       "color":"#000000"
                   }
                }
            }
        req = urllib2.Request(self.post_tmplmsg_api)
        req.add_header('Content-Type', 'application/json')
        req.add_header('encoding', 'utf-8')
        response = urllib2.urlopen(req, json.dumps(data))
        result = json.loads(response.read())
        debug('refund-template', result)
        return (result.get('errcode'), result.get('errmsg'))
Example #6
0
    def _load_plugin(self, name, path_):
        """load_plugin(path_: str) -> bool

		Load `path_` and attempt to execute.
		Return True if it was executed.
		Return False if no changes were made (ie. not executed).

		"""

        with open(path_, "r") as f:
            a = f.read()
            # Skip plugins that haven't been updated.
        if not self.plugin_changed(name, a):
            return False

            # Replicate __file__ in the plugin, since it isn't set by the
            # interpreter when it executes a string.
            # We're using __file__ to know what command classes to unload.
        plugin = {"__file__": path_}
        exec compile(a, "plugin_%s.py" % name, "exec") in plugin
        # If the plugin has any initialization to be run, handle that here.
        initializer = mounts.PluginInitializers.plugins.get(path_)
        if initializer:
            initializer(self).initialize()

        utils.debug("core", "Loading Plugin (%s)" % path_)
        self._pluginhash[name] = hash(a)
        return True
Example #7
0
def transaction_warning_notification():
    '''
    每小时执行,生成交易地址预警提醒
    '''
    year = now().year
    month = now().month
    day = now().day
    ssuser = []
    for ss in SubscribeSetting.objects.filter(status=1):
        if (ss.start_time > ss.end_time and ss.start_time > now().time() and ss.end_time < now().time())\
                or (ss.start_time < ss.end_time and (ss.start_time > now().time() or ss.end_time < now().time())):
            ssuser.append(ss.user.pk)

    qs = TransactionWarning.objects.filter(user__in=ssuser,
                                           created_datetime__year=year,
                                           created_datetime__month=month,
                                           created_datetime__day=day,
                                           pushed=False)
    for obj in qs:
        desc = _(u'交易预警:{}有新的{}交易,交易量为{}币').format(
            obj.address_type == 1 and u'赚钱账户' or u'韭菜账户',
            obj.get_change_display(), obj.amount)
        Notification.objects.create(receiver=obj.user,
                                    content_object=obj,
                                    desc=desc,
                                    push_status='done',
                                    push_datetime=now())

    if qs.exists():
        users = qs.values('user').annotate(
            count=Count('user')).order_by('user')
        users_count = len(users)
        max_alias_const = 100
        max_alias = users_count if users_count < max_alias_const else max_alias_const
        sdk = PushSdk()

        for step in range(0, users_count, max_alias):
            real_alias = users_count % max_alias if users_count - \
                step < max_alias else max_alias
            push_notifications = []
            urlscheme = build_urlscheme('app')
            for index in xrange(0, real_alias):
                user = users[index + step]
                push_notifications.append(
                    Notification(receiver_id=user.get('user'),
                                 content_object=obj,
                                 desc=desc,
                                 ntf_type='push',
                                 push_required=False,
                                 push_status='done',
                                 push_datetime=now(),
                                 urlscheme=urlscheme))
            aliases = users[step:step + real_alias]
            r, info = sdk.publish_to_alias_batch(
                map(lambda x: str(x.get('user')), aliases), _(u'交易预警'),
                u'您订阅的地址有了新的交易行情', urlscheme)
            Notification.objects.bulk_create(push_notifications)
            debug('transaction_warning_notification', (r, info))
        qs.update(pushed=True)
Example #8
0
def cache_bigv_():
    st = time.time()
    bigvs = BigVs.objects.values('v_id', 'name', 'words_weight')
    res = {}
    map(lambda x: res.update({x['v_id']: x}), bigvs)
    cache.set(BIGVS_ALL_KEY, res)
    ed = time.time()
    debug('cache_bigv', ed - st)
Example #9
0
def cache_bigv_():
    st = time.time()
    bigvs = BigVs.objects.values('v_id', 'name', 'words_weight')
    res = {}
    map(lambda x: res.update({x['v_id']: x}), bigvs)
    cache.set(BIGVS_ALL_KEY, res)
    ed = time.time()
    debug('cache_bigv', ed - st)
Example #10
0
def unsubscribe(request):
    openid = request.session['openid']
    try:
        Subscribe.objects.filter(wechatuser__openid=openid, status='subscribe').update(status='cancel')
    except Exception as e:
        debug('unsubscribe', e)
        return JsonResponse({'res':'error'})
    return JsonResponse({'res':'ok'})
Example #11
0
def unsubscribe(request):
    openid = request.session['openid']
    try:
        Subscribe.objects.filter(wechatuser__openid=openid,
                                 status='subscribe').update(status='cancel')
    except Exception as e:
        debug('unsubscribe', e)
        return JsonResponse({'res': 'error'})
    return JsonResponse({'res': 'ok'})
Example #12
0
def flattext(slug, modes=''):
    """Render a flattext by slug."""
    # modes = modes.split()
    # silence = 'silence' in modes
    try:
        # where the db hit actually occurs
        text = FlatText.objects.get(slug=slug).render()
    except Exception, e:
        debug('flattext', u'failed to render flattext "%s": %s' % (slug, e))
        text = ''
Example #13
0
def flattext(slug, modes=''):
    """Render a flattext by slug."""
    # modes = modes.split()
    # silence = 'silence' in modes
    try:
        # where the db hit actually occurs
        text = FlatText.objects.get(slug=slug).render()
    except Exception, e:
        debug('flattext', u'failed to render flattext "%s": %s' % (slug, e))
        text = ''
Example #14
0
def unfollow(request):
    data = request.GET.copy()
    openid = data.get('openid')
    bigv_id = data.get('bigv_id')
    try:
        WechatUser_BigVs.objects.filter(wechatuser__openid=openid, bigvs__id=bigv_id).delete()
    except Exception as e:
        debug('unfollow', e, True)
        return JsonResponse({"res": False})
    return JsonResponse({"res": True})
Example #15
0
def follow(request):
    data = request.GET.copy()
    openid = data.get('openid')
    bigv_id = data.get('bigv_id')
    try:
        WechatUser_BigVs.objects.create(wechatuser=WechatUser.objects.get(openid=openid)\
                                        , bigvs=BigVs.objects.get(pk=bigv_id))
    except Exception as e:
        debug('follow', e, True)
        return JsonResponse({"res": False})
    return JsonResponse({"res": True})
Example #16
0
def unfollow(request):
    data = request.GET.copy()
    openid = data.get('openid')
    bigv_id = data.get('bigv_id')
    try:
        WechatUser_BigVs.objects.filter(wechatuser__openid=openid,
                                        bigvs__id=bigv_id).delete()
    except Exception as e:
        debug('unfollow', e, True)
        return JsonResponse({"res": False})
    return JsonResponse({"res": True})
Example #17
0
def follow(request):
    data = request.GET.copy()
    openid = data.get('openid')
    bigv_id = data.get('bigv_id')
    try:
        WechatUser_BigVs.objects.create(wechatuser=WechatUser.objects.get(openid=openid)\
                                        , bigvs=BigVs.objects.get(pk=bigv_id))
    except Exception as e:
        debug('follow', e, True)
        return JsonResponse({"res": False})
    return JsonResponse({"res": True})
Example #18
0
def subscribe(request):
    openid = request.session['openid']
    try:
        sub = Subscribe.objects.get(wechatuser__openid=openid)
        sub.status = 'subscribe'
        sub.save()
    except Subscribe.DoesNotExist:
        Subscribe.objects.create(wechatuser=WechatUser.objects.get(openid=openid), status='subscribe')
    except Exception as e:
        debug('subscribe', e)
        return JsonResponse({'res':'error'})
    return JsonResponse({'res':'ok'})
Example #19
0
def build_rank():
    st = time.time()
    rank = Judgement.objects.filter(judge__isnull=False).values('wechatuser').annotate(count=Count('wechatuser')).order_by('wechatuser')
    rank = sorted(rank, cmp=cmp, key=lambda x: x['count'], reverse=True)
    num = len(rank)
    res = {}
    map(lambda x: res.update({rank[x - 1]['wechatuser']: '******'.format((num - x) / num)}), range(1, num + 1))
    json_res = json.dumps(res)
    print json_res
    cache.set(JUDGE_RANK_KEY, res, settings.NEVER_REDIS_TIMEOUT)
    cache.set(JUDGE_RANK_KEY + '_json', json_res)
    ed = time.time()
    debug('build_rank', ed - st)
Example #20
0
def subscribe(request):
    openid = request.session['openid']
    try:
        sub = Subscribe.objects.get(wechatuser__openid=openid)
        sub.status = 'subscribe'
        sub.save()
    except Subscribe.DoesNotExist:
        Subscribe.objects.create(
            wechatuser=WechatUser.objects.get(openid=openid),
            status='subscribe')
    except Exception as e:
        debug('subscribe', e)
        return JsonResponse({'res': 'error'})
    return JsonResponse({'res': 'ok'})
Example #21
0
def build_pinyin_for_name():
    st = time.time()
    bigvs = BigVs.objects.filter(isdefault=0)
    p = Pinyin()
    def _build(bv):
        if bv.name and not bv.initials:
            bv.pinyin = p.get_pinyin(bv.name, u'')
            bv.initials = p.get_initials(bv.name, u'')
            bv.save()
    pool = Pool(8)
    pool.map(_build, bigvs)
    pool.close()
    pool.join()
    ed = time.time()
    debug('build_pinyin_for_name', ed - st)
Example #22
0
def build_score():
    st = time.time()
    queryset = ArticlePostedResults.active_objects.all()
    publish_date = queryset.only('publish_date').latest('publish_date').publish_date
    last = time.mktime(publish_date.timetuple())
    first = (publish_date - datetime.timedelta(days=60)).strftime('%Y-%m-%d %H:%M:%S')
    cursor = connection.cursor()
    sql = "update `{0}` inner join \
    (select `{0}`.id, (((2000 - (({1} - UNIX_TIMESTAMP(`{0}`.`publish_date`)) / 60.0)) * 0.05) + `big_vs`.`words_weight` + `{0}`.`is_predictable` * 5) AS `level`\
    FROM `{0}` INNER JOIN `big_vs` ON ( `{0}`.`v_id` = `big_vs`.`v_id` ) WHERE `{0}`.`article_status` IN (-2, 2, 3) and `{0}`.`publish_date` > '{2}'\
    ) as t1 on `{0}`.id = t1.id set score=t1.level".format('article_posted_results', last, first)
    cursor.execute(sql)
    cursor.fetchone()
    end = time.time()
    debug('build_score', end - st)
Example #23
0
def count_comments_():
    st = time.time()
    queryset = ArticlePostedResults.active_objects.all()
    print queryset.count()
    res = {}
    def _build(article):
        if article.comments.exists():
            count = article.comments.count()
            res.update({article.id: count})
    pool = Pool(8)
    pool.map(_build, queryset)
    pool.close()
    pool.join()
    cache.set(ARTICLE_COMMENTS_KEY, res)
    ed = time.time()
    debug('count_comments', ed - st)
Example #24
0
 def send(self, uid, msg):
     data = {
         "touser": uid.encode('utf-8'),
         "msgtype": "text",
         "text":{
             "content": msg.encode('utf-8')
         }
     }
     send_msg_api = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}' \
                             .format(self.__get_access_token())
     req = urllib2.Request(send_msg_api)
     req.add_header('Content-Type', 'application/json')
     req.add_header('encoding', 'utf-8')
     response = urllib2.urlopen(req, json.dumps(data, ensure_ascii=False))
     result = json.loads(response.read())
     debug('message-send', result)
     return result
Example #25
0
def build_pinyin_for_name():
    st = time.time()
    bigvs = BigVs.objects.filter(isdefault=0)
    p = Pinyin()

    def _build(bv):
        if bv.name and not bv.initials:
            bv.pinyin = p.get_pinyin(bv.name, u'')
            bv.initials = p.get_initials(bv.name, u'')
            bv.save()

    pool = Pool(8)
    pool.map(_build, bigvs)
    pool.close()
    pool.join()
    ed = time.time()
    debug('build_pinyin_for_name', ed - st)
Example #26
0
def build_rank():
    st = time.time()
    rank = Judgement.objects.filter(
        judge__isnull=False).values('wechatuser').annotate(
            count=Count('wechatuser')).order_by('wechatuser')
    rank = sorted(rank, cmp=cmp, key=lambda x: x['count'], reverse=True)
    num = len(rank)
    res = {}
    map(
        lambda x: res.update(
            {rank[x - 1]['wechatuser']: '******'.format((num - x) / num)}),
        range(1, num + 1))
    json_res = json.dumps(res)
    print json_res
    cache.set(JUDGE_RANK_KEY, res, settings.NEVER_REDIS_TIMEOUT)
    cache.set(JUDGE_RANK_KEY + '_json', json_res)
    ed = time.time()
    debug('build_rank', ed - st)
Example #27
0
def build_score():
    st = time.time()
    queryset = ArticlePostedResults.active_objects.all()
    publish_date = queryset.only('publish_date').latest(
        'publish_date').publish_date
    last = time.mktime(publish_date.timetuple())
    first = (publish_date -
             datetime.timedelta(days=60)).strftime('%Y-%m-%d %H:%M:%S')
    cursor = connection.cursor()
    sql = "update `{0}` inner join \
    (select `{0}`.id, (((2000 - (({1} - UNIX_TIMESTAMP(`{0}`.`publish_date`)) / 60.0)) * 0.05) + `big_vs`.`words_weight` + `{0}`.`is_predictable` * 5) AS `level`\
    FROM `{0}` INNER JOIN `big_vs` ON ( `{0}`.`v_id` = `big_vs`.`v_id` ) WHERE `{0}`.`article_status` IN (-2, 2, 3) and `{0}`.`publish_date` > '{2}'\
    ) as t1 on `{0}`.id = t1.id set score=t1.level".format(
        'article_posted_results', last, first)
    cursor.execute(sql)
    cursor.fetchone()
    end = time.time()
    debug('build_score', end - st)
Example #28
0
def count_comments_():
    st = time.time()
    queryset = ArticlePostedResults.active_objects.all()
    print queryset.count()
    res = {}

    def _build(article):
        if article.comments.exists():
            count = article.comments.count()
            res.update({article.id: count})

    pool = Pool(8)
    pool.map(_build, queryset)
    pool.close()
    pool.join()
    cache.set(ARTICLE_COMMENTS_KEY, res)
    ed = time.time()
    debug('count_comments', ed - st)
Example #29
0
    def _unload_plugin(self, path_):
        utils.debug("core", "Unloading Plugin (%s)" % path_)
        initializer = mounts.PluginInitializers.plugins.get(path_)
        if initializer:
            if isinstance(initializer, type):
                initializer.remove(initializer)
            else:
                initializer.__exit__()

        for cmd in mounts.CommandMount.get_plugin_list(file=path_):
            if isinstance(cmd, type):
                cmd.remove(cmd)
            else:
                cmd.__exit__()

        for hook in mounts.HookMount.get_plugin_list(file=path_):
            if isinstance(hook, type):
                hook.remove(hook)
            else:
                hook.__exit__()
Example #30
0
	def reconnect(self, tries=5):
		"""reconnect(tries=5) -> bool

		Attempt to reconnect to the server `tries` number of times.

		"""
		delay = 5
		utils.debug('connection', 'Attempting to reconnect in %s seconds.' % delay)
		time.sleep(delay)
		try:
			self.client.reconnectAndReauth()
			self.setOnline()
			return True
		except AttributeError:
			utils.debug('connection', 'Failed to reconnect. Making new connection'
								' in %s seconds.' % delay)
			time.sleep(delay)
			self.prep()
			if tries:
				return self.reconnect(tries-1)

		return False
Example #31
0
def build_words_weight():
    st = time.time()
    bigvs = BigVs.objects.all()

    def _build(b):
        data = ArticlePostedResults.active_objects.filter(
            bigv__v_id=b.v_id,
            is_correct__in=(0, 1)).values('is_correct').annotate(
                count=Count('is_correct')).order_by('is_correct')
        sum_c, w, c = 0, 0, 0
        for d in data:
            if d['is_correct'] == 1:
                c = d['count']
            sum_c += d['count']
        if sum_c:
            w = c * 1.0 / sum_c
            c = w * 200
            sum_c = 200
        data = Judgement.objects.filter(
            article__bigv=b, judge__isnull=False).values('judge').annotate(
                count=Count('judge')).order_by('judge')
        for d in data:
            if d['judge'] == 'right':
                c += d['count']
            sum_c += d['count']
        if sum_c:
            w = int(round(c * 1.0 / sum_c * 100))
            b.words_weight = w
            b.save()
            print b.name, c, sum_c, w

    pool = Pool(8)
    pool.map(_build, bigvs)
    pool.close()
    pool.join()
    ed = time.time()
    debug('build_words_weight', ed - st)
Example #32
0
    def device_notice(self, openid, number, msg):
#        OPENTM401260554
        data = {
                "touser":openid
                , "template_id":self.adv.device_notice_template_id
                , "url":""
                , "topcolor":"#7B68EE"
                , "data":{
                   "first": {
                       "value":'让您久等啦!\n',
                       "color":"#000000"
                   },
                   "keyword1":{
                       "value":number,
                       "color":"#000000"
                   },
                   "keyword2": {
                       "value":msg,
                       "color":"#000000"
                   },
                   "remark":{
                       "value":"\n感谢您的光临~",
                       "color":"#000000"
                   }
                }
            }
        req = urllib2.Request(self.post_tmplmsg_api)
        req.add_header('Content-Type', 'application/json')
        req.add_header('encoding', 'utf-8')
        response = urllib2.urlopen(req, json.dumps(data))
        result = json.loads(response.read())
        debug('device-notice-template', result)
        code = result.get('errcode')
        if code != 0:
            self.send(openid, msg)
        return (code, result.get('errmsg'))
Example #33
0
 def post(self, request, *args, **kwargs):
     data = request.POST.copy()
     openid = data.get('wechatuser')
     wechatuser = WechatUser.objects.get(openid=openid)
     data.update({'wechatuser': wechatuser.id})
     article_id = data.get('article')
     judge = data.get('judge', '')
     if judge:
         data.update({'judge_datetime': datetime.datetime.now()})
         data.update({'remind_date': datetime.datetime.now().date()})
     try:
         instance = Judgement.objects.get(wechatuser__id=wechatuser.id, article__id=article_id)
     except Judgement.DoesNotExist:
         instance = None
     form = JudgementForm(data, instance=instance)
     res = {'status': 'ok'}
     if form.is_valid():
         form.save()
         ArticlePostedResults.objects.filter(pk=article_id).update(is_judgement=1)
     else:
         debug('judgement_created', form.errors)
         res.update({'status':'error'})
     
     return self.render_to_json_response(res)
Example #34
0
 def wrapped_view(*args, **kwargs):
     st = time.time()
     res = view_func(*args, **kwargs)
     ed = time.time()
     debug(view_func.__name__, ed - st)
     return res
Example #35
0
		# Process persistant hooks.
		if not self.hook(const.LOC_EV_CHAT, user, status):
			return

	def ev_dnd(self, user, status):
		# Process persistant hooks.
		if not self.hook(const.LOC_EV_DND, user, status):
			return

	def ev_xa(self, user, status):
		# Process persistant hooks.
		if not self.hook(const.LOC_EV_XA, user, status):
			return

if __name__ == '__main__':
	me = ConferenceBot()

	me.prep()
	me.setOnline()

	#Add any new users.
	#for i in me.getRoster():
	#	i = getjid(i)
	#	if i not in userlist.keys():
	#		adduser(getname(i))

	utils.debug('core', "The bot is now online!\nRunning version: %s\nAt %s" % (
			utils.get_svn_revision(), time.strftime("%Y-%m-%d %H:%M:%S")
		))
	me.run()
Example #36
0
    def _push(self, devicetype, target, targetvalue, title, content,
              urlscheme):
        clt = client.AcsClient(self.accessKeyId, self.accessKeySecret,
                               self.regionId)
        title = title[:20]
        xm_title = title[:15]
        xm_content = content[:127]

        request = PushRequest.PushRequest()
        request.set_AppKey(self.appKey)
        # 推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
        request.set_Target(target)
        # 根据Target来设定,如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        request.set_TargetValue(targetvalue)
        # 设备类型 ANDROID iOS ALL
        request.set_DeviceType(devicetype)
        # 消息类型 MESSAGE NOTICE
        request.set_PushType("NOTICE")

        extra_dict = {'urlscheme': urlscheme}
        # 消息的标题
        request.set_Title(title.encode('utf-8'))
        # 消息的内容
        request.set_Body(content.encode('utf-8'))

        # iOS配置
        request.set_iOSBadge(1)
        # 开启静默通知
        request.set_iOSSilentNotification(False)
        # iOS通知声音
        request.set_iOSMusic("default")
        # iOS的通知是通过APNs中心来发送的,需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
        request.set_iOSApnsEnv("PRODUCT")
        # 消息推送时设备不在线(既与移动推送的服务端的长连接通道不通),则这条推送会做为通知,通过苹果的APNs通道送达一次。注意:离线消息转通知仅适用于生产环境
        request.set_iOSRemind(True)
        # iOS消息转通知时使用的iOS通知内容,仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
        request.set_iOSRemindBody("iOSRemindBody")
        # 自定义的kv结构,开发者扩展用 针对iOS设备
        request.set_iOSExtParameters(json.dumps(extra_dict))

        # android配置

        # 指定notificaitonchannel id
        request.set_AndroidNotificationChannel("1")

        # 通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
        request.set_AndroidNotifyType("SOUND")
        # 通知栏自定义样式1-100
        request.set_AndroidNotificationBarType(1)
        # 点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
        request.set_AndroidOpenType("ACTIVITY")
        # Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
        #         request.set_AndroidOpenUrl("www.aliyun.com")
        # 设定通知打开的activity,仅当AndroidOpenType="Activity"有效
        request.set_AndroidActivity("com.blockcashflow.app.main.MainActivity")
        # Android通知声音
        request.set_AndroidMusic("default")
        # 设置该参数后启动小米托管弹窗功能, 此处指定通知点击后跳转的Activity(托管弹窗的前提条件:1. 集成小米辅助通道;2. StoreOffline参数设为true)
        request.set_AndroidXiaoMiActivity(
            "com.blockcashflow.app.main.MainActivity")
        # 设定通知的扩展属性。(注意 : 该参数要以 json map 的格式传入,否则会解析出错)
        request.set_AndroidExtParameters(json.dumps(extra_dict))

        request.set_AndroidXiaoMiNotifyTitle(xm_title.encode('utf-8'))
        request.set_AndroidXiaoMiNotifyBody(xm_content.encode('utf-8'))

        request.set_StoreOffline(True)

        try:
            debug('aliyun_push_data',
                  ', '.join([target, targetvalue, title, content, urlscheme]))
            result = clt.do_action_with_exception(request)
            result = json.loads(result)
            debug('aliyun_push', result)
            return True, result.get('MessageId')
        except Exception as e:
            debug('aliyun_push_error', e, True)
            return False, str(e)
Example #37
0
    def post(self, request, *args, **kwargs):
        user = request.app_user
        data = request.data
        mspk = data.get('mspk')
        ms = MemberService.objects.get(pk=mspk)
        last_date = user.member_last_date
        if last_date and now().date() + datetime.timedelta(
                days=15) < last_date:
            return Response({'code': 40009, 'detail': _(u'会员到期前15天可续费')})
        if last_date and now().date() <= last_date:
            start_date = last_date + datetime.timedelta(days=1)
        else:
            start_date = now().date()
        if MemberOrder.objects.filter(
                user=user,
                status__in=('new', 'paid'),
                created_datetime__gt=now() -
                datetime.timedelta(seconds=15 * 60)).exists():
            return Response({'code': 40009, 'detail': _(u'未支付或未确认订单等待处理')})
        end_date = start_date + datetime.timedelta(days=ms.duration)
        order_id = '{0}{1}'.format(int(time.time()), random_number(4))
        if ms.coin_type == 'BTC':
            price = round(float(ms.price) / bitpay_rates.get_usd_rate(), 8)
            notificationURL = '{0}/api/users/payment/callback/'.format(
                Site.objects.get_current(request).domain)

            client = Client(api_uri=settings.BITPAY_API_URL,
                            insecure=False,
                            pem=settings.BITPAY_KEY)

            #         print client.create_token('merchant')
            #         token = client.tokens['merchant']
            #         print token
            token = settings.BITPAY_TOKEN
            data = client.create_invoice({
                "price": price,
                "currency": ms.coin_type,
                "transactionSpeed": "medium",
                "fullNotifications": "true",
                "notificationURL": notificationURL,
                "buyer": {
                    "email": user.email
                },
                "orderId": order_id,
                "token": token
            })
            debug('payment_data', data)
            order = MemberOrder.objects.create(
                order_id=order_id,
                user=user,
                service=ms,
                guid=data.get('guid', ''),
                url=data.get('url'),
                start_date=start_date,
                end_date=end_date,
                coin_type=ms.coin_type,
                coin_amount=price,
                status=data.get('status'),
                exception_status=data.get('exceptionStatus'),
                invoice_id=data.get('id'),
                addresses=data.get('addresses', ''),
                origin=data)
            return Response({
                'invoice_id': order.invoice_id,
                'url': data.get('url')
            })
        elif ms.coin_type == 'BCF':
            price = round(float(ms.price) / settings.BCF_RATE, 8)
            if float(user.balance) < price:
                return Response({'code': 40009, 'detail': _(u'账户BCF余额不足')})
            order = MemberOrder.objects.create(order_id=order_id,
                                               user=user,
                                               service=ms,
                                               guid='',
                                               url='',
                                               start_date=start_date,
                                               end_date=end_date,
                                               coin_type=ms.coin_type,
                                               coin_amount=price,
                                               status='complete',
                                               exception_status='false',
                                               invoice_id='',
                                               addresses='',
                                               origin='')
            user.is_member = True
            user.member_last_date = order.end_date
            user.save()
            UserBalanceRecord.objects.create(user=user,
                                             trans_type='pay_member',
                                             amount=price)
            return Response({'code': 0, 'detail': u'支付成功'})