desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the type of dataform.'
def getType(self):
return self.getAttr('type')
'Set the type of dataform.'
def setType(self, typ):
self.setAttr('type', typ)
'Return the title of dataform.'
def getTitle(self):
return self.getTagData('title')
'Set the title of dataform.'
def setTitle(self, text):
self.setTagData('title', text)
'Return the instructions of dataform.'
def getInstructions(self):
return self.getTagData('instructions')
'Set the instructions of dataform.'
def setInstructions(self, text):
self.setTagData('instructions', text)
'Add one more instruction to the dataform.'
def addInstructions(self, text):
self.addChild('instructions', {}, [text])
'Return the datafield object with name \'name\' (if exists).'
def getField(self, name):
return self.getTag('field', attrs={'var': name})
'Create if nessessary or get the existing datafield object with name \'name\' and return it.'
def setField(self, name):
f = self.getField(name) if f: return f return self.addChild(node=DataField(name))
'Represent dataform as simple dictionary mapping of datafield names to their values.'
def asDict(self):
ret = {} for field in self.getTags('field'): name = field.getAttr('var') typ = field.getType() if (isinstance(typ, (str, unicode)) and (typ[(-6):] == '-multi')): val = [] for i in field.getTags('value'): val.append(i.getData()) else: ...
'Simple dictionary interface for getting datafields values by their names.'
def __getitem__(self, name):
item = self.getField(name) if item: return item.getValue() raise IndexError('No such field')
'Simple dictionary interface for setting datafields values by their names.'
def __setitem__(self, name, val):
return self.setField(name).setValue(val)
'Initialises internal variables. Used internally.'
def __init__(self):
PlugIn.__init__(self) DBG_LINE = 'browser' self._exported_methods = [] self._handlers = {'': {}}
'Registers it\'s own iq handlers in your application dispatcher instance. Used internally.'
def plugin(self, owner):
owner.RegisterHandler('iq', self._DiscoveryHandler, typ='get', ns=NS_DISCO_INFO) owner.RegisterHandler('iq', self._DiscoveryHandler, typ='get', ns=NS_DISCO_ITEMS)
'Unregisters browser\'s iq handlers from your application dispatcher instance. Used internally.'
def plugout(self):
self._owner.UnregisterHandler('iq', self._DiscoveryHandler, typ='get', ns=NS_DISCO_INFO) self._owner.UnregisterHandler('iq', self._DiscoveryHandler, typ='get', ns=NS_DISCO_ITEMS)
'Returns dictionary and key or None,None None - root node (w/o "node" attribute) /a/b/c - node /a/b/ - branch Set returns \'\' or None as the key get returns \'\' or None as the key or None as the dict. Used internally.'
def _traversePath(self, node, jid, set=0):
if self._handlers.has_key(jid): cur = self._handlers[jid] elif set: self._handlers[jid] = {} cur = self._handlers[jid] else: cur = self._handlers[''] if (node is None): node = [None] else: node = node.replace('/', ' /').split('/') for i in node:...
'This is the main method that you will use in this class. It is used to register supplied DISCO handler (or dictionary with static info) as handler of some disco tree branch. If you do not specify the node this handler will be used for all queried nodes. If you do not specify the jid this handler will be used for all q...
def setDiscoHandler(self, handler, node='', jid=''):
self.DEBUG(('Registering handler %s for "%s" node->%s' % (handler, jid, node)), 'info') (node, key) = self._traversePath(node, jid, 1) node[key] = handler
'Returns the previously registered DISCO handler that is resonsible for this node/jid combination. Used internally.'
def getDiscoHandler(self, node='', jid=''):
(node, key) = self._traversePath(node, jid) if node: return node[key]
'Unregisters DISCO handler that is resonsible for this node/jid combination. When handler is unregistered the branch is handled in the same way that it\'s parent branch from this moment.'
def delDiscoHandler(self, node='', jid=''):
(node, key) = self._traversePath(node, jid) if node: handler = node[key] del node[dict][node[str]] return handler
'Servers DISCO iq request from the remote client. Automatically determines the best handler to use and calls it to handle the request. Used internally.'
def _DiscoveryHandler(self, conn, request):
node = request.getQuerynode() if node: nodestr = node else: nodestr = 'None' handler = self.getDiscoHandler(node, request.getTo()) if (not handler): self.DEBUG(('No Handler for request with jid->%s node->%s ns->%s' % (request.getTo().__str__().encode('utf...
'When the session is created it\'s type (client/server) is determined from the beginning. socket argument is the pre-created socket-like object. It must have the following methods: send, recv, fileno, close. owner is the \'master\' instance that have Dispatcher plugged into it and generally will take care about all ses...
def __init__(self, socket, owner, xmlns=None, peer=None):
self.xmlns = xmlns if peer: self.TYP = 'client' self.peer = peer self._socket_state = SOCKET_UNCONNECTED else: self.TYP = 'server' self.peer = None self._socket_state = SOCKET_ALIVE self._sock = socket self._send = socket.send self._recv = socket.r...
'This method is used to initialise the internal xml expat parser and to send initial stream header (in case of client connection). Should be used after initial connection and after every stream restart.'
def StartStream(self):
self._stream_state = STREAM__NOT_OPENED self.Stream = simplexml.NodeBuilder() self.Stream._dispatch_depth = 2 self.Stream.dispatch = self._dispatch self.Parse = self.Stream.Parse self.Stream.stream_footer_received = self._stream_close if (self.TYP == 'client'): self.Stream.stream_hea...
'Reads all pending incoming data. Raises IOError on disconnection. Blocks until at least one byte is read.'
def receive(self):
try: received = self._recv(10240) except: received = '' if len(received): self.DEBUG(((`self.fileno()` + ' ') + received), 'got') else: self.DEBUG('Socket error while receiving data', 'error') self.set_socket_state(SOCKET_DEAD) raise IOError...
'Put chunk into "immidiatedly send" queue. Should only be used for auth/TLS stuff and like. If you just want to shedule regular stanza for delivery use enqueue method.'
def sendnow(self, chunk):
if isinstance(chunk, Node): chunk = chunk.__str__().encode('utf-8') elif (type(chunk) == type(u'')): chunk = chunk.encode('utf-8') self.enqueue(chunk)
'Takes Protocol instance as argument. Puts stanza into "send" fifo queue. Items into the send queue are hold until stream authenticated. After that this method is effectively the same as "sendnow" method.'
def enqueue(self, stanza):
if isinstance(stanza, Protocol): self.stanza_queue.append(stanza) else: self.sendbuffer += stanza if (self._socket_state >= SOCKET_ALIVE): self.push_queue()
'If stream is authenticated than move items from "send" queue to "immidiatedly send" queue. Else if the stream is failed then return all queued stanzas with error passed as argument. Otherwise do nothing.'
def push_queue(self, failreason=ERR_RECIPIENT_UNAVAILABLE):
if ((self._stream_state >= STREAM__CLOSED) or (self._socket_state >= SOCKET_DEAD)): self._owner.deactivatesession(self) for key in self.deliver_key_queue: self._dispatch(Error(self.deliver_queue_map[key], failreason), trusted=1) for stanza in self.stanza_queue: self._...
'Put the "immidiatedly send" queue content on the wire. Blocks until at least one byte sent.'
def flush_queue(self):
if self.sendbuffer: try: sent = self._send(self.sendbuffer) except: self.set_socket_state(SOCKET_DEAD) self.DEBUG('Socket error while sending data', 'error') return self.terminate_stream() self.DEBUG(((`self.fileno()` + ' ') + se...
'This is callback that is used to pass the received stanza forth to owner\'s dispatcher _if_ the stream is authorised. Otherwise the stanza is just dropped. The \'trusted\' argument is used to emulate stanza receive. This method is used internally.'
def _dispatch(self, stanza, trusted=0):
self._owner.packets += 1 if ((self._stream_state == STREAM__OPENED) or trusted): self.DEBUG(stanza.__str__(), 'dispatch') stanza.trusted = trusted return self.Dispatcher.dispatch(stanza, self)
'This callback is used to detect the stream namespace of incoming stream. Used internally.'
def _catch_stream_id(self, ns=None, tag='stream', attrs={}):
if ((not attrs.has_key('id')) or (not attrs['id'])): return self.terminate_stream(STREAM_INVALID_XML) self.ID = attrs['id'] if (not attrs.has_key('version')): self._owner.Dialback(self)
'This callback is used to handle opening stream tag of the incoming stream. In the case of client session it just make some validation. Server session also sends server headers and if the stream valid the features node. Used internally.'
def _stream_open(self, ns=None, tag='stream', attrs={}):
text = '<?xml version="1.0" encoding="utf-8"?>\n<stream:stream' if (self.TYP == 'client'): text += (' to="%s"' % self.peer) else: text += (' id="%s"' % self.ID) if (not attrs.has_key('to')): text += (' from="%s"' % self._owner.servernames[0]) else: ...
'Declare some stream feature as activated one.'
def feature(self, feature):
if (feature not in self.features): self.features.append(feature) self.unfeature(feature)
'Declare some feature as illegal. Illegal features can not be used. Example: BIND feature becomes illegal after Non-SASL auth.'
def unfeature(self, feature):
if (feature in self.waiting_features): self.waiting_features.remove(feature)
'Write the closing stream tag and destroy the underlaying socket. Used internally.'
def _stream_close(self, unregister=1):
if (self._stream_state >= STREAM__CLOSED): return self.set_stream_state(STREAM__CLOSING) self.sendnow('</stream:stream>') self.set_stream_state(STREAM__CLOSED) self.push_queue() self._owner.flush_queues() if unregister: self._owner.unregistersession(self) self._destroy_so...
'Notify the peer about stream closure. Ensure that xmlstream is not brokes - i.e. if the stream isn\'t opened yet - open it before closure. If the error condition is specified than create a stream error and send it along with closing stream tag. Emulate receiving \'unavailable\' type presence just before stream closure...
def terminate_stream(self, error=None, unregister=1):
if (self._stream_state >= STREAM__CLOSING): return if (self._stream_state < STREAM__OPENED): self.set_stream_state(STREAM__CLOSING) self._stream_open() else: self.set_stream_state(STREAM__CLOSING) p = Presence(typ='unavailable') p.setNamespace(NS_CLIENT) ...
'Break cyclic dependancies to let python\'s GC free memory right now.'
def _destroy_socket(self):
self.Stream.dispatch = None self.Stream.stream_footer_received = None self.Stream.stream_header_received = None self.Stream.destroy() self._sock.close() self.set_socket_state(SOCKET_DEAD)
'Declare some feature as "negotiating now" to prevent other features from start negotiating.'
def start_feature(self, f):
if self.feature_in_process: raise ('Starting feature %s over %s !' % (f, self.feature_in_process)) self.feature_in_process = f
'Declare some feature as "negotiated" to allow other features start negotiating.'
def stop_feature(self, f):
if (self.feature_in_process != f): raise ('Stopping feature %s instead of %s !' % (f, self.feature_in_process)) self.feature_in_process = None
'Change the underlaying socket state. Socket starts with SOCKET_UNCONNECTED state and then proceeds (possibly) to SOCKET_ALIVE and then to SOCKET_DEAD'
def set_socket_state(self, newstate):
if (self._socket_state < newstate): self._socket_state = newstate
'Change the session state. Session starts with SESSION_NOT_AUTHED state and then comes through SESSION_AUTHED, SESSION_BOUND, SESSION_OPENED and SESSION_CLOSED states.'
def set_session_state(self, newstate):
if (self._session_state < newstate): if ((self._session_state < SESSION_AUTHED) and (newstate >= SESSION_AUTHED)): self._stream_pos_queued = self._stream_pos_sent self._session_state = newstate
'Change the underlaying XML stream state Stream starts with STREAM__NOT_OPENED and then proceeds with STREAM__OPENED, STREAM__CLOSING and STREAM__CLOSED states. Note that some features (like TLS and SASL) requires stream re-start so this state can have non-linear changes.'
def set_stream_state(self, newstate):
if (self._stream_state < newstate): self._stream_state = newstate
'Initialises class and sets up local variables'
def __init__(self, browser):
PlugIn.__init__(self) DBG_LINE = 'commands' self._exported_methods = [] self._handlers = {'': {}} self._browser = browser
'Makes handlers within the session'
def plugin(self, owner):
owner.RegisterHandler('iq', self._CommandHandler, typ='set', ns=NS_COMMANDS) owner.RegisterHandler('iq', self._CommandHandler, typ='get', ns=NS_COMMANDS) self._browser.setDiscoHandler(self._DiscoHandler, node=NS_COMMANDS, jid='')
'Removes handlers from the session'
def plugout(self):
self._owner.UnregisterHandler('iq', self._CommandHandler, ns=NS_COMMANDS) for jid in self._handlers: self._browser.delDiscoHandler(self._DiscoHandler, node=NS_COMMANDS)
'The internal method to process the routing of command execution requests'
def _CommandHandler(self, conn, request):
jid = str(request.getTo()) try: node = request.getTagAttr('command', 'node') except: conn.send(Error(request, ERR_BAD_REQUEST)) raise NodeProcessed if self._handlers.has_key(jid): if self._handlers[jid].has_key(node): self._handlers[jid][node]['execute'](conn,...
'The internal method to process service discovery requests'
def _DiscoHandler(self, conn, request, typ):
if (typ == 'items'): list = [] items = [] jid = str(request.getTo()) if self._handlers.has_key(jid): for each in self._handlers[jid].keys(): items.append((jid, each)) else: for each in self._handlers[''].keys(): items.ap...
'The method to call if adding a new command to the session, the requred parameters of cmddisco and cmdexecute are the methods to enable that command to be executed'
def addCommand(self, name, cmddisco, cmdexecute, jid=''):
if (not self._handlers.has_key(jid)): self._handlers[jid] = {} self._browser.setDiscoHandler(self._DiscoHandler, node=NS_COMMANDS, jid=jid) if self._handlers[jid].has_key(name): raise NameError, 'Command Exists' else: self._handlers[jid][name] = {'disco': cmddisco, 'execut...
'Removed command from the session'
def delCommand(self, name, jid=''):
if (not self._handlers.has_key(jid)): raise NameError, 'Jid not found' if (not self._handlers[jid].has_key(name)): raise NameError, 'Command not found' else: command = self.getCommand(name, jid)['disco'] del self._handlers[jid][name] self._browser.delDisco...
'Returns the command tuple'
def getCommand(self, name, jid=''):
if (not self._handlers.has_key(jid)): raise NameError, 'Jid not found' elif (not self._handlers[jid].has_key(name)): raise NameError, 'Command not found' else: return self._handlers[jid][name]
'Set up the class'
def __init__(self, jid=''):
PlugIn.__init__(self) DBG_LINE = 'command' self.sessioncount = 0 self.sessions = {} self.discoinfo = {'ids': [{'category': 'automation', 'type': 'command-node', 'name': self.description}], 'features': self.discofeatures} self._jid = jid
'Plug command into the commands class'
def plugin(self, owner):
self._commands = owner self._owner = owner._owner self._commands.addCommand(self.name, self._DiscoHandler, self.Execute, jid=self._jid)
'Remove command from the commands class'
def plugout(self):
self._commands.delCommand(self.name, self._jid)
'Returns an id for the command session'
def getSessionID(self):
self.count = (self.count + 1) return ('cmd-%s-%d' % (self.name, self.count))
'The method that handles all the commands, and routes them to the correct method for that stage.'
def Execute(self, conn, request):
try: session = request.getTagAttr('command', 'sessionid') except: session = None try: action = request.getTagAttr('command', 'action') except: action = None if (action == None): action = 'execute' if self.sessions.has_key(session): if (self.session...
'The handler for discovery events'
def _DiscoHandler(self, conn, request, type):
if (type == 'list'): return (request.getTo(), self.name, self.description) elif (type == 'items'): return [] elif (type == 'info'): return self.discoinfo
'Init internal constants.'
def __init__(self, jid=''):
Command_Handler_Prototype.__init__(self, jid) self.initial = {'execute': self.cmdFirstStage}
'Determine'
def cmdFirstStage(self, conn, request):
try: session = request.getTagAttr('command', 'sessionid') except: session = None if (session == None): session = self.getSessionID() self.sessions[session] = {'jid': request.getFrom(), 'actions': {'cancel': self.cmdCancel, 'next': self.cmdSecondStage, 'execute': self.cmdSecon...
'Initialise internal variables.'
def __init__(self):
PlugIn.__init__(self) self.DBG_LINE = 'ibb' self._exported_methods = [self.OpenStream] self._streams = {} self._ampnode = Node((NS_AMP + ' amp'), payload=[Node('rule', {'condition': 'deliver-at', 'value': 'stored', 'action': 'error'}), Node('rule', {'condition': 'match-resource', 'value': 'exact'...
'Register handlers for receiving incoming datastreams. Used internally.'
def plugin(self, owner):
self._owner.RegisterHandlerOnce('iq', self.StreamOpenReplyHandler) self._owner.RegisterHandler('iq', self.IqHandler, ns=NS_IBB) self._owner.RegisterHandler('message', self.ReceiveHandler, ns=NS_IBB)
'Handles streams state change. Used internally.'
def IqHandler(self, conn, stanza):
typ = stanza.getType() self.DEBUG(('IqHandler called typ->%s' % typ), 'info') if ((typ == 'set') and stanza.getTag('open', namespace=NS_IBB)): self.StreamOpenHandler(conn, stanza) elif ((typ == 'set') and stanza.getTag('close', namespace=NS_IBB)): self.StreamCloseHandler(conn, stan...
'Handles opening of new incoming stream. Used internally.'
def StreamOpenHandler(self, conn, stanza):
"\n<iq type='set' \n from='romeo@montague.net/orchard'\n to='juliet@capulet.com/balcony'\n id='inband_1'>\n <open sid='mySID' \n block-size='4096'\n xmlns='http://jabber.org/protocol/ibb'/>\...
'Start new stream. You should provide stream id \'sid\', the endpoind jid \'to\', the file object containing info for send \'fp\'. Also the desired blocksize can be specified. Take into account that recommended stanza size is 4k and IBB uses base64 encoding that increases size of data by 1/3.'
def OpenStream(self, sid, to, fp, blocksize=3000):
if (sid in self._streams.keys()): return if (not JID(to).getResource()): return self._streams[sid] = {'direction': ('|>' + to), 'block-size': blocksize, 'fp': fp, 'seq': 0} self._owner.RegisterCycleHandler(self.SendHandler) syn = Protocol('iq', to, 'set', payload=[Node((NS_IBB + ' ...
'Send next portion of data if it is time to do it. Used internally.'
def SendHandler(self, conn):
self.DEBUG('SendHandler called', 'info') for sid in self._streams.keys(): stream = self._streams[sid] if (stream['direction'][:2] == '|>'): cont = 1 elif (stream['direction'][0] == '>'): chunk = stream['fp'].read(stream['block-size']) if chunk: ...
'Receive next portion of incoming datastream and store it write it to temporary file. Used internally.'
def ReceiveHandler(self, conn, stanza):
(sid, seq, data) = (stanza.getTagAttr('data', 'sid'), stanza.getTagAttr('data', 'seq'), stanza.getTagData('data')) self.DEBUG(('ReceiveHandler called sid->%s seq->%s' % (sid, seq)), 'info') try: seq = int(seq) data = base64.decodestring(data) except: seq = '' dat...
'Handle stream closure due to all data transmitted. Raise xmpppy event specifying successfull data receive.'
def StreamCloseHandler(self, conn, stanza):
sid = stanza.getTagAttr('close', 'sid') self.DEBUG(('StreamCloseHandler called sid->%s' % sid), 'info') if (sid in self._streams.keys()): conn.send(stanza.buildReply('result')) conn.Event(self.DBG_LINE, 'SUCCESSFULL RECEIVE', self._streams[sid]) del self._streams[sid] el...
'Handle stream closure due to all some error while receiving data. Raise xmpppy event specifying unsuccessfull data receive.'
def StreamBrokenHandler(self, conn, stanza):
syn_id = stanza.getID() self.DEBUG(('StreamBrokenHandler called syn_id->%s' % syn_id), 'info') for sid in self._streams.keys(): stream = self._streams[sid] if (stream['syn_id'] == syn_id): if (stream['direction'][0] == '<'): conn.Event(self.DBG_LINE, 'ERROR ...
'Handle remote side reply about is it agree or not to receive our datastream. Used internally. Raises xmpppy event specfiying if the data transfer is agreed upon.'
def StreamOpenReplyHandler(self, conn, stanza):
syn_id = stanza.getID() self.DEBUG(('StreamOpenReplyHandler called syn_id->%s' % syn_id), 'info') for sid in self._streams.keys(): stream = self._streams[sid] if (stream['syn_id'] == syn_id): if (stanza.getType() == 'error'): if (stream['direction'][0] == '<...
'flag can be of folowing types: None - this msg will always be shown if any debugging is on flag - will be shown if flag is active (flag1,flag2,,,) - will be shown if any of the given flags are active if prefix / sufix are not given, default ones from init will be used lf = -1 means strip linefeed if pressent lf = 1 me...
def show(self, msg, flag=None, prefix=None, sufix=None, lf=0):
if self.validate_flags: self._validate_flag(flag) if (not self.is_active(flag)): return if prefix: pre = prefix else: pre = self.prefix if sufix: suf = sufix else: suf = self.sufix if (self.time_stamp == 2): output = ('%s%s ' % (pre,...
'If given flag(s) should generate output.'
def is_active(self, flag):
if (not self.active): return 0 if ((not flag) or (flag in self.active)): return 1 elif (type(flag) in (type(()), type([]))): for s in flag: if (s in self.active): return 1 return 0
'returns 1 if any flags where actually set, otherwise 0.'
def active_set(self, active_flags=None):
r = 0 ok_flags = [] if (not active_flags): self.active = [] elif (type(active_flags) in (types.TupleType, types.ListType)): flags = self._as_one_list(active_flags) for t in flags: if (t not in self.debug_flags): sys.stderr.write(('Invalid debugflag ...
'returns currently active flags.'
def active_get(self):
return self.active
'init param might contain nested lists, typically from group flags. This code organises lst and remves dupes'
def _as_one_list(self, items):
if ((type(items) != type([])) and (type(items) != type(()))): return [items] r = [] for l in items: if (type(l) == type([])): lst2 = self._as_one_list(l) for l2 in lst2: self._append_unique_str(r, l2) elif (l == None): continue ...
'filter out any dupes.'
def _append_unique_str(self, lst, item):
if (type(item) != type('')): msg2 = ('%s' % item) raise 'Invalid item type (should be string)', msg2 if (item not in lst): lst.append(item) return lst
'verify that flag is defined.'
def _validate_flag(self, flags):
if flags: for f in self._as_one_list(flags): if (not (f in self.debug_flags)): msg2 = ('%s' % f) raise 'Invalid debugflag given', msg2
'if multiple instances of Debug is used in same app, some flags might be created multiple time, filter out dupes'
def _remove_dupe_flags(self):
unique_flags = [] for f in self.debug_flags: if (f not in unique_flags): unique_flags.append(f) self.debug_flags = unique_flags
'Get media ID set, by your hashtag'
def get_media_id_by_tag(self, tag):
if self.login_status: log_string = ('Get media id by tag: %s' % tag) self.write_log(log_string) if (self.login_status == 1): url_tag = (self.url_tag % tag) try: r = self.s.get(url_tag) all_data = json.loads(r.text) ...
'Like all media ID that have self.media_by_tag'
def like_all_exist_media(self, media_size=(-1), delay=True):
if self.login_status: if (self.media_by_tag != 0): i = 0 for d in self.media_by_tag: if ((media_size > 0) or (media_size < 0)): media_size -= 1 l_c = self.media_by_tag[i]['likes']['count'] if (((l_c <= self.m...
'Send http request to like media by ID'
def like(self, media_id):
if self.login_status: url_likes = (self.url_likes % media_id) try: like = self.s.post(url_likes) last_liked_media_id = media_id except: self.write_log('Except on like!') like = 0 return like
'Send http request to unlike media by ID'
def unlike(self, media_id):
if self.login_status: url_unlike = (self.url_unlike % media_id) try: unlike = self.s.post(url_unlike) except: self.write_log('Except on unlike!') unlike = 0 return unlike
'Send http request to comment'
def comment(self, media_id, comment_text):
if self.login_status: comment_post = {'comment_text': comment_text} url_comment = (self.url_comment % media_id) try: comment = self.s.post(url_comment, data=comment_post) if (comment.status_code == 200): self.comments_counter += 1 log_s...
'Send http request to follow'
def follow(self, user_id):
if self.login_status: url_follow = (self.url_follow % user_id) try: follow = self.s.post(url_follow) if (follow.status_code == 200): self.follow_counter += 1 log_string = ('Followed: %s #%i.' % (user_id, self.follow_counter)) ...
'Send http request to unfollow'
def unfollow(self, user_id):
if self.login_status: url_unfollow = (self.url_unfollow % user_id) try: unfollow = self.s.post(url_unfollow) if (unfollow.status_code == 200): self.unfollow_counter += 1 log_string = ('Unfollow: %s #%i.' % (user_id, self.unfollow_counter)...
'Unfollow on cleanup by @rjmayott'
def unfollow_on_cleanup(self, user_id):
if self.login_status: url_unfollow = (self.url_unfollow % user_id) try: unfollow = self.s.post(url_unfollow) if (unfollow.status_code == 200): self.unfollow_counter += 1 log_string = ('Unfollow: %s #%i of %i.' % (user_id, self.unfol...
'Star loop, that get media ID by your tag list, and like it'
def auto_mod(self):
if self.login_status: while True: random.shuffle(self.tag_list) self.get_media_id_by_tag(random.choice(self.tag_list)) self.like_all_exist_media(random.randint(1, self.max_like_for_one_tag))
'Make some random for next iteration'
def add_time(self, time):
return ((time * 0.9) + ((time * 0.2) * random.random()))
'Write log by print() or logger'
def write_log(self, log_text):
if (self.log_mod == 0): try: print log_text except UnicodeEncodeError: print 'Your text has unicode problem!' elif (self.log_mod == 1): if (self.log_file == 0): self.log_file = 1 now_time = datetime.datetime.now() se...
'Search user_id or user_name, if you don\'t have it.'
def search_user(self, user_id=None, user_name=None):
self.user_id = (user_id or False) self.user_name = (user_name or False) if ((not self.user_id) and (not self.user_name)): return False elif self.user_id: search_url = (self.url_list[self.i_a]['search_id'] % self.user_id) elif self.user_name: search_url = (self.url_list[self.i...
'Base constructor for ESPLoader bootloader interaction Don\'t call this constructor, either instantiate ESP8266ROM or ESP32ROM, or use ESPLoader.detect_chip(). This base class has all of the instance methods for bootloader functionality supported across various chips & stub loaders. Subclasses replace the functions the...
def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD):
if isinstance(port, serial.Serial): self._port = port else: self._port = serial.serial_for_url(port) self._slip_reader = slip_reader(self._port) self._set_port_baudrate(baud)
'Use serial access to detect the chip type. We use the UART\'s datecode register for this, it\'s mapped at the same address on ESP8266 & ESP32 so we can use one memory read and compare to the datecode register for each chip type. This routine automatically performs ESPLoader.connect() (passing connect_mode parameter) a...
@staticmethod def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset'):
detect_port = ESPLoader(port, baud) detect_port.connect(connect_mode) print('Detecting chip type...', end='') sys.stdout.flush() date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR) for cls in [ESP8266ROM, ESP32ROM]: if (date_reg == cls.DATE_REG_VALUE): inst = ...
'Execute a command with \'command\', check the result code and throw an appropriate FatalError if it fails. Returns the "result" of a successful command.'
def check_command(self, op_description, op=None, data='', chk=0):
(val, data) = self.command(op, data, chk) if (len(data) < self.STATUS_BYTES_LENGTH): raise FatalError(('Failed to %s. Only got %d byte status response.' % (op_description, len(data)))) status_bytes = data[(- self.STATUS_BYTES_LENGTH):] if (byte(status_bytes, 0) != 0): ...
'A single connection attempt, with esp32r0 workaround options'
def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
last_error = None if (mode != 'no_reset'): self._port.setDTR(False) self._port.setRTS(True) time.sleep(0.1) if esp32r0_delay: time.sleep(1.2) self._port.setDTR(True) self._port.setRTS(False) if esp32r0_delay: time.sleep(0.4) ...
'Try connecting repeatedly until successful, or giving up'
def connect(self, mode='default_reset'):
print('Connecting...', end='') sys.stdout.flush() last_error = None try: for _ in range(10): last_error = self._connect_attempt(mode=mode, esp32r0_delay=False) if (last_error is None): return last_error = self._connect_attempt(mode=mode, esp32r...
'Start downloading compressed data to Flash (performs an erase) Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.'
@stub_and_esp32_function_only def flash_defl_begin(self, size, compsize, offset):
num_blocks = (((compsize + self.FLASH_WRITE_SIZE) - 1) // self.FLASH_WRITE_SIZE) erase_blocks = (((size + self.FLASH_WRITE_SIZE) - 1) // self.FLASH_WRITE_SIZE) self._port.timeout = START_FLASH_TIMEOUT t = time.time() if self.IS_STUB: write_size = size else: write_size = (erase_bl...
'Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command.'
def flash_spi_attach(self, hspi_arg):
arg = struct.pack('<I', hspi_arg) if (not self.IS_STUB): is_legacy = 0 arg += struct.pack('BBBB', is_legacy, 0, 0, 0) self.check_command('configure SPI flash pins', ESP32ROM.ESP_SPI_ATTACH, arg)
'Tell the ESP bootloader the parameters of the chip Corresponds to the "flashchip" data structure that the ROM has in RAM. \'size\' is in bytes. All other flash parameters are currently hardcoded (on ESP8266 these are mostly ignored by ROM code, on ESP32 I\'m not sure.)'
def flash_set_parameters(self, size):
fl_id = 0 total_size = size block_size = (64 * 1024) sector_size = (4 * 1024) page_size = 256 status_mask = 65535 self.check_command('set SPI params', ESP32ROM.ESP_SPI_SET_PARAMS, struct.pack('<IIIIII', fl_id, total_size, block_size, sector_size, page_size, status_mask))
'Run an arbitrary SPI flash command. This function uses the "USR_COMMAND" functionality in the ESP SPI hardware, rather than the precanned commands supported by hardware. So the value of spiflash_command is an actual command byte, sent over the wire. After writing command byte, writes \'data\' to MOSI and then reads ba...
def run_spiflash_command(self, spiflash_command, data='', read_bits=0):
SPI_USR_COMMAND = (1 << 31) SPI_USR_MISO = (1 << 28) SPI_USR_MOSI = (1 << 27) base = self.SPI_REG_BASE SPI_CMD_REG = (base + 0) SPI_USR_REG = (base + 28) SPI_USR1_REG = (base + 32) SPI_USR2_REG = (base + 36) SPI_W0_REG = (base + self.SPI_W0_OFFS) if self.SPI_HAS_MOSI_DLEN_REG: ...
'Read up to 24 bits (num_bytes) of SPI flash status register contents via RDSR, RDSR2, RDSR3 commands Not all SPI flash supports all three commands. The upper 1 or 2 bytes may be 0xFF.'
def read_status(self, num_bytes=2):
SPIFLASH_RDSR = 5 SPIFLASH_RDSR2 = 53 SPIFLASH_RDSR3 = 21 status = 0 shift = 0 for cmd in [SPIFLASH_RDSR, SPIFLASH_RDSR2, SPIFLASH_RDSR3][0:num_bytes]: status += (self.run_spiflash_command(cmd, read_bits=8) << shift) shift += 8 return status
'Write up to 24 bits (num_bytes) of new status register num_bytes can be 1, 2 or 3. Not all flash supports the additional commands to write the second and third byte of the status register. When writing 2 bytes, esptool also sends a 16-byte WRSR command (as some flash types use this instead of WRSR2.) If the set_non_vo...
def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
SPIFLASH_WRSR = 1 SPIFLASH_WRSR2 = 49 SPIFLASH_WRSR3 = 17 SPIFLASH_WEVSR = 80 SPIFLASH_WREN = 6 SPIFLASH_WRDI = 4 enable_cmd = (SPIFLASH_WREN if set_non_volatile else SPIFLASH_WEVSR) if (num_bytes == 2): self.run_spiflash_command(enable_cmd) self.run_spiflash_command(SPIF...
'Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29'
def chip_id(self):
id0 = self.read_reg(self.ESP_OTP_MAC0) id1 = self.read_reg(self.ESP_OTP_MAC1) return ((id0 >> 24) | ((id1 & MAX_UINT24) << 8))
'Read MAC from OTP ROM'
def read_mac(self):
mac0 = self.read_reg(self.ESP_OTP_MAC0) mac1 = self.read_reg(self.ESP_OTP_MAC1) mac3 = self.read_reg(self.ESP_OTP_MAC3) if (mac3 != 0): oui = (((mac3 >> 16) & 255), ((mac3 >> 8) & 255), (mac3 & 255)) elif (((mac1 >> 16) & 255) == 0): oui = (24, 254, 52) elif (((mac1 >> 16) & 255)...
'Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.'
def get_erase_size(self, offset, size):
sectors_per_block = 16 sector_size = self.FLASH_SECTOR_SIZE num_sectors = (((size + sector_size) - 1) // sector_size) start_sector = (offset // sector_size) head_sectors = (sectors_per_block - (start_sector % sectors_per_block)) if (num_sectors < head_sectors): head_sectors = num_sectors...