def new_recipient_digital_key(self, recipient, data): """ add recipient with 'clé digitale' authentication """ # post recipient data, sending app notification with same request data['typeEnvoi'] = 'AF' self.add_recip.go(data=json.dumps(data), headers={'Content-Type': 'application/json'}) recipient = self.page.get_recipient(recipient) # prepare data for polling assert recipient._id_transaction polling_data = {} polling_data['idBeneficiaire'] = recipient._transfer_id polling_data['idTransaction'] = recipient._id_transaction polling_data['typeActivation'] = 2 timeout = time.time() + 300.00 # float(second), like bnp website # polling while time.time() < timeout: time.sleep(5) # like website self.activate_recip_digital_key.go( data=json.dumps(polling_data), headers={'Content-Type': 'application/json'}) if self.page.is_recipient_validated(): break else: raise AddRecipientTimeout() return recipient
def login(self, login, password): payload = {'validate': {'PASSWORD_LOOKUP': [{'id': self.form_id, 'login': login.encode(self.browser.ENCODING).upper(), 'password': password.encode(self.browser.ENCODING), 'type': 'PASSWORD_LOOKUP' }] } } req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) self.logger.debug(doc) if 'phase' in doc and doc['phase']['state'] == 'TERMS_OF_USE': # Got: # {u'phase': {u'state': u'TERMS_OF_USE'}, u'validationUnits': [{u'LIST_OF_TERMS': [{u'type': u'TERMS', u'id': u'b7f28f91-7aa0-48aa-8028-deec13ae341b', u'reference': u'CGU_CYBERPLUS'}]}]} payload = {'validate': doc['validationUnits'][0]} req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) self.logger.debug(doc) if ('phase' in doc and doc['phase']['previousResult'] == 'FAILED_AUTHENTICATION') or \ doc['response']['status'] != 'AUTHENTICATION_SUCCESS': raise BrowserIncorrectPassword() self.browser.location(doc['response']['saml2_post']['action'], urllib.urlencode({'SAMLResponse': doc['response']['saml2_post']['samlResponse']}))
def new_recipient_digital_key(self, recipient, data): """ add recipient with 'clé digitale' authentication """ # post recipient data, sending app notification with same request data['typeEnvoi'] = 'AF' self.add_recip.go(data=json.dumps(data), headers={'Content-Type': 'application/json'}) recipient = self.page.get_recipient(recipient) # prepare data for polling assert recipient._id_transaction polling_data = {} polling_data['idBeneficiaire'] = recipient._transfer_id polling_data['idTransaction'] = recipient._id_transaction polling_data['typeActivation'] = 2 timeout = time.time() + 300.00 # float(second), like bnp website # polling while time.time() < timeout: time.sleep(5) # like website self.activate_recip_digital_key.go( data = json.dumps(polling_data), headers = {'Content-Type': 'application/json'} ) if self.page.is_recipient_validated(): break else: raise AddRecipientTimeout() return recipient
def download_document(self, document): token = self.get_csrf_token() bills_informations = self.bill_informations.go( headers={ 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/plain, */*' }, data=json.dumps({ 'bpNumber': document._bp, 'csrfToken': token, 'docId': document._doc_number, 'docName': 'FACTURE', 'numAcc': document._num_acc, 'parNumber': document._par_number })).get_bills_informations() self.bill_download.go(csrf_token=token, dn='FACTURE', pn=document._par_number, di=document._doc_number, bn=bills_informations.get('bpNumber'), an=bills_informations.get('numAcc')) # sometimes we land to another page that tell us, this document doesn't exist, but just sometimes... # make sure this page is the right one to avoid return a html page as document if not self.bill_download.is_here(): raise BrokenPageError() return self.page.content
def fetch_products(self, ids): ids = list(set(ids) - set(self.products.keys())) page = self.product.open( data=json.dumps(ids), sessionId=self.sessionId, headers={'Content-Type': 'application/json;charset=UTF-8'}) self.products.update(page.get_products())
def inner(browser, *args, **kwargs): if (not hasattr(browser, 'logged') or (hasattr(browser, 'logged') and not browser.logged)) and \ (not hasattr(browser, 'page') or browser.page is None or not browser.page.logged): browser.do_login() if browser.logger.settings.get('export_session'): browser.logger.debug('logged in with session: %s', json.dumps(browser.export_session())) return func(browser, *args, **kwargs)
def login(self, login, password): payload = { 'validate': { 'PASSWORD_LOOKUP': [{ 'id': self.form_id, 'login': login.encode(self.browser.ENCODING).upper(), 'password': password.encode(self.browser.ENCODING), 'type': 'PASSWORD_LOOKUP' }] } } req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) self.logger.debug(doc) if ('phase' in doc and doc['phase']['previousResult'] == 'FAILED_AUTHENTICATION') or \ doc['response']['status'] != 'AUTHENTICATION_SUCCESS': raise BrowserIncorrectPassword() self.browser.location( doc['response']['saml2_post']['action'], urllib.urlencode({ 'SAMLResponse': doc['response']['saml2_post']['samlResponse'] }))
def search_housings(self, query, cities): self.update_header() data = {} data['rubrique'] = TYPES.get(query.type) data['prix_max'] = query.cost_max or None data['surface_min'] = query.area_min or None if len(cities) > 1: data['rayon'] = None else: data['rayon'] = 100 data['CategorieMode'] = None data['CategorieMaison'] = None data['Kilometrage'] = None data['top'] = 50 data['order_by'] = 5 data['sort_order'] = 1 data['lstNbPieces'] = [query.nb_rooms or 0] data['pageNumber'] = 1 for city in cities: data['localisation'] = {} data['localisation']['localisationid'] = city.id data['localisation']['label'] = city.name data['localisation']['localisationType'] = 5 data['localisationType'] = 5 data['lstLocalisationId'] = str(city.id) for house_type in query.house_types: data['lstTbien'] = RET.get(house_type) for house in self.search_house.go(data=json.dumps(data)).iter_houses(): if (empty(query.cost_min) or house.cost >= query.cost_min) and \ (empty(query.area_max) or house.area <= query.area_max): yield house
def search_housings(self, type, cities, nb_rooms, area_min, area_max, cost_min, cost_max, house_types): if type not in self.TYPES: raise TypeNotSupported self.update_header() result = self.form_item.open(data="{'rubrique': '%s'}" % self.TYPES.get(type)) biens = json.loads(json.loads(result.content)['d']) for house_type in house_types: id_type = self.RET[type].get(house_type, '1') data = {} data['rubrique'] = self.TYPES.get(type) data['ach_id'] = None data['FromMoteur'] = "true" for bien in biens: if bien['Idchoix'] == int(id_type): data['lstSSTbien'] = bien['SsTypebien'] data['lstTbien'] = bien['TypeBien'] data['Caracteristique'] = bien['Idchoix'] data['OrigineAlerte'] = "SaveSearchMoteurHome" data['pays'] = "fra" data['prix_min'] = cost_min if cost_min and cost_min > 0 else None data['prix_max'] = cost_max if cost_max and cost_max > 0 else None data['lstThemes'] = "" min_rooms = nb_rooms if nb_rooms else None if not min_rooms: data['lstNbPieces'] = 0 else: data['lstNbPieces'] = ','.join('%s' % n for n in range(min_rooms, 6)) data['lstNbChambres'] = None data['surface_min'] = area_min if area_min else None # var localisationType = { "all": -1, "ville": 5, "region": 2, "departement": 4, "pays": 1, "regionUsuelle": 3 }; data['localisationType'] = 5 data['reference'] = '' data['rayon'] = 0 data['localisation_id_rayon'] = None data['lstLocalisationId'] = ','.join(cities) data['photos'] = 0 data['colocation'] = '' data['meuble'] = '' data['pageNumber'] = 1 data['order_by'] = 1 data['sort_order'] = 1 data['top'] = 25 data['SaveSearch'] = "false" data['EmailUser'] = "" data['GSMUser'] = "" self.search.go(data="{'p_SearchParams':'%s', 'forcealerte':'0'}" % json.dumps(data)) data = '{pageIndex: 1,source:"undefined"}' for item in self.search_result.go(data=data).iter_housings(): yield item
def send_code(self, recipient, **params): # depending on whether recipient is a weboob or a budgea backend object. _id = recipient.webid if hasattr(recipient, 'webid') else recipient.id data = {} data['idBeneficiaire'] = _id data['typeActivation'] = 1 data['codeActivation'] = params['code'] return self.activate_recip.go(data=json.dumps(data), headers={'Content-Type': 'application/json'}).get_recipient(recipient)
def open(self, *args, **kwargs): if isJSON(kwargs.get('data')): kwargs['data'] = json.dumps(kwargs['data'][1]) if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Content-Type'] = 'application/json' return super(JsonBrowserMixin, self).open(*args, **kwargs)
def open(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) if not 'headers' in kwargs: kwargs['headers'] = {} kwargs['headers']['Content-Type'] = 'application/json' return super(APIBrowser, self).open(*args, **kwargs)
def login(self, login, password): payload = { 'validate': { self.form_id[0]: [{ 'id': self.form_id[1], 'login': login.upper(), 'password': password, 'type': 'PASSWORD_LOOKUP', }] } } url = self.request_url + '/step' headers = {'Content-Type': 'application/json'} r = self.browser.open(url, data=json.dumps(payload), headers=headers) doc = r.json() self.logger.debug('doc = %s', doc) if 'phase' in doc and doc['phase']['state'] == 'TERMS_OF_USE': # Got: # {u'phase': {u'state': u'TERMS_OF_USE'}, u'validationUnits': [{u'LIST_OF_TERMS': [{u'type': u'TERMS', u'id': u'b7f28f91-7aa0-48aa-8028-deec13ae341b', u'reference': u'CGU_CYBERPLUS'}]}]} if 'reference' in doc['validationUnits'][0]: del doc['validationUnits'][0]['reference'] elif 'reference' in doc['validationUnits'][0]['LIST_OF_TERMS'][0]: del doc['validationUnits'][0]['LIST_OF_TERMS'][0]['reference'] payload = {'validate': doc['validationUnits'][0]} url = self.request_url + '/step' headers = {'Content-Type': 'application/json'} r = self.browser.open(url, data=json.dumps(payload), headers=headers) doc = r.json() self.logger.debug('doc = %s', doc) if 'phase' in doc and doc['phase']['state'] == "ENROLLMENT": raise ActionNeeded() if (('phase' in doc and doc['phase']['previousResult'] == 'FAILED_AUTHENTICATION') or doc['response']['status'] != 'AUTHENTICATION_SUCCESS'): raise BrowserIncorrectPassword() data = {'SAMLResponse': doc['response']['saml2_post']['samlResponse']} self.browser.location(doc['response']['saml2_post']['action'], data=data)
def build_request(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Content-Type'] = 'application/json' return super(APIBrowser, self).build_request(*args, **kwargs)
def _issue_post_body(self, issue): data = {'title': issue.title, 'body': issue.body} if issue.assignee: data['assignee'] = issue.assignee.id if issue.version: data['milestone'] = issue.version.id if issue.status: data['state'] = issue.status.name # TODO improve if more statuses are implemented return json_module.dumps(data)
def post_message(self, thread_id, content): data = {'body': content, 'profile_tab': '', 'receiverid': thread_id, 'service': 'mailbox', 'source': 'desktop_global'} self.message_send.go(params={'access_token': self.access_token}, data=json.dumps(data))
def send_code(self, recipient, **params): """ add recipient with sms otp authentication """ data = {} data['idBeneficiaire'] = recipient._transfer_id data['typeActivation'] = 1 data['codeActivation'] = params['code'] return self.activate_recip_sms.go(data=json.dumps(data), headers={'Content-Type': 'application/json'}).get_recipient(recipient)
def create_json_data(self, method, parameters, token): data = {'header': self.HEADER} data['header']['client'] = self.GROOVESHARK_CONSTANTS[0] data['header']['clientRevision'] = self.GROOVESHARK_CONSTANTS[1] if (token is not None): data['header']['token'] = token data['method'] = method data['parameters'] = parameters return simplejson.dumps(data)
def create_json_data(self, method, parameters, token): data = {} data['header'] = self.HEADER data['header']['client'] = self.GROOVESHARK_CONSTANTS[0] data['header']['clientRevision'] = self.GROOVESHARK_CONSTANTS[1] if(token is not None): data['header']['token'] = token data['method'] = method data['parameters'] = parameters return simplejson.dumps(data)
def login(self, login, password): payload = { 'validate': { 'PASSWORD_LOOKUP': [{ 'id': self.form_id, 'login': login.encode(self.browser.ENCODING).upper(), 'password': password.encode(self.browser.ENCODING), 'type': 'PASSWORD_LOOKUP' }] } } req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) self.logger.debug(doc) if 'phase' in doc and doc['phase']['state'] == 'TERMS_OF_USE': # Got: # {u'phase': {u'state': u'TERMS_OF_USE'}, u'validationUnits': [{u'LIST_OF_TERMS': [{u'type': u'TERMS', u'id': u'b7f28f91-7aa0-48aa-8028-deec13ae341b', u'reference': u'CGU_CYBERPLUS'}]}]} if 'reference' in doc['validationUnits'][0]: del doc['validationUnits'][0]['reference'] payload = {'validate': doc['validationUnits'][0]} req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) self.logger.debug(doc) if ('phase' in doc and doc['phase']['previousResult'] == 'FAILED_AUTHENTICATION') or \ doc['response']['status'] != 'AUTHENTICATION_SUCCESS': raise BrowserIncorrectPassword() self.browser.location( doc['response']['saml2_post']['action'], urllib.urlencode({ 'SAMLResponse': doc['response']['saml2_post']['samlResponse'] }))
def go_aura(self, message, page_uri): context = { 'mode': self.context['mode'], 'fwuid': self.context[ 'fwuid'], # this value changes sometimes, (not at every synchronization) 'app': self.context['app'], 'loaded': self.context['loaded'], 'dn': [], 'globals': {}, 'uad': False } data = { 'aura.pageURI': page_uri, 'aura.token': self.token, 'aura.context': json.dumps(context), 'message': json.dumps(message), # message determines kind of response } self.aura.go(data=data)
def post(self, contents, max_age): form = self.get_form(xpath='//form[@class="well"]') password, d = encrypt(b64encode(contents.encode('utf-8'))) form['content'] = json.dumps(d) form['expiration'] = self.AGES[max_age] j = form.submit().json() assert j['status'] == 'ok' return urljoin(urljoin(self.url, form.url), '%s#%s' % (j['paste'], password))
def do_login(self): """ Attempt to log in. Note: this method does nothing if we are already logged in. """ try: self.login.go(data=json.dumps({'username': self.username, 'password': self.password}), headers={'Content-Type': 'application/json;charset=UTF-8'}) self.token = self.authorize.go().get_token() except ClientError: raise BrowserIncorrectPassword()
def new_recipient(self, recipient, **params): if 'code' in params: # for sms authentication return self.send_code(recipient, **params) # prepare commun data for all authentication method data = {} data['adresseBeneficiaire'] = '' data['iban'] = recipient.iban data['libelleBeneficiaire'] = recipient.label data['notification'] = True data['typeBeneficiaire'] = '' # provisional if self.digital_key: if 'digital_key' in params: return self.new_recipient_digital_key(recipient, data) # need to be on recipient page send sms or mobile notification # needed to get the phone number, enabling the possibility to send sms. # all users with validated phone number can receive sms code self.recipients.go(data=JSON({'type': 'TOUS'})) # check type of recipient activation type_activation = 'sms' # provisional if self.digital_key: if self.page.has_digital_key(): # force users with digital key activated to use digital key authentication type_activation = 'digital_key' if type_activation == 'sms': # post recipient data sending sms with same request data['typeEnvoi'] = 'SMS' recipient = self.add_recip.go(data=json.dumps(data), headers={ 'Content-Type': 'application/json' }).get_recipient(recipient) raise AddRecipientStep( recipient, Value('code', label='Saisissez le code reçu par SMS.')) elif type_activation == 'digital_key': # recipient validated with digital key are immediatly available recipient.enabled_date = datetime.today() raise AddRecipientStep( recipient, ValueBool( 'digital_key', label= 'Validez pour recevoir une demande sur votre application bancaire. La validation de votre bénéficiaire peut prendre plusieurs minutes.' ))
def search_videos(self, s): self.go_home() algolia_app_id, algolia_api_key = self.page.get_params() params = "x-algolia-agent=Algolia for vanilla JavaScript (lite) 3.27.0;instantsearch.js 2.10.2;JS Helper 2.26.0&x-algolia-application-id="+algolia_app_id+"&x-algolia-api-key="+algolia_api_key data = {} data['requests'] = [0] data['requests'][0] = {} data['requests'][0]['indexName'] = "yatta_prod_contents" ts = int(time.time()) data['requests'][0]['params'] = 'query={}&hitsPerPage=20&page=0&filters=class:video AND ranges.replay.web.begin_date < {} AND ranges.replay.web.end_date > {}&facetFilters=["class:video"]&facets=[]&tagFilters='.format(s, ts, ts) return self.search_page.go(p=params, data=json.dumps(data)).iter_videos()
def send_code(self, recipient, **params): """ add recipient with sms otp authentication """ data = {} data['idBeneficiaire'] = recipient._transfer_id data['typeActivation'] = 1 data['codeActivation'] = params['code'] return self.activate_recip_sms.go(data=json.dumps(data), headers={ 'Content-Type': 'application/json' }).get_recipient(recipient)
def do_login(self): """ Attempt to log in. Note: this method does nothing if we are already logged in. """ assert isinstance(self.username, basestring) assert isinstance(self.password, basestring) try: self.login.go(data=json.dumps({'username' : self.username, 'password' : self.password}), \ headers={'Content-Type': 'application/json;charset=UTF-8'}) self.token = self.authorize.go().get_token() except ClientError: raise BrowserIncorrectPassword()
def new_recipient(self, recipient, **params): if 'code' in params: return self.send_code(recipient, **params) # needed to get the phone number, enabling the possibility to send sms. self.recipients.go(data=JSON({'type': 'TOUS'})) # post recipient data sending sms with same request data = {} data['adresseBeneficiaire'] = '' data['iban'] = recipient.iban data['libelleBeneficiaire'] = recipient.label data['notification'] = True data['typeBeneficiaire'] = '' data['typeEnvoi'] = 'SMS' recipient = self.add_recip.go(data=json.dumps(data), headers={'Content-Type': 'application/json'}).get_recipient(recipient) raise AddRecipientStep(recipient, Value('code', label='Saississez le code.'))
def search_videos(self, s): self.go_home() algolia_app_id, algolia_api_key = self.page.get_params() params = "x-algolia-agent=Algolia for vanilla JavaScript (lite) 3.27.0;instantsearch.js 2.10.2;JS Helper 2.26.0&x-algolia-application-id=" + algolia_app_id + "&x-algolia-api-key=" + algolia_api_key data = {} data['requests'] = [0] data['requests'][0] = {} data['requests'][0]['indexName'] = "yatta_prod_contents" ts = int(time.time()) data['requests'][0][ 'params'] = 'query={}&hitsPerPage=20&page=0&filters=class:video AND ranges.replay.web.begin_date < {} AND ranges.replay.web.end_date > {}&facetFilters=["class:video"]&facets=[]&tagFilters='.format( s, ts, ts) return self.search_page.go(p=params, data=json.dumps(data)).iter_videos()
def new_recipient(self, recipient, **params): if 'code' in params: # for sms authentication return self.send_code(recipient, **params) # prepare commun data for all authentication method data = {} data['adresseBeneficiaire'] = '' data['iban'] = recipient.iban data['libelleBeneficiaire'] = recipient.label data['notification'] = True data['typeBeneficiaire'] = '' # provisional if self.digital_key: if 'digital_key' in params: return self.new_recipient_digital_key(recipient, data) # need to be on recipient page send sms or mobile notification # needed to get the phone number, enabling the possibility to send sms. # all users with validated phone number can receive sms code self.recipients.go(data=JSON({'type': 'TOUS'})) # check type of recipient activation type_activation = 'sms' # provisional if self.digital_key: if self.page.has_digital_key(): # force users with digital key activated to use digital key authentication type_activation = 'digital_key' if type_activation == 'sms': # post recipient data sending sms with same request data['typeEnvoi'] = 'SMS' recipient = self.add_recip.go( data=json.dumps(data), headers={'Content-Type': 'application/json'} ).get_recipient(recipient) raise AddRecipientStep(recipient, Value('code', label='Saisissez le code reçu par SMS.')) elif type_activation == 'digital_key': # recipient validated with digital key are immediatly available recipient.enabled_date = datetime.today() raise AddRecipientStep( recipient, ValueBool('digital_key', label='Validez pour recevoir une demande sur votre application bancaire. La validation de votre bénéficiaire peut prendre plusieurs minutes.') )
def do_login(self): try: self.login.go(data=json.dumps({ 'username': self.username, 'password': self.password })) except ClientError as e: if e.response.status_code == 400: raise BrowserIncorrectPassword() raise self.sessionId = self.page.get_session_id() self.client.go(sessionId=self.sessionId) self.intAccount = self.page.get_information('intAccount') self.name = self.page.get_information('displayName')
def post(self, contents, max_age): compressor = compressobj(-1, DEFLATED, -MAX_WBITS) contents = compressor.compress(contents.encode('utf-8')) contents += compressor.flush() password, d = encrypt(b64encode(contents)) data = { 'data': json.dumps(d), 'expire': self.AGES[max_age], 'burnafterreading': str(int(max_age is 0)), 'opendiscussion': str(int(self.browser.opendiscussion)), 'syntaxcoloring': '1', } response = self.browser.location(self.url, data=data) j = response.json() assert j['status'] == 0 return '%s?%s#%s' % (self.url, j['id'], password)
def login(self, login, password): payload = {'validate': {'PASSWORD_LOOKUP': [{'id': self.form_id, 'login': login.encode(self.browser.ENCODING), 'password': password.encode(self.browser.ENCODING), 'type': 'PASSWORD_LOOKUP' }] } } req = self.browser.request_class(self.request_url + '/step') req.add_header('Content-Type', 'application/json') r = self.browser.openurl(req, json.dumps(payload)) doc = json.load(r) if ('phase' in doc and doc['phase']['previousResult'] == 'FAILED_AUTHENTICATION') or \ doc['response']['status'] != 'AUTHENTICATION_SUCCESS': raise BrowserIncorrectPassword() self.browser.location(doc['response']['saml2_post']['action'], urllib.urlencode({'SAMLResponse': doc['response']['saml2_post']['samlResponse']}))
def open(self, *args, **kwargs): """ Do a JSON request. The "Content-Type" header is always set to "application/json". :param data: if specified, format as JSON and send as request body :type data: :class:`dict` :param headers: if specified, add these headers to the request :type headers: :class:`dict` """ if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Content-Type'] = 'application/json' return super(APIBrowser, self).open(*args, **kwargs)
def download_document(self, document): token = self.get_csrf_token() bills_informations = self.bill_informations.go( headers={ 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/plain, */*' }, data=json.dumps({ 'bpNumber': document._bp, 'csrfToken': token, 'docId': document._doc_number, 'docName': 'FACTURE', 'numAcc': document._num_acc, 'parNumber': document._par_number })).get_bills_informations() return self.bill_download.go(csrf_token=token, dn='FACTURE', pn=document._par_number, \ di=document._doc_number, bn=bills_informations.get('bpNumber'), \ an=bills_informations.get('numAcc')).content
def post(self, contents, max_age): compressor = compressobj(-1, DEFLATED, -MAX_WBITS) contents = compressor.compress(contents.encode('utf-8')) contents += compressor.flush() password, d = encrypt(b64encode(contents)) data = { 'data': json.dumps(d), 'expire': self.AGES[max_age], 'burnafterreading': str(int(max_age is 0)), 'opendiscussion': str(int(self.browser.opendiscussion)), 'syntaxcoloring': '1', } headers = { 'Accept': 'application/json', } response = self.browser.location(self.url, data=data, headers=headers) j = response.json() assert j['status'] == 0 return '%s?%s#%s' % (self.url, j['id'], password)
def search_housings(self, query, cities): self.update_header() data = {} data['rubrique'] = TYPES.get(query.type) data['prix_max'] = query.cost_max or None data['surface_min'] = query.area_min or None if len(cities) > 1: data['rayon'] = None else: data['rayon'] = 100 data['CategorieMode'] = None data['CategorieMaison'] = None data['Kilometrage'] = None data['top'] = 50 data['order_by'] = 5 data['sort_order'] = 1 data['lstNbPieces'] = [query.nb_rooms or 0] data['pageNumber'] = 1 for city in cities: data['localisation'] = {} data['localisation']['localisationid'] = city.id data['localisation']['label'] = city.name data['localisation']['localisationType'] = 5 data['localisationType'] = 5 data['lstLocalisationId'] = str(city.id) for house_type in query.house_types: data['lstTbien'] = RET.get(house_type) for house in self.search_house.go( data=json.dumps(data)).iter_houses(): if (empty(query.cost_min) or house.cost >= query.cost_min) and \ (empty(query.area_max) or house.area <= query.area_max): yield house
def tostring(self, element): return json.dumps(element)
def post_comment(self, issue_id, comment): project_id, issue_number = issue_id.rsplit('/', 1) url = 'https://api.github.com/repos/%s/issues/%s/comments' % (project_id, issue_number) data = json_module.dumps({'body': comment}) self.do_post(url, data)
def download_document(self, document): token = self.get_csrf_token() bills_informations = self.bill_informations.go(headers={'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/plain, */*'}, data=json.dumps({ 'bpNumber': document._bp, 'csrfToken': token, 'docId': document._doc_number, 'docName': 'FACTURE', 'numAcc': document._num_acc, 'parNumber': document._par_number })).get_bills_informations() return self.bill_download.go(csrf_token=token, dn='FACTURE', pn=document._par_number, \ di=document._doc_number, bn=bills_informations.get('bpNumber'), \ an=bills_informations.get('numAcc')).content
def request(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) self.location(*args, **kwargs) return json.loads(self.response.content)
def request(self, *args, **kwargs): if "data" in kwargs: kwargs["data"] = json.dumps(kwargs["data"]) r = self.location(*args, **kwargs) return json.loads(r.content)
def flush(self): self.output(json.dumps(self.queue, cls=WeboobEncoder))
def flush(self): self.output(json.dumps(self.queue, cls=Encoder))
def format_dict(self, item): self.output(json.dumps(item, cls=Encoder))
def request(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) r = self.location(*args, **kwargs) return json.loads(r.content)
def search_housings(self, query, module_name): if query.type not in self.TYPES.keys(): return TypeNotSupported() data = {} data['filters'] = {} data['filters']['category'] = {} data['filters']['category']['id'] = self.TYPES.get(query.type) data['filters']['enums'] = {} data['filters']['enums']['ad_type'] = ['offer'] data['filters']['enums']['real_estate_type'] = [] for t in query.house_types: t = self.RET.get(t) if t: data['filters']['enums']['real_estate_type'].append(t) if query.type == POSTS_TYPES.FURNISHED_RENT: data['filters']['enums']['furnished'] = ['1'] elif query.type == POSTS_TYPES.RENT: data['filters']['enums']['furnished'] = ['2'] data['filters']['keywords'] = {} data['filters']['ranges'] = {} if query.cost_max or query.cost_min: data['filters']['ranges']['price'] = {} if query.cost_max: data['filters']['ranges']['price']['max'] = query.cost_max if query.cost_min: data['filters']['ranges']['price']['min'] = query.cost_min if query.area_max or query.area_min: data['filters']['ranges']['square'] = {} if query.area_max: data['filters']['ranges']['square']['max'] = query.area_max if query.area_min: data['filters']['ranges']['square']['min'] = query.area_min if query.nb_rooms: data['filters']['ranges']['rooms'] = {} data['filters']['ranges']['rooms']['min'] = query.nb_rooms data['filters']['location'] = {} data['filters']['location']['city_zipcodes'] = [] for c in query.cities: if c.backend == module_name: _c = c.id.split(' ') __c = {} __c['city'] = _c[0] __c['zipcode'] = _c[1] __c['label'] = c.name data['filters']['location']['city_zipcodes'].append(__c) if len(query.advert_types) == 1: if query.advert_types[0] == ADVERT_TYPES.PERSONAL: data['owner_type'] = 'private' elif query.advert_types[0] == ADVERT_TYPES.PROFESSIONAL: data['owner_type'] = 'pro' else: data['owner_type'] = 'all' data['limit'] = 100 data['limit_alu'] = 3 data['offset'] = 0 self.session.headers.update({"api_key": self.home.go().get_api_key()}) return self.api.go(data=json.dumps(data)).get_housing_list(query_type=query.type, data=data)
def format_dict(self, item): self.output(json.dumps(item, cls=WeboobEncoder))
def flush(self): print(json.dumps(self.queue, cls=Encoder))
def set_message_read(self, _id): datas = {'action': 'markAsRead', 'type': 'entries', 'entryIds': [_id]} self.marker.open(data=json.dumps(datas))
def format_dict(self, item): print(json.dumps(item, cls=Encoder))