def EBAY_LEAVE_FEEDBACK(opener, buyer): url = [ 'http://k2b-bulk.ebay.com.hk/ws/eBayISAPI.dll?MfcISAPICommand=SalesRecordConsole&', 'currentpage=SCSold&pageNumber=1&searchField=BuyerId&searchValues=<USER_ID>&StoreCategory=', '-4&Status=All&Period=Last122Days&searchSubmit=%E6%90%9C%E5%B0%8B&goToPage=' ] url = ''.join(url) url = url.replace('<USER_ID>', buyer) response = Firefox(opener).get(url=url, max_try_times=10) soup = BeautifulSoup(response) tag_a = soup.find_all('a', href=re.compile(r'http://.*?orderid=\d*')) orderids = map( lambda t: re.compile(r'http://.*?orderid=(\d*)').findall(str(t['href']) )[0], tag_a) orderids = list(set(orderids)) url = 'http://k2b-bulk.ebay.com.hk/ws/eBayISAPI.dll' base_form = 'MfcISAPICommand=LeaveCustomFeedback&urlstack=5508%7CPeriod_Last122Days%7CsearchField_BuyerId%'\ '7CpageNumber_1%7Ccurrentpage_SCSold%7CsearchValues_noname%7C&orderid=<place_holder>&commenttype=0'\ '&commentselected=0&customcomment=&LeaveFeedback=%E7%95%99%E4%B8%8B%E4%BF%A1%E7%94%A8%E8%A9%95%E5%83%B9' for i in orderids: form = base_form.replace('<place_holder>', str(i)) response = Firefox(opener).post(url=url, form=form, max_try_times=3) return True
def OA_ORDER_GET_ORDER_INFO(opener, order): order = _is_valid_order(order) def tag_filter(tag): if tag.name == 'td' and tag.get('class') == [ 'category' ] and not tag.next_element.name in ['select', 'input']: return True if tag.has_attr('selected') and tag['selected'] == 'selected': return True if tag.name == 'input' and tag.get('type') == 'text': print tag.get('value') tag.string = tag.get('value') return True url = 'http://banggood.sellercube.com/BillDetail/index?id=%s' % order response = Firefox(opener).clean_get(url=url, max_try_times=6) soup = BeautifulSoup(response) resultset = soup.find_all(tag_filter) ss = models.build_order_info_object(SoupResultSet=resultset, order=order) return ss
def OA_CONTACT_BUYER_QUERY(opener, store, contactStatus): url = 'http://banggood.sellercube.com/order/ListGridNew?state=11&setting=&isIndexRequest=1' form = { 'productManagerId': '0', 'ContactProgress': contactStatus, 'rp': '300', 'sortname': '', 'orderType': '', 'searchField': 'Id', 'FlytInCompany': '', 'HandUser': '', 'productSpecialeId': '0', 'countrys': '', 'processCenterID': '', 'search': '', 'sortorder': 'asc', 'postTypeID': '', 'query': '', 'qtype': '', 'page': '1', 'shopName': store } response = Firefox(opener).post(url=url, form=form, max_try_times=7) J = json.loads(response) Finder = models.ContactBuyerFinder(J) return Finder
def OA_MAIL_REPLY_MAIL(opener, mail_id, content, receiver, forceReply=False): if forceReply: replied = False else: replied = OA_MAIL_IS_MAIL_REPLIED(opener, mail_id) if replied: raise ZeroDivisionError('This mail had already been replied.') assert '@' in receiver, 'Incorrect Receiver %r' % receiver url = 'http://banggood.sellercube.com/MailSend/ReplyContent' if isinstance(content, unicode): content = _encode(content) content = HackedEscape(content) form = { 'receivedId': mail_id, 'replyContent': content, 'toEmail': receiver } response = Firefox(opener).post(url=url, form=form, max_try_times=4) if u'已发送成功' in response: return True return False
def OA_QUERY_MAIL_RECORDS_GET_FINDER(opener, buyer, account): assert '@' in account, 'Incorrect Mail Address' url = 'http://banggood.sellercube.com/MailReceived/SearchGrid' form = { 'Category': '', 'searchStr': 'FromEbayUser', 'search': buyer, 'rp': '300', 'sortname': 'ReceiveTime', 'toEmail': account, 'sortorder': 'DESC', 'query': '', 'endTime': '', 'qtype': '', 'page': '1', 'beginTime': '' } response = Firefox(opener).post(url=url, form=form, max_try_times=10) J = json.loads(response) Finder = models.MailRecordsFinder(J) return Finder
def OA_CHECK_IF_TALKED(opener, buyer, account): url = 'http://banggood.sellercube.com/MailReceived/SearchGrid' form = { 'Category': '', 'searchStr': 'FromEbayUser', 'search': buyer, 'rp': '20', 'sortname': 'ReceiveTime', 'toEmail': account, 'sortorder': 'DESC', 'query': '', 'endTime': '', 'qtype': '', 'page': '1', 'beginTime': '' } response = Firefox(opener).post(url, form, max_try_times=3) J = json.loads(response) Finder = models.MailRecordsFinder(J) if Finder.total > 0: return True return False
def EBAY_CHK_IF_SENT_MSG(opener, buyer): _lock.acquire() global _Global_Buyer_List headers = { 'Origin': 'http://mesgmy.ebay.com.hk', 'Referer': 'http://mesgmy.ebay.com.hk/ws/eBayISAPI.dll?ViewMyMessages&&ssPageName=STRK:MEMM:LNLK&FolderId=1&CurrentPage=MyeBayMyMessagesSent&_trksid=p3984.m2295.l3929' } url = 'http://mesgmy.ebay.com.hk/V4Ajax' form = 'svcid=MY_MSG_SERVICE&stok=351778162&pId=5039&v=0&reqttype=JSON&resptype=JSON&clientType=Safari:537:&request=%7B%22mode%22%3A12%2C%22currentView%22%3A%22%22%2C%22folderId%22%3A1%7D' if (not _Global_Buyer_List) or (len(_Global_Buyer_List) < 100): #need to get buyer list from eBay #and store it. print('Getting list') response = Firefox(opener, c_lock=_c_lock).post(url=url, form=form, headers=headers, encode_to='utf-8', max_try_times=6) _Global_Buyer_List = response print('Getting list [OK]') _lock.release() if not buyer in _Global_Buyer_List: return False else: return True
def EBAY_SEND_MESSAGE(opener, message, buyer, item): '''注意这里的链接,应该传入openers自动匹配''' url = 'http://contact.ebay.com.hk/ws/eBayISAPI.dll?ContactUserNextGen' headers = { 'Referer': 'http://contact.ebay.com.hk/ws/eBayISAPI.dll?ContactUserNextGen&iId=%s&recipient=%s' % (item, buyer), 'Origin': 'http://contact.ebay.com.hk' } form = { 'imageUrls': '', 'msg_cnt': message, 'cat': '-99', 'msg_cnt_cnt': message, 'iId': item, 'actn': 'submit', 'ccSender': 'on', 'recipient': buyer } ok_mark = u'<title>訊息已寄出</title>' response = Firefox(opener, c_lock=_c_lock).post(url, form, headers=headers, max_try_times=3) if ok_mark in response: return True else: return False
def OA_NEED_CARE_SET_OK(opener, rid): '''Here is buggy''' url = 'http://banggood.sellercube.com/eBayCaseAttempt/IsResponedUser?ids=%s' % rid form = {} response = Firefox(opener).post(url, form, max_try_times=3) ok_mark = u'设置已回复成功' if ok_mark in response: return True else: return False
def OA_CONTACT_BUYER_CHECK_STOCK(opener, order): url = 'http://banggood.sellercube.com/order/GetOrderStock' form = {'ids': order} response = Firefox(opener).post(url=url, form=form, max_try_times=7) if u'不缺货' in response: return True return False
def OA_ORDER_MOVE_TO(opener, order, to): order = _is_valid_order(order) url = 'http://banggood.sellercube.com/order/UpdateStatus?status=%s&ids=%s' % ( to, order) form = {} response = Firefox(opener).post(url=url, form=form, max_try_times=3) if 'true' in response: return True else: return False
def LoginOA(user, password): import cookielib url = 'http://banggood.sellercube.com/Start/Login' form = {'email': user, 'password': password, 'rememberMe': 'true'} cookie_jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar)) response = Firefox(opener).post(url=url, form=form, encode_to='gbk') print(response) return opener
def OA_ORDER_GET_ORDER_HISTORY(opener, order): url = 'http://banggood.sellercube.com/BillDetail/ViewOperationalHistory' form = {'orderId': order} response = Firefox(opener).post(url=url, form=form, max_try_times=6) if 'noData' in response: return None J = json.loads(response) return J
def OA_ORDER_GET_ORDER_DETAIL_LIST(opener, order): order = _is_valid_order(order) url = 'http://banggood.sellercube.com/BillDetail/GetOrderDetailById' form = {'orderId': order} response = Firefox(opener).post(url=url, form=form, max_try_times=6) soup = BeautifulSoup(response) L = models.build_order_detail_containers(soup) return L
def EBAY_GET_FEEDBACKS_BUYER_ITEM_REPLY(opener, store, negative=False): headers = { 'Host': 'feedback.ebay.com.hk', 'Referer': 'http://feedback.ebay.com.hk/' } if negative: which = 'negative' else: which = 'neutral' url = [ 'http://feedback.ebay.com.hk/ws/eBayISAPI.dll?', 'ViewFeedback2&userid=%s&iid=-1&de=off&', 'items=100&which=%s&interval=30&&page=1' ] url = ''.join(url) url = url % (store, which) REG = r'^(?!%s)' % store response = Firefox(opener).get(url, headers=headers) soup = BeautifulSoup(response) comments = soup('td', class_='fbOuterAddComm', nowrap=False, text=True) replies = soup('ul', class_='addlc') authors = [ i.find_next('span', class_='mbg-nw', text=re.compile(REG)) for i in comments ] items = [ i.find_next('a', href=re.compile(r'http://.*?/itm/.*?/\d*')) for i in comments ] authors = map(lambda t: str(t.text), authors) items = map( lambda t: re.compile(r'http://.*?/itm/.*?/(\d*)').findall( str(t['href']))[0], items) comments = map(lambda t: t.text.encode('utf-8', 'ignore'), comments) replies = map(lambda t: t.text.encode('utf-8', 'ignore'), replies) if len(comments) < 10: raise ValueError('Too less comments!') result = zip(comments, replies, authors, items) return result
def OA_INTERCEPT_ORDER(opener, order, reason): assert isinstance(reason, unicode), 'Need unicode' encoded_reason = _encode(reason) url = 'http://banggood.sellercube.com/Order/RequestBlockSet?Length=15' form = {'state': '', 'BlockReason': encoded_reason, 'orderIDs': order} response = Firefox(opener).post(url, form) ok_mark = u'self.parent.tb_remove()' if ok_mark in response: return True else: return False
def get_oa_opener(): url = 'http://banggood.sellercube.com/Start/Login' data = 'email=610591830%40qq.com&password=topsecrett1&rememberMe=true' cookie_jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar)) headers = {'User-Agent': ua} response = Firefox(opener).post(url=url, form=data, headers=headers, encode_to='gbk') print(response) return opener
def OA_MAIL_IS_MAIL_REPLIED(opener, mail_id): url = 'http://banggood.sellercube.com/MailReceived/IsReplied' form = {'id': mail_id} response = Firefox(opener).post(url=url, form=form, max_try_times=4) J = json.loads(response) if J == True: isreplied = True elif J == False: isreplied = False else: raise ValueError('Unexpected response') return isreplied
def OA_ORDER_CHANGE_COMMENT_AREA(opener, order, newComment): url = 'http://banggood.sellercube.com/order/setComfirmerRemarkByCell' assert isinstance(newComment, unicode), 'need unicode' newComment = _encode(newComment) form = {'orderID': order, 'remark': newComment} response = Firefox(opener).post(url=url, form=form, max_try_times=3) J = json.loads(response) if J['success'] == True: return True else: return False
def OA_MAIL_TEMPLATES_FINDER(opener): url = 'http://banggood.sellercube.com/MailTemplate/Grid' form = { 'rp': '300', 'sortname': 'Title', 'sortorder': 'asc', 'query': '', 'qtype': '', 'page': '1' } response = Firefox(opener).post(url=url, form=form, max_try_times=7) J = json.loads(response) Finder = models.TemplatesFinder(J) return Finder
def OA_QUERY_MAIL_RECORDS_GET_RESULT(opener, Finder): #z=(this_id,link,title,timestamp,who) L = [] for rec in Finder: this_id, link, title, sender, receiver, time, sent, responder = rec response = Firefox(opener).get(url=link, max_try_times=6, encode_to='utf-8') if 'R' in this_id: #Received from eBay, html L.append((response, 'R')) else: #Sent from OA L.append((response, 'S')) return L
def OA_ORDER_QUERY_ORDER(opener, search_key, search_field='', store=''): if not search_field: if '@' in search_key: search_field = const.FIELD_EMAIL elif ' ' in search_key: search_field = const.FIELD_RECEIVER elif len(search_key) == 17: search_field = const.FIELD_PAYPAL elif len(search_key) == const.valid_order_length: search_field = const.FIELD_ORDER elif (search_key[:2].isalpha() and search_key[-2:].isalpha())\ and (search_key[:2].isupper() and search_key[-2:].isupper()): search_field = const.FIELD_TRACKING else: search_field = const.FIELD_BUYER url = 'http://banggood.sellercube.com/order/ListGridMore?state=all&setting=&isIndexRequest=1' form = { 'search': search_key, 'rp': '300', 'sortname': '[state]', 'isComplain': '是否投诉', 'productManagerId': '0', 'searchField': search_field, 'FlytInCompany': '', 'productSpecialeId': '0', 'countrys': '', 'processCenterID': '', 'sortorder': 'asc', 'postTypeID': '', 'query': '', 'qtype': '', 'page': '1', 'shopName': store } response = Firefox(opener).post(url=url, form=form, max_try_times=10) J = json.loads(response) Finder = models.SearchResultFinder(J) return Finder
def OA_ORDER_CONTACT_BUYER(opener, order, text): base_url = 'http://banggood.sellercube.com/Order/ContactBuyer?orderId=<ph>'\ '&contactProgressc=%E6%9C%AA%E8%81%94%E7%B3%BB&keepThis=true&' url = base_url.replace('<ph>', order) if not isinstance(text, unicode): raise ValueError('Need unicode') text = _encode(text) form = {'contactText': text, 'orderId': order, 'contactProgressc': '未联系'} response = Firefox(opener).post(url=url, form=form, max_try_times=3) ok_mark = "removeContactBuyer('%s')" % order if ok_mark in response: return True else: return False
def OA_REFUND_CHECK_STATUS(opener, order, key=None): url = 'http://banggood.sellercube.com/Refund/GetOrderCurrency' form = {'OrderID': order} response = Firefox(opener).post(url=url, form=form, max_try_times=6) J = json.loads(response) IsRepeatedSent = J['IsRepeatSent'] Total = J['TotalAmount'] Currency = J['Currency'] IsRefundedBefore = J['IsRefunded'] PaypalName = J['PaypalName'] if key: index = 'IsRepeatedSent, Total, Currency, IsRefundedBefore, PaypalName'.split( ', ').index(key) return [IsRepeatedSent, Total, Currency, IsRefundedBefore, PaypalName][index] return IsRepeatedSent, Total, Currency, IsRefundedBefore, PaypalName
def OA_MAIL_INBOX_GET_FINDER(opener, who=u'', account=''): assert isinstance(who, unicode) if account: assert '@' in account who = _encode(who) url = 'http://banggood.sellercube.com/MailReceived/Grid?folderId=' #XXXXX form = { 'IsOver': '', 'Category': '', 'search': '', 'rp': '20', 'sortname': 'ReceiveTime', 'isNew': 'all', 'productManagerId': '0', 'searchField': '', 'toEmail': account, 'isIsRead': '', 'dispatchUserName': who, 'ProductSpeciale': '0', 'sortorder': 'asc', 'beginTime': '', 'timeField': '', 'query': '', 'endTime': '', 'qtype': '', 'page': '1', 'isReplay': '0' } response = Firefox(opener).post(url=url, form=form, max_try_times=7) J = json.loads(response) Finder = models.MailInboxFinder(J) return Finder
def EBAY_RETURN_IS_NO_NEED_REPLY(openers, return_link): url = return_link simple = _simple_host(url) opener = openers.find(url) new_url = None def callback_f(_url): new_url = _url return True headers = { 'Host': 'postorder.%s' % simple, 'Referer': 'http://banggood.sellercube.com/ebaycase', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } #decoded response response = Firefox(opener, c_lock=_c_lock, redirect_callback=callback_f).get(url, headers=headers) if new_url: log.warning('Redirecting...') return EBAY_RETURN_IS_NO_NEED_REPLY(return_link=new_url, openers=openers) no_need_mark = u'You sent a message' if no_need_mark in response: log.debug('NO NEED [%s]' % url) return True else: log.debug('YOU NEED[%s]' % url) return False
def OA_NEED_CARE_FIND_BUYER(opener, store): '''This is buggy''' store = '842' url = 'http://banggood.sellercube.com/eBayCaseAttempt/Grid' form = { 'ItemID': '', 'rp': '300', 'sortname': 'ImportTime', 'Site': '', 'DispatchUserID': '0', 'sortorder': 'desc', 'eBayName': store, 'IsRespone': '0', 'BuyerUserID': '', 'query': '', 'TurnOverUser': '', 'qtype': '', 'page': '1' } response = Firefox(opener).post(url, form) #id #item #buyer RE = re.compile( r'"id":"(\w*?)","cell":\["homesale_estore","(\d*?)",".*?",".*?",".*?","(.*?)"' ) RLT = RE.findall(response) logger.info(str(RLT)) return RLT
def OA_REFUND_QUERY_BY_ORDER(opener, order, phase=None): if not phase in ['confirmed', 'unconfirmed', 'finished', None]: raise ValueError('Phase not correct!') order = _is_valid_order(order) d = {} url = 'http://banggood.sellercube.com/Refund/ListFinished' form = { 'orderID': order, 'StandardCode': '', 'PaypalTransactionIdIsNull': '', 'endDate': '', 'startDate': '', 'ProcessCenter': '', 'X-Requested-With': 'XMLHttpRequest', 'ddOrderTypes': '', 'ProblemType': '', 'sord': 'asc', 'paymentType': '', 'PorductManager': '0', 'ProductSpeciale': '', 'sidx': 'Amount', 'createUser': '', 'SalePlatform': '', 'flytUserID': '', 'ListPaypalNames': '' } d['finished'] = (url, form) url = 'http://banggood.sellercube.com/Refund/ListIndex' form = { 'orderID': order, 'startDate': '', 'endDate': '', 'ProblemType': '', 'paymentType': '', 'X-Requested-With': 'XMLHttpRequest', 'CreateUser': '', 'flytUserID': '', 'ListPaypalNames': '' } d['unconfirmed'] = (url, form) url = 'http://banggood.sellercube.com/Refund/ListApproved' form = { 'orderID': order, 'startDate': '', 'endDate': '', 'sidx': 'Amount', 'sord': 'asc', 'paymentType': '', 'X-Requested-With': 'XMLHttpRequest', 'CreateUser': '', 'flytUserID': '', 'ListPaypalNames': '' } d['confirmed'] = (url, form) if not phase: z = [] for phase in ['confirmed', 'unconfirmed', 'finished']: url, form = d[phase] response = Firefox(opener).clean_post(url=url, form=form, max_try_times=7) soup = BeautifulSoup(response) L = models.bulid_refund_info(soup, phase) z.extend(L) return z else: url, form = d[phase] response = Firefox(opener).clean_post(url=url, form=form, max_try_times=7) soup = BeautifulSoup(response) L = models.bulid_refund_info(soup, phase) return L
def OA_REFUND_CREATE_NEW(opener, order, amount, currency, reason_TYPE, reason_CN, reason_EN, existed=False, PayPalAcc=None): if isinstance(amount, (str, unicode)): amount = float(amount) min_amount = const.min_amount max_amount = const.max_amount if PayPalAcc == None: IsRepeatedSent, Total, Currency, refunded, PaypalName = OA_REFUND_CHECK_STATUS( opener, order) PayPalAcc = PaypalName if existed: exist_code = 1 else: exist_code = 0 order = _is_valid_order(order) if not min_amount < amount < max_amount: raise ValueError('Amount not ok %r' % amount) if not isinstance(reason_CN, unicode): raise ValueError('Encoding Not Unicode %r' % type(reason_CN)) assert currency, 'Currency not ok: %r' % currency if PayPalAcc: assert '@' in PayPalAcc, 'Not a valid PayPal account' encoded_reason_CN = _encode(reason_CN) url = 'http://banggood.sellercube.com/Refund/Add?keepThis=true&' form = { 'OrderID': order, 'Amount': amount, 'Currency': currency, 'OrderProblemType': reason_TYPE, 'Reason': encoded_reason_CN, 'ReasonEn': reason_EN, 'isOrderExist': exist_code, 'PaypalName': PayPalAcc } response = Firefox(opener).post(url, form, max_try_times=1) if not response: logger.warning('Response is None') ok_mark = u'success' if ok_mark in response: logger.info('success') return '[SUCCESS]' else: logger.debug('[Failed?] %r' % order) return '[FAILED]'