desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
@excmd def do_touch(self, arg=None):
(res, resp) = ([], None) if (hasattr(self, 'target_url') and self.target_url): resp = self.head(self.target_url) res.append(('HEAD %s - %s' % (self.target_url, resp.status_code))) for (key, val) in resp.headers.items(): res.append(('Header: %s -- %s' % (key, val))) tres = self.touch(resp) if (len(res) > 0): for i in res: self.log.info(('Touch result: %s' % i)) if (type(tres) == type([])): for i in res: self.log.info(('Touch result: %s' % i)) elif tres: self.log.error('Touch returned an error') self.log.error(('Reason given: %s' % res))
''
@excmd def do_probe(self, arg=None):
res = self.probe() if (not res): self.log.info('Target is vulnerable. Safe to proceed.') else: self.log.error('Target appears not to be vulnerable.') self.log.error(('Reason given: %s' % res))
''
@excmd def do_survey(self, arg=None):
res = self.survey() if (not res): self.log.info('Survey complete.') else: self.log.error('Survey failed.') self.log.error(('Reason given: %s' % res))
''
@excmd def do_exploit(self, arg=None):
res = self.exploit() if (not res): self.log.info('Exploit complete. Got root?') else: self.log.error('Exploit failed') self.log.error(('Reason given: %s' % res))
''
@excmd def do_clean(self, arg=None):
res = self.clean() if (not res): self.log.info('Cleanup completed successfully.') else: self.log.error(('Cleanup failed: %s' % res))
''
def do_show(self, args=None):
if args: args = args.strip() try: print ('%s = %s :: %s' % (args, self.ns.__dict__[args], self.action_help[args])) except KeyError: self.log.warning('Variable does not exist.') else: print 'Exploit variables' print '=========================' for (key, val) in self.ns.__dict__.items(): if (key not in self.action_help): self.action_help[key] = 'No help available' if (key not in ['func', 'config', 'load']): print (' %s = %s :: %s' % (key, val, self.action_help[key]))
''
def do_set(self, args):
if args: args = split(args) if (len(args) >= 2): if (args[0] in self.ns.__dict__): try: self._update_var(args[0], args[1]) except ArgumentTypeError as e: self.log.warning(('Setting %s failed: %s' % (args[0], e))) else: self.log.warning(('Variable %s does not exist' % args[0])) else: self.log.warning('Inavlid command syntax. Please see help for usage.') self._apply_settings()
''
def do_guided(self, args=None):
for cmd in self.excmds: if (cmd in dir(self)): res = raw_input(('About to execute %s. Continue, skip, interact, or quit? (C/s/i/q) ' % cmd)) if (res.lower() == 's'): continue elif (res.lower() == 'q'): return elif (res.lower() == 'i'): self.cmdloop() res = raw_input(('Done interacting, about to execute %s. Continue, skip, or quit? (C/s/q) ' % cmd)) if (res.lower() == 's'): continue if (res.lower() == 'q'): return elif getattr(self, ('do_' + cmd))(): return elif getattr(self, ('do_' + cmd))(): return res = raw_input('Finished executing commands. Quit or enter interactive mode? (Q/i) ') if (res.lower() == 'i'): self.cmdloop()
''
def request(self, mthd, url, **kwargs):
quiet = False if ('quiet' in kwargs): quiet = kwargs['quiet'] del kwargs['quiet'] if quiet: l = logging.getLogger('fosho.requests.packages.urllib3.connectionpool') old = l.getEffectiveLevel() l.setLevel(logging.ERROR) if (not self.multi): url = (self.target + url) self.log.debug(('Requesting %s %s with following provided settings: %s' % (mthd, url, kwargs))) if self.ns.host: if ('headers' not in kwargs): kwargs['headers'] = {} if ('host' not in kwargs['headers']): kwargs['headers']['Host'] = self.host kwargs['config'] = {} httplog = StringIO() stdout = sys.stdout t = TeeStdout(httplog, self.debug) try: resp = Session.request(self, mthd, url, **kwargs) except Exception as e: self._restore_stdout(httplog, stdout) if (('ignore_errors' in kwargs) and kwargs['ignore_errors']): return if (not quiet): self.log.error(('Exception occurred during request: %s' % e)) else: l.setLevel(old) raise e if quiet: l.setLevel(old) print ('body: %s' % repr(resp.content)) self._restore_stdout(httplog, stdout) return resp
''
def prompt_for_settings(self, names):
for name in names: try: res = getattr(self, ('_get_' + name))() except AttributeError as e: res = None if (not hasattr(self.ns, name)): self.ns.__dict__[name] = None if ((not self.ask) and (not res)): res = self.ns.__dict__[name] if ((not res) and self.ask): res = raw_input(('%s [%s]: ' % (name, self.ns.__dict__[name]))) if (not res): continue elif self.ask: res2 = raw_input(('%s [%s]: ' % (name, res))) if (res2.strip() != ''): res = res2 self._update_var(name, res) self._apply_settings()
''
def continue_prompt(self, msg, default='n'):
other = ('y' if (default == 'n') else 'n') opts = '(y/n)'.replace(default, default.upper()) res = raw_input(('%s %s ' % (msg, opts))) if (res.lower() != 'y'): try: self._do_finish() except: pass sys.exit('Stopping exploit...')
''
def get_etag(self, path):
res = self.head(path) return self._parse_etag(res.headers['etag'])
''
def _parse_etag(self, etag):
return (etag, 'Could not parse etag')
''
def _apply_settings(self):
for (key, val) in self.ns.__dict__.items(): if (key in ['quiet', 'debug']): level = logging.DEBUG if self.ns.quiet: level = logging.INFO self.log.setLevel(level) logging.getLogger('fosho.requests.packages.urllib3.connectionpool').setLevel(level) if (key == 'debug'): self.debug = (val and (not self.ns.quiet)) elif (key not in ['config', 'func']): setattr(self, key, val)
''
def _update_var(self, key, val):
if (val == 'False'): val = False cur = self.ns.__dict__[key] if (cur == None): cur = '' t = type(self.ns.__dict__[key]) if ((key in self.action_types) and self.action_types[key]): t = self.action_types[key] try: self.ns.__dict__[key] = t(val) except TypeError: self.ns.__dict__[key] = None
''
@classmethod def add_args(cur, cls):
parser = ArgumentParser(prog=sys.argv[0], description=('%s %s - %s' % (cls.name, cls.version, cls.desc))) subparsers = parser.add_subparsers(help='Exploit Commands') if cls.interact: inparse = subparsers.add_parser('interact', help='Run tool in interactive mode') inparse.set_defaults(func=cls.cmdloop) if cls.guided: gdparse = subparsers.add_parser('guided', help='Run tool in guided mode') gdparse.set_defaults(func=cls.do_guided) if hasattr(cls, 'touch'): tparse = subparsers.add_parser('touch', help='Touch target and return targeting information.') tparse.set_defaults(func=cls.do_touch) if hasattr(cls, 'probe'): vparse = subparsers.add_parser('probe', help='Check if target is vulnerable.') vparse.set_defaults(func=cls.do_probe) if hasattr(cls, 'survey'): iparse = subparsers.add_parser('survey', help='Gather useful information from target.') iparse.add_argument('-w', '--outfile', type=str, help='File to save target information to. (default: out.tar)') iparse.add_argument('-s', '--script', type=str, help='Survey script to run on server.') iparse.set_defaults(func=cls.do_survey) if hasattr(cls, 'exploit'): eparse = subparsers.add_parser('exploit', help='Exploit target.') eparse.add_argument('--mode', choices=cls.modes, help='Mode to use against target') eparse.add_argument('-p', '--binpath', default=None, help='Path to tool being used.') eparse.add_argument('-c', '--callback', type=is_target, help='Callback IP:Port for tool (Example: 127.0.0.1:12345)') eparse.set_defaults(func=cls.do_exploit) if hasattr(cls, 'clean'): cparse = subparsers.add_parser('clean', help='Do clean after exploit.') cparse.set_defaults(func=cls.do_clean) ggroup = parser.add_argument_group('Generic Exploit Options') ggroup.add_argument('--quiet', action='store_true', help='Disable verbose logging') ggroup.add_argument('--debug', action='store_true', help='Enable debug output. (Warning: prepare for spam)') ggroup.add_argument('-a', '--ask', action='store_true', help='Enable confirmation prompting before running commands.') ggroup.add_argument('--color', action='store_true', help='Enable log output colors.') ggroup.add_argument('-l', '--loadlast', action='store_true', help='Load last session used.') ggroup.add_argument('-s', '--session', type=str, help='Use specified session file.') ggroup.add_argument('-t', '--target', type=is_url, help='Target to exploit. (Ex: https://127.0.0.1:1234)') hgroup = parser.add_argument_group('HTTP Options') hgroup.add_argument('--timeout', type=int, help='Socket timeout') hgroup.add_argument('--host', type=str, help='Host header to use (default: empty') return (parser, subparsers)
'Adds labels to an ad object. Args: labels: A list of ad label IDs Returns: The FacebookResponse object.'
def add_labels(self, labels=None):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'adlabels'), params={'adlabels': [{'id': label} for label in labels]})
'Remove labels to an ad object. Args: labels: A list of ad label IDs Returns: The FacebookResponse object.'
def remove_labels(self, labels=None):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'adlabels'), params={'adlabels': [{'id': label} for label in labels]})
'Initialize an ObjectParser. To Initialize, you need to provide either a resuse_object, target_class, or an custom_parse_method. Args: api: FacebookAdsApi object. target_class (optional): The expected return object type. reuse_object (optional): Reuse existing object to populate response. custom_parse_method (optional): Custom parsing method.'
def __init__(self, api=None, target_class=None, reuse_object=None, custom_parse_method=None):
if (not any([target_class, (reuse_object is not None), custom_parse_method])): raise FacebookBadObjectError(('Must specify either target class calling object' + 'or custom parse method for parser')) self._reuse_object = reuse_object self._target_class = target_class self._custom_parse_method = custom_parse_method self._api = api
'Initializes a CRUD object. Args: fbid (optional): The id of the object ont the Graph. parent_id (optional): The id of the object\'s parent. api (optional): An api object which all calls will go through. If an api object is not specified, api calls will revert to going through the default api.'
def __init__(self, fbid=None, parent_id=None, api=None):
super(AbstractCrudObject, self).__init__() self._api = (api or FacebookAdsApi.get_default_api()) self._changes = {} if (parent_id is not None): warning_message = 'parent_id as a parameter of constructor is being deprecated.' logging.warning(warning_message) self._parent_id = parent_id self._data['id'] = fbid self._include_summary = True
'Sets an item in this CRUD object while maintaining a changelog.'
def __setitem__(self, key, value):
if ((key not in self._data) or (self._data[key] != value)): self._changes[key] = value super(AbstractCrudObject, self).__setitem__(key, value) if ('_setitem_trigger' in dir(self)): self._setitem_trigger(key, value) return self
'Two objects are the same if they have the same fbid.'
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.get_id() and other.get_id() and (self.get_id() == other.get_id()))
'Returns the object\'s fbid if set. Else, it returns None.'
def get_id(self):
return self[self.Field.id]
'Returns the object\'s parent\'s id.'
def get_parent_id(self):
return (self._parent_id or FacebookAdsApi.get_default_account_id())
'Returns the api associated with the object.'
def get_api(self):
return self._api
'Returns the fbid of the object. Raises: FacebookBadObjectError if the object does not have an id.'
def get_id_assured(self):
if (not self.get(self.Field.id)): raise FacebookBadObjectError(('%s object needs an id for this operation.' % self.__class__.__name__)) return self.get_id()
'Returns the object\'s parent\'s fbid. Raises: FacebookBadObjectError if the object does not have a parent id.'
def get_parent_id_assured(self):
if (not self.get_parent_id()): raise FacebookBadObjectError(('%s object needs a parent_id for this operation.' % self.__class__.__name__)) return self.get_parent_id()
'Returns the fbid of the object. Raises: FacebookBadObjectError if get_api returns None.'
def get_api_assured(self):
api = self.get_api() if (not api): raise FacebookBadObjectError(('%s does not yet have an associated api object.\nDid you forget to instantiate an API session with: FacebookAdsApi.init(app_id, app_secret, access_token)' % self.__class__.__name__)) return api
'Sets object\'s data as if it were read from the server. Warning: Does not log changes.'
def _set_data(self, data):
for key in map(str, data): self[key] = data[key] self._changes.pop(key, None) self._json = data return self
'Returns a dictionary of property names mapped to their values for properties modified from their original values.'
def export_changed_data(self):
return self.export_value(self._changes)
'Deprecated. Use export_all_data() or export_changed_data() instead.'
def export_data(self):
return self.export_changed_data()
'Clears the object\'s fbid.'
def clear_id(self):
del self[self.Field.id] return self
'Returns the node\'s relative path as a tuple of tokens.'
def get_node_path(self):
return (self.get_id_assured(),)
'Returns the node\'s path as a tuple.'
def get_node_path_string(self):
return '/'.join(self.get_node_path())
'Creates the object by calling the API. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. files (optional): An optional mapping of file names to binary open file objects. These files will be attached to the request. success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. Returns: self if not a batch call. the return value of batch.add if a batch call.'
def remote_create(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
if self.get_id(): raise FacebookBadObjectError(('This %s object was already created.' % self.__class__.__name__)) if (not ('get_endpoint' in dir(self))): raise TypeError(('Cannot create object of type %s.' % self.__class__.__name__)) params = ({} if (not params) else params.copy()) params.update(self.export_all_data()) request = None if hasattr(self, 'api_create'): request = self.api_create(self.get_parent_id_assured(), pending=True) else: request = FacebookRequest(node_id=self.get_parent_id_assured(), method='POST', endpoint=self.get_endpoint(), api=self._api, target_class=self.__class__, response_parser=ObjectParser(reuse_object=self)) request.add_params(params) request.add_files(files) if (batch is not None): def callback_success(response): self._set_data(response.json()) self._clear_history() if success: success(response) def callback_failure(response): if failure: failure(response) return batch.add_request(request=request, success=callback_success, failure=callback_failure) else: response = request.execute() self._set_data(response._json) self._clear_history() return self
'Reads the object by calling the API. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. fields (optional): A list of fields to read. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. files (optional): An optional mapping of file names to binary open file objects. These files will be attached to the request. success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. Returns: self if not a batch call. the return value of batch.add if a batch call.'
def remote_read(self, batch=None, failure=None, fields=None, params=None, success=None, api_version=None):
params = dict((params or {})) if hasattr(self, 'api_get'): request = self.api_get(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='GET', endpoint='/', api=self._api, target_class=self.__class__, response_parser=ObjectParser(reuse_object=self)) request.add_params(params) request.add_fields(fields) if (batch is not None): def callback_success(response): self._set_data(response.json()) if success: success(response) def callback_failure(response): if failure: failure(response) batch_call = batch.add_request(request=request, success=callback_success, failure=callback_failure) return batch_call else: self = request.execute() return self
'Updates the object by calling the API with only the changes recorded. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. files (optional): An optional mapping of file names to binary open file objects. These files will be attached to the request. success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. Returns: self if not a batch call. the return value of batch.add if a batch call.'
def remote_update(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
params = ({} if (not params) else params.copy()) params.update(self.export_changed_data()) self._set_data(params) if hasattr(self, 'api_update'): request = self.api_update(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='POST', endpoint='/', api=self._api, target_class=self.__class__, response_parser=ObjectParser(reuse_object=self)) request.add_params(params) request.add_files(files) if (batch is not None): def callback_success(response): self._clear_history() if success: success(response) def callback_failure(response): if failure: failure(response) batch_call = batch.add_request(request=request, success=callback_success, failure=callback_failure) return batch_call else: request.execute() self._clear_history() return self
'Deletes the object by calling the API with the DELETE http method. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. Returns: self if not a batch call. the return value of batch.add if a batch call.'
def remote_delete(self, batch=None, failure=None, params=None, success=None, api_version=None):
if hasattr(self, 'api_delete'): request = self.api_delete(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='DELETE', endpoint='/', api=self._api) request.add_params(params) if (batch is not None): def callback_success(response): self.clear_id() if success: success(response) def callback_failure(response): if failure: failure(response) batch_call = batch.add_request(request=request, success=callback_success, failure=callback_failure) return batch_call else: request.execute() self.clear_id() return self
'Calls remote_create method if object has not been created. Else, calls the remote_update method.'
def remote_save(self, *args, **kwargs):
if self.get_id(): return self.remote_update(*args, **kwargs) else: return self.remote_create(*args, **kwargs)
'Returns Cursor with argument self as source_object and the rest as given __init__ arguments. Note: list(iterate_edge(...)) can prefetch all the objects.'
def iterate_edge(self, target_objects_class, fields=None, params=None, fetch_first_page=True, include_summary=True, endpoint=None):
source_object = self cursor = Cursor(source_object, target_objects_class, fields=fields, params=params, include_summary=include_summary, endpoint=endpoint) if fetch_first_page: cursor.load_next_page() return cursor
'Returns first object when iterating over Cursor with argument self as source_object and the rest as given __init__ arguments.'
def edge_object(self, target_objects_class, fields=None, params=None, endpoint=None):
params = ({} if (not params) else params.copy()) params['limit'] = '1' for obj in self.iterate_edge(target_objects_class, fields=fields, params=params, endpoint=endpoint): return obj return None
'Returns all leadgen forms on the page'
def get_leadgen_forms(self, fields=None, params=None):
return self.iterate_edge(LeadgenForm, fields, params, endpoint='leadgen_forms')
'Returns all events on the page'
def get_events(self, fields=None, params=None):
return self.iterate_edge(Event, fields, params, endpoint='events')
'Returns info for fields that use enum values Should be implemented in subclasses'
@classmethod def _get_field_enum_info(cls):
return {}
'Returns the endpoint name. Raises: NotImplementedError if the method is not implemented in a class that derives from this abstract class.'
@classmethod def get_endpoint(cls):
raise NotImplementedError(('%s must have implemented get_endpoint.' % cls.__name__))
'Returns the class\'s list of default fields to read.'
@classmethod def get_default_read_fields(cls):
return cls._default_read_fields
'Sets the class\'s list of default fields to read. Args: fields: list of field names to read by default without specifying them explicitly during a read operation either via EdgeIterator or via AbstractCrudObject.read.'
@classmethod def set_default_read_fields(cls, fields):
cls._default_read_fields = fields
'Applies fields to params in a consistent manner.'
@classmethod def _assign_fields_to_params(cls, fields, params):
if (fields is None): fields = cls.get_default_read_fields() if fields: params['fields'] = ','.join(fields)
'For an AbstractObject, we do not need to keep history.'
def set_data(self, data):
self._set_data(data)
'Deprecated. Use export_all_data() instead.'
def export_data(self):
return self.export_all_data()
'Returns the preview html.'
def get_html(self):
return self[self.Field.body]
'`data` may have a different structure depending if you\'re creating new AdImages or iterating over existing ones using something like AdAccount.get_ad_images(). While reading existing images, _set_data from AbstractCrudObject handles everything correctly, but we need to treat the remote_create case. remote_create sample response: "images": { "8cf726a44ab7008c5cc6b4ebd2491234": { "hash":"8cf726a44ab7008c5cc6b4ebd2491234", "url":"https://fbcdn-photos-a.akamaihd.net/..." Sample response when calling act_<ACT_ID>/adimages, used internally by AdAccount.get_ad_images(): "data": [ "hash": "181b88e3cdf6464af7ed52fe488fe559", "id": "1739564149602806:181b88e3cdf6464af7ed52fe488fe559" "paging": { "cursors": { "before": "MTczOTU2NDE0OTYwMjgwNjoxODFiODh==", "after": "MTczOTU2NDE0OTYwMjgwNjoxODFiODhl=="'
def _set_data(self, data):
if ('images' in data): (_, data) = data['images'].popitem() for key in map(str, data): self._data[key] = data[key] self._changes.pop(key, None) self._data[self.Field.id] = ('%s:%s' % (self.get_parent_id_assured()[4:], self[self.Field.hash])) return self else: return AbstractCrudObject._set_data(self, data)
'Uploads filename and creates the AdImage object from it. It has same arguments as AbstractCrudObject.remote_create except it does not have the files argument but requires the \'filename\' property to be defined.'
def remote_create(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
if (not self[self.Field.filename]): raise FacebookBadObjectError('AdImage required a filename to be defined.') filename = self[self.Field.filename] with open(filename, 'rb') as open_file: return_val = AbstractCrudObject.remote_create(self, files={filename: open_file}, batch=batch, failure=failure, params=params, success=success, api_version=api_version) return return_val
'Returns the image hash to which AdCreative\'s can refer.'
def get_hash(self):
return self[self.Field.hash]
'Normalize the value based on the key'
@classmethod def normalize_key(cls, key_name, key_value=None):
if (key_value is None): return key_value if ((key_name == cls.Schema.MultiKeySchema.extern_id) or (key_name == cls.Schema.MultiKeySchema.email) or (key_name == cls.Schema.MultiKeySchema.madid)): return key_value if (key_name == cls.Schema.MultiKeySchema.phone): key_value = re.sub('[^0-9]', '', key_value) return key_value if (key_name == cls.Schema.MultiKeySchema.gen): key_value = key_value.strip()[:1] return key_value if (key_name == cls.Schema.MultiKeySchema.doby): key_value = re.sub('[^0-9]', '', key_value) return key_value if ((key_name == cls.Schema.MultiKeySchema.dobm) or (key_name == cls.Schema.MultiKeySchema.dobd)): key_value = re.sub('[^0-9]', '', key_value) if (len(key_value) == 1): key_value = ('0' + key_value) return key_value if ((key_name == cls.Schema.MultiKeySchema.ln) or (key_name == cls.Schema.MultiKeySchema.fn) or (key_name == cls.Schema.MultiKeySchema.ct) or (key_name == cls.Schema.MultiKeySchema.fi) or (key_name == cls.Schema.MultiKeySchema.st)): key_value = re.sub('[^a-zA-Z]', '', key_value) return key_value if (key_name == cls.Schema.MultiKeySchema.zip): key_value = re.split('-', key_value)[0] return key_value if (key_name == cls.Schema.MultiKeySchema.country): key_value = re.sub('[^a-zA-Z]', '', key_value)[:2] return key_value
'Adds users to this CustomAudience. Args: schema: A CustomAudience.Schema value specifying the type of values in the users list. users: A list of identities respecting the schema specified. Returns: The FacebookResponse object.'
def add_users(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None, session=None):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'users'), params=self.format_params(schema, users, is_raw, app_ids, pre_hashed, session))
'Deletes users from this CustomAudience. Args: schema: A CustomAudience.Schema value specifying the type of values in the users list. users: A list of identities respecting the schema specified. Returns: The FacebookResponse object.'
def remove_users(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None, session=None):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'users'), params=self.format_params(schema, users, is_raw, app_ids, pre_hashed, session))
'Shares this CustomAudience with the specified account_ids. Args: account_ids: A list of account ids. Returns: The FacebookResponse object.'
def share_audience(self, account_ids):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'adaccounts'), params={'adaccounts': account_ids})
'Unshares this CustomAudience with the specified account_ids. Args: account_ids: A list of account ids. Returns: The FacebookResponse object.'
def unshare_audience(self, account_ids):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'adaccounts'), params={'adaccounts': account_ids})
'Updates a product stored in a product catalog Args: retailer_id: product id from product feed. g:price tag in Google Shopping feed kwargs: key-value pairs to update on the object, being key the field name and value the updated value Returns: The FacebookResponse object.'
def update_product(self, retailer_id, **kwargs):
if (not kwargs): raise FacebookError("No fields to update provided. Example:\n catalog = ProductCatalog('catalog_id')\n catalog.update_product(\n retailer_id,\n price=100,\n availability=Product.Availability.out_of_stock\n )\n ") product_endpoint = ':'.join(('catalog', self.get_id_assured(), self.b64_encoded_id(retailer_id))) url = '/'.join((FacebookSession.GRAPH, FacebookAdsApi.API_VERSION, product_endpoint)) return self.get_api_assured().call('POST', url, params=kwargs)
'Associate ads pixel with another business'
def share_pixel_with_agency(self, business_id, agency_id):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'shared_agencies'), params={'business': business_id, 'agency_id': agency_id})
'Returns a list of businesses associated with the ads pixel'
def get_agencies(self):
response = self.get_api_assured().call('GET', (self.get_id_assured(), 'shared_agencies')).json() ret_val = [] if response: keys = response['data'] for item in keys: search_obj = Business() search_obj.update(item) ret_val.append(search_obj) return ret_val
'Returns list of adaccounts associated with the ads pixel'
def get_ad_accounts(self, business_id):
response = self.get_api_assured().call('GET', (self.get_id_assured(), 'shared_accounts'), params={'business': business_id}).json() ret_val = [] if response: keys = response['data'] for item in keys: search_obj = AdAccount() search_obj.update(item) ret_val.append(search_obj) return ret_val
'Returns iterator over AdAccounts associated with this user.'
def get_ad_accounts(self, fields=None, params=None):
return self.iterate_edge(AdAccount, fields, params, endpoint='adaccounts')
'Returns first AdAccount associated with this user.'
def get_ad_account(self, fields=None, params=None):
return self.edge_object(AdAccount, fields, params)
'Returns iterator over Pages\'s associated with this user.'
def get_pages(self, fields=None, params=None):
return self.iterate_edge(Page, fields, params)
'Gets the final result from an async job Accepts params such as limit'
def get_result(self, params=None):
return self.get_insights(params=params)
'Uploads filepath and creates the AdVideo object from it. It has same arguments as AbstractCrudObject.remote_create except it does not have the files argument but requires the \'filepath\' property to be defined.'
def remote_create(self, batch=None, failure=None, params=None, success=None):
if ((self.Field.slideshow_spec in self) and (self[self.Field.slideshow_spec] is not None)): request = VideoUploadRequest(self.get_api_assured()) request.setParams(params={'slideshow_spec': {'images_urls': self[self.Field.slideshow_spec]['images_urls'], 'duration_ms': self[self.Field.slideshow_spec]['duration_ms'], 'transition_ms': self[self.Field.slideshow_spec]['transition_ms']}}) response = request.send((self.get_parent_id_assured(), 'advideos')).json() elif (not (self.Field.filepath in self)): raise FacebookBadObjectError('AdVideo requires a filepath or slideshow_spec to be defined.') else: video_uploader = VideoUploader() response = video_uploader.upload(self) self._set_data(response) return response
'Returns all the thumbnails associated with the ad video'
def get_thumbnails(self, fields=None, params=None):
return self.iterate_edge(VideoThumbnail, fields, params, endpoint='thumbnails')
'Initializes and populates the instance attributes with app_id, app_secret, access_token, appsecret_proof, proxies, timeout and requests given arguments app_id, app_secret, access_token, proxies and timeout.'
def __init__(self, app_id=None, app_secret=None, access_token=None, proxies=None, timeout=None):
self.app_id = app_id self.app_secret = app_secret self.access_token = access_token self.proxies = proxies self.timeout = timeout self.requests = requests.Session() self.requests.verify = os.path.join(os.path.dirname(__file__), 'fb_ca_chain_bundle.crt') params = {'access_token': self.access_token} if app_secret: params['appsecret_proof'] = self._gen_appsecret_proof() self.requests.params.update(params) if self.proxies: self.requests.proxies.update(self.proxies)
'Upload the given video file. Args: video(required): The AdVideo object that will be uploaded wait_for_encoding: Whether to wait until encoding is finished.'
def upload(self, video, wait_for_encoding=False):
if self._session: raise FacebookError('There is already an upload session for this video uploader') self._session = VideoUploadSession(video, wait_for_encoding) result = self._session.start() self._session = None return result
'send upload request'
@abstractmethod def send_request(self, context):
pass
'get upload params from context'
@abstractmethod def getParamsFromContext(self, context):
pass
'send start request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) request.setParams(self.getParamsFromContext(context)) return request.send((context.account_id, 'advideos'))
'send transfer request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) self._start_offset = context.start_offset self._end_offset = context.end_offset filepath = context.file_path file_size = os.path.getsize(filepath) retry = max((file_size / ((1024 * 1024) * 10)), 2) f = open(filepath, 'rb') while (self._start_offset != self._end_offset): f.seek(self._start_offset) chunk = f.read((self._end_offset - self._start_offset)) context.start_offset = self._start_offset context.end_offset = self._end_offset request.setParams(self.getParamsFromContext(context), {'video_file_chunk': (context.file_path, chunk, 'multipart/form-data')}) try: response = request.send((context.account_id, 'advideos')).json() self._start_offset = int(response['start_offset']) self._end_offset = int(response['end_offset']) except FacebookRequestError as e: subcode = e.api_error_subcode() body = e.body() if (subcode == 1363037): if (body and ('error' in body) and ('error_data' in body['error']) and ('start_offset' in body['error']['error_data']) and (retry > 0)): self._start_offset = int(body['error']['error_data']['start_offset']) self._end_offset = int(body['error']['error_data']['end_offset']) retry = max((retry - 1), 0) continue elif (('error' in body) and ('is_transient' in body['error'])): if body['error']['is_transient']: time.sleep(1) continue f.close() raise e f.close() return response
'send transfer request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) request.setParams(self.getParamsFromContext(context)) return request.send((context.account_id, 'advideos'))
'send the current request'
def send(self, path):
return self._api.call('POST', path, params=self._params, files=self._files, url_override='https://graph-video.facebook.com')
'Delete accumulated remote objects.'
def delete_remote_objects(self):
for o in reversed(self.remote_objects): if ((o.Field.id in o) and (o.get_id() is not None)): try: o.remote_delete() except Exception: if isinstance(o, objects.AdImage): pass else: raise
'Prepare to delete obj in tearDown.'
def delete_in_teardown(self, obj):
self.remote_objects.append(obj)
'Returns object of same class as subject and with same id.'
@classmethod def get_mirror(cls, subject):
return subject.__class__(subject.get_id())
'Tests if object can be created. It asserts that id is empty before creation, and populated after.'
@classmethod def assert_can_create(cls, subject):
assert (subject[subject.Field.id] is None) subject.remote_create() assert (subject[subject.Field.id] is not None)
'Tests if object can be read. Reads default fields of subject and sees if subject matches with its mirror in all the subject\'s fields.'
@classmethod def assert_can_read(cls, subject):
assert (subject.Field.id in subject) fields_to_read = subject.get_default_read_fields() subject.remote_read(fields=fields_to_read) for field in fields_to_read: assert (field in subject) mirror = cls.get_mirror(subject) mirror.remote_read(fields=fields_to_read) for field in fields_to_read: assert (subject[field] == mirror[field])
'Asserts that the id is empty before creation and then updates'
@classmethod def assert_can_save(cls, subject):
assert (subject[subject.Field.id] is None) subject.remote_save() assert (subject[subject.Field.id] is not None) subject.remote_save() mirror = cls.get_mirror(subject) assert (subject[subject.Field.id] == mirror[mirror.Field.id])
'Sometimes the response returns an array inside the data key. This asserts that we successfully build objects using the objects in that array.'
def test_builds_from_array(self):
response = {'data': [{'id': '6019579'}, {'id': '6018402'}]} ei = api.Cursor(adaccount.AdAccount(fbid='123'), ad.Ad) objs = ei.build_objects_from_response(response) assert (len(objs) == 2)
'Sometimes the response returns a single JSON object. This asserts that we\'re not looking for the data key and that we correctly build the object without relying on the data key.'
def test_builds_from_object(self):
response = {'id': '601957/targetingsentencelines', 'targetingsentencelines': [{'content': 'Location - Living In:', 'children': ['United States']}, {'content': 'Age:', 'children': ['18 - 65+']}]} ei = api.Cursor(adaccount.AdAccount(fbid='123'), ad.Ad) obj = ei.build_objects_from_response(response) assert ((len(obj) == 1) and (obj[0]['id'] == '601957/targetingsentencelines'))
'Sometimes the response returns a single JSON object - with a "data". For instance with reachestimate. This asserts that we successfully build the object that is in "data" key.'
def test_builds_from_object_with_data_key(self):
response = {'data': {'estimate_ready': True, 'bid_estimations': [{'cpa_min': 63, 'cpa_median': 116, 'cpm_max': 331, 'cpc_max': 48, 'cpc_median': 35, 'cpc_min': 17, 'cpm_min': 39, 'cpm_median': 212, 'unsupported': False, 'location': 3, 'cpa_max': 163}], 'users': 7600000}} ei = api.Cursor(ad.Ad('123'), reachestimate.ReachEstimate) obj = ei.build_objects_from_response(response) assert ((len(obj) == 1) and (obj[0]['users'] == 7600000))
'Demonstrates that AbstractCrudObject._assign_fields_to_params() handles various combinations of params and fields properly.'
def test_fields_to_params(self):
class Foo(abstractcrudobject.AbstractCrudObject, ): _default_read_fields = ['id', 'name'] class Bar(abstractcrudobject.AbstractCrudObject, ): _default_read_fields = [] for (adclass, fields, params, expected) in [(Foo, None, {}, {'fields': 'id,name'}), (Foo, None, {'a': 'b'}, {'a': 'b', 'fields': 'id,name'}), (Foo, ['x'], {}, {'fields': 'x'}), (Foo, ['x'], {'a': 'b'}, {'a': 'b', 'fields': 'x'}), (Foo, [], {}, {}), (Foo, [], {'a': 'b'}, {'a': 'b'}), (Bar, None, {}, {}), (Bar, None, {'a': 'b'}, {'a': 'b'}), (Bar, ['x'], {}, {'fields': 'x'}), (Bar, ['x'], {'a': 'b'}, {'a': 'b', 'fields': 'x'}), (Bar, [], {}, {}), (Bar, [], {'a': 'b'}, {'a': 'b'})]: adclass._assign_fields_to_params(fields, params) assert (params == expected)
'Must be able to print nested objects without serialization issues'
def test_can_print(self):
obj = specs.ObjectStorySpec() obj2 = specs.OfferData() obj2['barcode'] = 'foo' obj['offer_data'] = obj2 try: obj.__repr__() except TypeError as e: self.fail(('Cannot call __repr__ on AbstractObject\n %s' % e))
'Prepare for Ads API calls and return a tuple with act_id and page_id. page_id can be None but act_id is always set.'
@classmethod def auth(cls):
config = cls.load_config() if cls._is_authenticated: return (config['act_id'], config.get('page_id', None)) if (config['app_id'] and config['app_secret'] and config['act_id'] and config['access_token']): FacebookAdsApi.init(config['app_id'], config['app_secret'], config['access_token'], config['act_id']) cls._is_authenticated = True return (config['act_id'], config.get('page_id', None)) else: required_fields = set(('app_id', 'app_secret', 'act_id', 'access_token')) missing_fields = (required_fields - set(config.keys())) raise FacebookError('\n DCTB File config.json needs to have the following fields: {}\n DCTB Missing fields: {}\n'.format(', '.join(required_fields), ', '.join(missing_fields)))
'Initializes the object\'s internal data. Args: body (optional): The response body as text. http_status (optional): The http status code. headers (optional): The http headers. call (optional): The original call that was made.'
def __init__(self, body=None, http_status=None, headers=None, call=None):
self._body = body self._http_status = http_status self._headers = (headers or {}) self._call = call
'Returns the response body.'
def body(self):
return self._body
'Returns the response body -- in json if possible.'
def json(self):
try: return json.loads(self._body) except (TypeError, ValueError): return self._body
'Return the response headers.'
def headers(self):
return self._headers
'Returns the ETag header value if it exists.'
def etag(self):
return self._headers.get('ETag')
'Returns the http status code of the response.'
def status(self):
return self._http_status
'Returns boolean indicating if the call was successful.'
def is_success(self):
json_body = self.json() if (isinstance(json_body, collections.Mapping) and ('error' in json_body)): return False elif bool(json_body): if ('success' in json_body): return json_body['success'] return ('Service Unavailable' not in json_body) elif (self._http_status == http_client.NOT_MODIFIED): return True elif (self._http_status == http_client.OK): return True else: return False
'Returns boolean indicating if the call failed.'
def is_failure(self):
return (not self.is_success())
'Returns a FacebookRequestError (located in the exceptions module) with an appropriate debug message.'
def error(self):
if self.is_failure(): return FacebookRequestError('Call was not successful', self._call, self.status(), self.headers(), self.body()) else: return None
'Initializes the api instance. Args: session: FacebookSession object that contains a requests interface and attribute GRAPH (the Facebook GRAPH API URL). api_version: API version'
def __init__(self, session, api_version=None):
self._session = session self._num_requests_succeeded = 0 self._num_requests_attempted = 0 self._api_version = (api_version or self.API_VERSION)
'Returns the number of calls attempted.'
def get_num_requests_attempted(self):
return self._num_requests_attempted