Example #1
0
    def select_contacts(self):
        logger.info(self.params)
        contacts_id = self.params.get("contacts_id", "")
        m_type = self.params.get("type")
        group_id = self.params.get("group_id", "")
        platform = self.params.get("platform", "")

        result, tmp = [], []
        with sessionCM() as session:
            if contacts_id:
                result = Contacts.find_by_id(session, contacts_id)
            else:
                result = Contacts.find_by_user_id(session,
                                                  self.current_user.id)
                result = [
                    item for item in result if item.platform == platform
                ] if platform else result
                result = [item for item in result
                          if item.type == m_type] if m_type else result
                result = [
                    item for item in result if item.group_id == group_id
                ] if group_id else result
        if not isinstance(result, list):
            result = [result]
        for item in result:
            tmp.append({
                "id": item.id,
                "user_id": item.user_id,
                "name": item.name,
                "origin_id": item.origin_id,
                "group_id": item.group_id,
                "type": item.type
            })

        return {"status": 1, "data": tmp, "message": ""}
Example #2
0
    def update_configuration(self):
        logger.info(self.params)
        kw = {}

        configuration_id = self.params.get("configuration_id", "")
        if not configuration_id:
            return {"status": 0, "data": "必填参数\"configuration_id\"缺失!"}

        if self.params.get("content", ""):
            kw["content"] = self.params.get("content", "")

        if self.params.get("status", ""):
            kw["status"] = self.params.get("status", "")

        if self.params.get("condition", ""):
            kw["condition"] = self.params.get("condition", "")

        if self.params.get("count", ""):
            kw["count"] = self.params.get("count", "")

        with sessionCM() as session:
            configuration = Configuration.find_by_id(
                session, configuration_id=configuration_id)
            if not configuration:
                return {"status": 0, "data": "configuration不存在!"}

            configuration.update(session, configuration, **kw)

        return {"status": 1, "data": "更新成功!"}
Example #3
0
    def select_template(self):
        logger.info(self.params)
        template_id = self.params.get("template_id", "")
        user_id = self.params.get("user_id", "")
        m_type = self.params.get("type", "")
        result, tmp = [], []
        with sessionCM() as session:
            if template_id:
                result = Template.find_by_id(session, template_id)

            if user_id:
                result = Template.find_by_user_id(session, user_id)
                result = [item for item in result
                          if item.type == m_type] if m_type else result
        if not isinstance(result, list):
            result = [result]
        for item in result:
            tmp.append({
                "id": item.id,
                "user_id": item.user_id,
                "title": item.title,
                "content": item.content,
                "type": item.type,
                "condition": item.condition,
            })

        return {"status": 1, "data": tmp}
Example #4
0
    def select_group(self):
        logger.info(self.params)
        group_id = self.params.get("group_id", "")
        user_id = self.params.get("user", "")
        if user_id:
            user_id = self.current_user.id
        else:
            user_id = False

        result, tmp = [], []
        with sessionCM() as session:
            if group_id:
                result = Group.find_by_id(session, group_id)

            if user_id:
                result = Group.find_by_user_id(session, user_id)
        if not isinstance(result, list):
            result = [result]
        for item in result:
            tmp.append({
                "id": item.id,
                "user_id": item.user_id,
                "name": item.name,
            })

        return {"status": 1, "data": tmp}
Example #5
0
    def save_contacts(self):
        logger.info(self.params)
        user_id = self.current_user.id  # self.params.get("user_id", "")
        name = self.params.get("name", "")
        origin_id = self.params.get("origin_id")
        group_id = self.params.get("group_id")
        m_type = self.params.get("type", "normal")  # 可选值 normal, black, white
        platform = self.params.get("platform" "")
        kw = dict()

        if not origin_id:
            return {"status": 0, "message": "参数:\"origin_id\"缺失!"}
        if not platform:
            return {"status": 0, "message": "参数:\"platform\"缺失!"}

        kw["user_id"] = user_id
        kw["name"] = name or ""
        kw["origin_id"] = origin_id
        kw["group_id"] = group_id or ""
        kw["type"] = m_type or ""
        kw["platform"] = platform

        with sessionCM() as session:
            contacts = Contacts.create(session, **kw)
        if contacts:
            return {"status": 1, "message": "创建成功!"}
        else:
            return {"status": 0, "message": "创建失败!"}
Example #6
0
 def get_token(self, code):
     logger.info("WishSDK正在执行获取token的操作")
     try_times = 3
     while try_times > 0:
         res = None
         try:
             url = "https://%s/api/v2/oauth/access_token" % self.domain
             logger.info(u"请求链接为:%s" % url)
             params = dict(grant_type="authorization_code",
                           client_id=self.config.get("client_id"),
                           client_secret=self.config.get("client_secret"),
                           redirect_uri=self.config.get("redirect_uri"),
                           code=code)
             logger.info(u'请求参数:%s' % params)
             res = requests.post(url, params, timeout=20)
             logger.info(u'获取到的数据结果为%s' % res.text)
             logger.info("WishSDK请求执行完毕")
             return res.json()
         except Exception, e:
             try_times -= 1
             if try_times <= 0:
                 logger.error({
                     "response": res.text if res else "授权请求3次均超时",
                     "message": traceback.format_exc(e)
                 })
Example #7
0
    def execute(self):
        logger.info("正在同步店铺ID为%d的smt客服消息" % self.shop.id)
        print("正在同步店铺ID为%d的smt客服消息" % self.shop.id)

        for channel_id in self.sync_message_list("message_center"):
            # sync_smt_customer_detail.delay(self, channel_id, "message_center")
            sync_smt_customer_detail(self, channel_id, "message_center")
Example #8
0
 def get_token(self, code):
     logger.info("AliSDK正在执行获取token的操作")
     try_times = 3
     while try_times > 0:
         res = None
         try:
             url = "https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/getToken/%s" % self.config.get(
                 "app_key")
             logger.info(u"请求链接为:%s" % url)
             params = dict(grant_type="authorization_code",
                           need_refresh_token=True,
                           client_id=self.config.get("app_key"),
                           client_secret=self.config.get("secret_key"),
                           redirect_uri=self.config.get("redirect_uri"),
                           code=code)
             logger.info(u'请求参数:%s' % params)
             res = requests.post(url, params, timeout=20)
             logger.info(u'获取到的数据结果为%s' % res.text)
             logger.info("AliSDK请求执行完毕")
             return json.loads(res.text)
         except Exception, e:
             try_times -= 1
             if try_times <= 0:
                 logger.error({
                     "response": res.text if res else "授权请求3次均超时",
                     "message": traceback.format_exc(e)
                 })
Example #9
0
 def immediately_sync_message(shop):
     time_format = "%Y-%m-%dT%H:%M:%S"
     start = datetime.datetime.now() - timedelta(minutes=30)
     end = datetime.datetime.now() + timedelta(minutes=5)
     timestamp = start.strftime(time_format) + ";" + end.strftime(
         time_format)
     ##################
     print(shop.platform)
     print(shop.site_id)
     print(shop.account)
     print(shop.owner)
     print(shop.id)
     shop.token = "AgAAAA**AQAAAA**aAAAAA**7HTjVw**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6ABkoGoD5aHpAqdj6x9nY+seQ**94UCAA**AAMAAA**UGJaMLGzkw/V30Q7yrFVpkDxh9+F1v7X7taOlLW6WeEQCY/F6PhqPrjJfFLfw5rg93LNBvSQV4hO/cLtHS1K059mXzg61q4xHToNFk2uK+DdoFlCGbc1BD0TRyZ9zOSw4peeHJy/XUG2GwzkyPSrkBlU8X8e2IcZiyqCEILF0yl0ffDJy4Yz62JZVYCCX7HzvI/39N3ROGcUpCVbmxPE+QJI4a2Xst9ApBikHreVDntERITCRj8FhnnmAoDHGWziGN5GlNOQ40ETGX9GUX9yjK31haSpTpIsJRQBYhYeOYwo+F+LV5mFR55XDtuKD837jmKGZvpwll2pN4XhJfVbU7VFWbqyi2p4ccjxNEKXqmbJSSESvXmhiNK5J5EmAZVxh0BmXnNAHYCMJ1gZ7+sa4shnnzH12wcjMjK679iwXyYiK1YTrNmLNei4UeDFBfb2fzqm+eSDQIBK9g+HX/fZkTssU0O1m59wTeS+9GG6Bu7wTZyjU5cbCbjlQl6J4xhy4rs+efJLLAx/PfXmAODHgPF1Ai4rF/YYogFy+V9G0SiQJLQz31yxD3uJuDNyVoEB7/voPAvVutUvZcJzw2LAHIETfHG7GNMoHFA1fyLOF76YIZzsxBylxRY/x12gLlHFaKrtNAJRWpbKHO6usD0GMehDd9a/ALlSqHMPolKyaN6RMWEdov/Drq5PYTW+2OmO8GYyzrmCSk8s+OEv4LhLwkL4YBdYZyKoGo7Qf2FTqbfuYOKMblMi2MDACFSYKuvZ"
     shop.site_id = "0"
     ######################
     handler = SyncEbayCustomer(shop, timestamp)
     try:
         logger.info(timestamp)
         for message_dict in handler.execute():
             if not message_dict:
                 continue
             for channel_id, message_ids in message_dict.items():
                 for i in range(0, len(message_ids), 10):
                     sync_customer_detail(handler.shop,
                                          channel_id,
                                          message_ids=message_ids[i:i + 10])
     except Exception, e:
         logger.warning(traceback.format_exc(e))
Example #10
0
    def update_contacts(self):
        logger.info(self.params)
        kw = {}

        contacts_id = self.params.get("contacts_id", "")
        if not contacts_id:
            return {"status": 0, "message": "必填参数\"contacts_id\"缺失!"}

        if self.params.get("name", ""):
            kw["name"] = self.params.get("name", "")

        if self.params.get("origin_id", ""):
            kw["origin_id"] = self.params.get("origin_id", "")

        if self.params.get("group_id", ""):
            kw["group_id"] = self.params.get("group_id", "")

        if self.params.get("type", ""):
            kw["type"] = self.params.get("type", "")

        with sessionCM() as session:
            contacts = Contacts.find_by_id(session, contacts_id=contacts_id)
            if not contacts:
                return {"status": 0, "message": "contacts不存在!"}

            contacts.update(session, contacts, **kw)

        return {"status": 1, "message": "更新成功!"}
Example #11
0
    def save_template(self):
        logger.info(self.params)
        user_id = self.params.get("user_id", "")
        title = self.params.get("title", "")
        content = self.params.get("content")
        m_type = self.params.get("type")
        condition = self.params.get("condition")
        kw = dict()

        if not user_id:
            return {"status": 0, "data": "参数:\"user_id\"缺失!"}
        if not title:
            return {"status": 0, "data": "参数:\"title\"缺失!"}
        if not content:
            return {"status": 0, "data": "\"参数:\"content\"缺失!"}
        if not m_type:
            return {"status": 0, "data": "\"参数:\"type\"缺失!"}
        if not condition:
            return {"status": 0, "data": "\"参数:\"condition\"缺失!"}

        kw["user_id"] = user_id
        kw["title"] = title
        kw["content"] = content
        kw["type"] = m_type
        kw["condition"] = condition

        with sessionCM() as session:
            template = Template.create(session, **kw)
        if template:
            return {"status": 1, "data": "创建成功!"}
        else:
            return {"status": 0, "data": "创建失败!"}
Example #12
0
    def update_template(self):
        logger.info(self.params)
        kw = {}

        template_id = self.params.get("template_id", "")
        if not template_id:
            return {"status": 0, "data": "必填参数\"template_id\"缺失!"}

        if self.params.get("title", ""):
            kw["title"] = self.params.get("title", "")

        if self.params.get("content", ""):
            kw["content"] = self.params.get("content", "")

        if self.params.get("condition", ""):
            kw["condition"] = self.params.get("condition", "")

        with sessionCM() as session:
            template = Template.find_by_id(session, template_id=template_id)
            if not template:
                return {"status": 0, "data": "template不存在!"}

            Template.update(session, template, **kw)

        return {"status": 1, "data": "更新成功!"}
Example #13
0
    def import_from_csv(self):
        """
        从csv中读取联系人信息

        :return:
        """
        logger.info(self.params)
        pass
Example #14
0
 def get_current_user(self):
     try:
         user_id = self.session.get("user_id")
         with sessionCM() as session:
             user = session.query(User).filter(User.id == user_id).one()
             return user
     except Exception, e:
         logger.info(self.request.headers["X-Real-IP"])
         logger.info(e.message)
Example #15
0
def sync_smt_customer_detail(handler, channel_id, msg_source, **kwargs):
    try:
        print (u"AliExpress平台编号为%s的客服通道开始同步..." % str(channel_id))
        handler.sync_message_detail(channel_id, msg_source, **kwargs)
        logger.info(u"AliExpress平台编号为%s的客服通道同步成功" % str(channel_id))
    except Exception, e:
        logger.error(traceback.format_exc(e))
        logger.info(u"AliExpress平台编号为%s的客服通道同步失败,失败原因:%s" % (
            str(channel_id), traceback.format_exc(e)))
Example #16
0
 def str_to_unicode(word):
     """
     将字符串转为unicode
     """
     try:
         return to_unicode(word)
     except Exception, e:
         logger.info(e.message)
         return word.decode("unicode-escape")
Example #17
0
    def post(self, *args, **kwargs):
        logger.info(self.params)
        method_route = {
            "group/save": self.save_group,
        }

        action = args[0]

        self.write(method_route[action]())
        self.write(self.params)
Example #18
0
    def search_message(self):
        """
        通过 搜索条件 进行信息检索

        参数:search_key --> 检索条件 例如:{"buyer_name": "key", "last_msg_content": "key"}
        检索条件关系为‘或’的关系
        :return:
        """
        logger.info(self.params)
        pass
Example #19
0
    def prepare(self, params):
        logger.info(u"请求参数为%s" % params)

        url = self.generate_request_url()
        logger.info(u"请求链接为%s" % url)
        path = self.generate_path()
        signature = api_signature_rule(self.config.get("secret_key"), path,
                                       params)
        params.update(_aop_signature=signature)
        return url, params
Example #20
0
    def post(self, *args, **kwargs):
        logger.info(self.params)
        method_route = {
            "configuration/save": self.save_configuration,
        }

        action = args[1]

        self.write(method_route[action]())
        self.write(self.params)
Example #21
0
    def get(self, *args, **kwargs):
        logger.info(self.params)

        method_route = {
            "group/update": self.update_group,
            "group/delete": self.delete_group,
            "group/list": self.select_group
        }

        action = args[0]

        self.write(method_route[action]())
Example #22
0
    def get(self, *args, **kwargs):
        logger.info(self.params)

        method_route = {
            "contacts/update": self.update_contacts,
            "contacts/delete": self.delete_contacts,
            "contacts/list": self.select_contacts
        }

        action = args[0]

        self.write(method_route[action]())
Example #23
0
    def get(self, *args, **kwargs):
        logger.info(self.params)

        method_route = {
            "template/update": self.update_template,
            "template/delete": self.delete_template,
            "template/list": self.select_template
        }

        action = args[0]

        self.write(method_route[action]())
Example #24
0
    def delete_configuration(self):
        logger.info(self.params)
        user_id = self.params.get("user_id", "")
        configuration_ids = self.params.get("configuration_id", "").split(";")

        with sessionCM() as session:
            if configuration_ids:
                for configuration_id in configuration_ids:
                    Configuration.remove(session,
                                         configuration_id=configuration_id)
                return {"status": 1, "message": "删除成功!"}

            return {"status": 0, "message": "删除失败!"}
Example #25
0
 def sync_message_list(self):
     # 第一步:获取所有消息文件夹
     start, end = self.timestamp.split(";")
     end = datetime.datetime.strptime(end, "%Y-%m-%dT%H:%M:%S")  # - datetime.timedelta(days=1)
     if not start:
         start = end - datetime.timedelta(days=365)
     else:
         start = datetime.datetime.strptime(start, "%Y-%m-%dT%H:%M:%S")  # - datetime.timedelta(days=1)
         start = start.strftime("%Y-%m-%dT%H:%M:%S")
         end = end.strftime("%Y-%m-%dT%H:%M:%S")
     logger.info("eBay-%d:正在获取FolderSummary" % self.shop.id)
     print("eBay-%d:正在获取FolderSummary" % self.shop.id)
     result = self.msg_handler.get_my_messages("ReturnSummary", start_time=start, end_time=end)
     print result, type(result)
     # 第二步:获取每个文件夹下的Message简要信息,从而获取MessageIDs
     for summary in result["Summary"]["FolderSummary"]:
         logger.info("eBay-%d:正在获取FolderID为%s的MessageList" % (self.shop.id, summary["FolderID"]))
         print("eBay-%d:正在获取FolderID为%s的MessageList" % (self.shop.id, summary["FolderID"]))
         if summary["FolderID"] == "2":
             continue
         yield self._get_messages_in_folder(summary["FolderID"], start, end)
         logger.info("eBay-%d:FolderID为%s的MessageList同步完成" % (self.shop.id, summary["FolderID"]))
         print ("eBay-%d:FolderID为%s的MessageList同步完成" % (self.shop.id, summary["FolderID"]))
         logger.info("-" * 30)
         print ("-" * 30)
Example #26
0
    def sync_today(self):
        from morph.task.sync_customer_detail import sync_customer_detail
        logger.info("正在同步店铺ID为%d的eBay客服消息" % self.shop.id)
        print("正在同步店铺ID为%d的eBay客服消息" % self.shop.id)

        for message_dict in self.sync_message_list():
            if not message_dict:
                continue
            for channel_id, message_ids in message_dict.iteritems():
                for i in xrange(0, len(message_ids), 10):
                    sync_customer_detail(
                        self, channel_id,
                        message_ids=message_ids[i: i + 10]
                    )
Example #27
0
    def sync_awaiting_evaluation_list(self):
        total_page = 1
        current_page = 0
        page_size = 100
        while True:
            current_page += 1
            logger.info("current_page: %d " % current_page)
            logger.info("total_page: %d " % total_page)
            if current_page > total_page:
                break

            result = self.elt_handler.get_awaiting_feedback(current_page=current_page, page_size=page_size)
            # print result
            if result.get("Ack") == "Success":
                items_awaiting_feed_back = result["ItemsAwaitingFeedback"]
                # print items_awaiting_feed_back
                total_page = int(items_awaiting_feed_back["PaginationResult"]["TotalNumberOfPages"])
                print "tmp_total_page: %s " % total_page
                if not int(total_page):
                    break
                transactions = items_awaiting_feed_back["TransactionArray"]["Transaction"]
                if isinstance(transactions, dict):
                    transactions = [transactions]

                with sessionCM() as session:
                    for transaction in transactions:
                        t_item = transaction.get("Item", {})
                        buyer = transaction.get("Buyer", {})
                        if transaction.get("FeedbackReceived", ""):
                            status = "seller"
                        elif transaction.get("FeedbackLeft", ""):
                            status = "buyer"
                        else:
                            status = "all"

                        evaluation = Evaluation.find_by_order_line_id(session, transaction["OrderLineItemID"])
                        kw = {
                            "shop_id": self.shop.id,
                            "order_line_item_id": transaction["OrderLineItemID"],
                            "item_id": t_item.get("ItemID", ""),
                            "item_title": t_item.get("Title", ""),
                            "status": status,
                            "buyer_id": buyer.get("UserID", ""),
                            "seller_content": ""
                        }
                        evaluation = Evaluation.update(session, evaluation, **kw)
                        # print '-'*60
                        # print evaluation.id, evaluation.buyer_id, evaluation.status, evaluation.order_line_item_id
                        # print evaluation.item_id, evaluation.item_title, evaluation.seller_content
        print "同步完成!"
Example #28
0
def sync_customer_detail(shop, channel_id, **kwargs):
    try:
        method_route = {
            "eBay": SyncEbayCustomer,
            "Wish": SyncWishCustomer,
        }
        handler = method_route[shop.platform](shop)
        handler.sync_message_detail(channel_id, **kwargs)
        logger.info(u"%s平台编号为%s的客服消息通道同步成功,IDs=%s" % (
            shop.platform, str(channel_id), str(kwargs["message_ids"])))
    except Exception, e:
        logger.error(traceback.format_exc(e))
        logger.info(u"%s平台编号为%s的客服消息通道同步失败,IDs=%s,失败原因:%s" % (
            shop.platform, str(channel_id), str(kwargs["message_ids"]), traceback.format_exc(e)))
Example #29
0
 def get_new_token(self, refresh_token):
     logger.info("WishSDK正在执行刷新token的操作")
     url = "https://%s/api/v2/oauth/refresh_token" % self.domain
     logger.info(u"请求链接为:%s" % url)
     params = dict(
         grant_type="refresh_token",
         client_id=self.config.get("client_id"),
         client_secret=self.config.get("client_secret"),
         refresh_token=refresh_token,
     )
     logger.info(u'请求参数:%s' % params)
     res = requests.post(url, params, timeout=20)
     logger.info(u'获取到的数据结果为%s' % res.text)
     logger.info("WishSDK请求执行完毕")
     return res.json()
Example #30
0
 def get_image_content(cls, pic_url):
     url = "http:" + pic_url if pic_url.startswith("//") else pic_url
     headers = {
         "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36"
     }
     try_times = 2
     while try_times > 0:
         try:
             res = requests.get(url, headers=headers, timeout=15)
             if res.status_code != 200:
                 return False
             return res.content
         except Exception, e:
             logger.info(e.message)
             try_times -= 1