def html(self): if self.__html: return self.__html from util.xml_tag import tag t = tag(u'font') if self.fontname: t[u'face'] = self.fontname if self.color: t[u'color'] = u'#' + (u''.join(map(lambda x: '%02x' % (x or 0), self.color[:3]))) if self.rightalign: t[u'align'] = u'right' innermost = top = t for attr in ('bold','italic','underline','strike'): if getattr(self,attr): _tag = tag(attr[0]) innermost += _tag innermost = _tag innermost._cdata = self.body self.__html = top._to_xml(pretty=False).strip() return self.__html
def to_tag(self): p = tag('p') tr = tag('b', 'Photos Album:') for photo in self: tr._add_child(photo.to_tag()) p._add_child(tr) return p
def to_tag(self): p = tag('p') p._add_child(tag('a', self.title, href=self.url)) for thing in self: p._add_child(thing.to_tag()) return p
def recv_not(self, msg): data = xml_tag.tag(xml_tag.tag(msg.payload).MSG.BODY._cdata) if not data.OwnerCID: return cid = int(data.OwnerCID) #last_mod = str(data.LastModifiedDate) has_new = bool(data.HasNewItem) if has_new: self.event('contact_profile_update', cid)
def to_tag(self): table = tag('table') tr = tag('tr') a = tag('a', href=self.url) a._add_child(tag('b', self.title + ':')) tr._add_child(a) tr._add_child(tag('td',self.description)) table._add_child(tr) return table
def recv_not(self, msg): data = xml_tag.tag(xml_tag.tag(msg.payload).MSG.BODY._cdata) if not data.OwnerCID: return cid = int(data.OwnerCID) # last_mod = str(data.LastModifiedDate) has_new = bool(data.HasNewItem) if has_new: self.event("contact_profile_update", cid)
def _get_profile(self, buddy, callback): request = xml_tag.tag("GetXmlFeed") ri = request.refreshInformation ri.cid = buddy.CID ri.storageAuthCache = "" ri.market = "%s-%s" % (hub.language.lower(), hub.country.upper()) ri.brand = "" ri.maxElementCount = 15 ri.maxCharacterCount = 200 ri.maxImageCount = 6 ri.applicationId = "Messenger Client 8.0" ri.updateAccessedTime = False yesterday = datetime.datetime.today() - datetime.timedelta(1) ri.spaceLastViewed = yesterday.isoformat() ri.profileLastViewed = yesterday.isoformat() ri.contactProfileLastViewed = yesterday.isoformat() ri.isActiveContact = False fs = ri.foreignStore fs.itemType = "Profile" fs.foreignId = "MyProfile" fs.lastChanged = yesterday.isoformat() fs.lastViewed = yesterday.isoformat() auth = xml_tag.tag("AuthTokenHeader") # auth.Token = self.ticket.encode('xml') token = str(self.tokens["spaces.live.com"].received.RequestedSecurityToken.BinarySecurityToken) assert token, token.received._to_xml() auth.Token = escape(token) auth.AuthPolicy = self.tokens["spaces.live.com"].policyref env = xml_tag.tag("envelope") # soap_envelope("http://www.msn.com/webservices/spaces/v1/") env.Header(auth) env.Body(request) # del env._children[0] print env._to_xml(pretty=False) response = xml_tag.post_xml( "http://cid-%X.cc.services.spaces.live.com/contactcard/contactcardservice.asmx" % int(self.self_buddy.CID), env, success=lambda t: self.incoming_profile(t, buddy), error=lambda e: self.incoming_profile(e, buddy, True) # Cookie=token )
def _get_profile(self, buddy, callback): request = xml_tag.tag('GetXmlFeed') ri = request.refreshInformation ri.cid = buddy.CID ri.storageAuthCache = '' ri.market = '%s-%s' % (hub.language.lower(), hub.country.upper()) ri.brand = '' ri.maxElementCount = 15 ri.maxCharacterCount = 200 ri.maxImageCount = 6 ri.applicationId = 'Messenger Client 8.0' ri.updateAccessedTime = False yesterday = datetime.datetime.today() - datetime.timedelta(1) ri.spaceLastViewed = yesterday.isoformat() ri.profileLastViewed = yesterday.isoformat() ri.contactProfileLastViewed = yesterday.isoformat() ri.isActiveContact = False fs = ri.foreignStore fs.itemType = 'Profile' fs.foreignId = 'MyProfile' fs.lastChanged = yesterday.isoformat() fs.lastViewed = yesterday.isoformat() auth = xml_tag.tag('AuthTokenHeader') #auth.Token = self.ticket.encode('xml') token = str(self.tokens['spaces.live.com'].received.RequestedSecurityToken.BinarySecurityToken) assert token, token.received._to_xml() auth.Token = escape(token) auth.AuthPolicy = self.tokens['spaces.live.com'].policyref env = xml_tag.tag("envelope") #soap_envelope("http://www.msn.com/webservices/spaces/v1/") env.Header(auth) env.Body(request) #del env._children[0] print env._to_xml(pretty=False) response = xml_tag.post_xml("http://cid-%X.cc.services.spaces.live.com/contactcard/contactcardservice.asmx" % int(self.self_buddy.CID), env, success=lambda t: self.incoming_profile(t, buddy), error =lambda e: self.incoming_profile(e, buddy, True) #Cookie=token )
def load(self): emoticons_txt = self.path / 'Emoticons.plist' if not emoticons_txt.isfile(): return None, None title = self.path.name with file(emoticons_txt) as f: plist = tag(f.read()) toplevel = plist._children[0] converted = plisttype_to_pytype(toplevel) emoticons = odict() bitmaps = odict() for img_name, info in sorted(converted['Emoticons'].items()): smileys = info['Equivalents'] imgpath = self.path / img_name if imgpath.isfile(): for smiley in smileys: if not smiley: continue # for badly formed plists with <string></string> emoticons[smiley] = S(path=imgpath) if not imgpath in bitmaps: bitmaps[imgpath] = [smiley] else: bitmaps[imgpath].append(smiley) self.name = title self.emoticons = emoticons self.bitmaps = bitmaps self.post_load()
def attrToHTML(textattr): font = textattr.Font attrs = {} if textattr.HasTextColour() and textattr.GetTextColour() != wx.BLACK: attrs['color'] = textattr.GetTextColour().GetAsString( wx.C2S_HTML_SYNTAX) attrs.update(size=str(aimsizes.get(font.PointSize // 15, 4)), face=unicode(font.FaceName)) start = tag('font', **attrs)._to_xml(self_closing=False, pretty=False)[:-7] end = '</font>' if font.Weight == wx.FONTWEIGHT_BOLD: start += '<b>' end = '</b>' + end if font.Style == wx.FONTSTYLE_ITALIC: start += '<i>' end = '</i>' + end if font.Underlined: start += '<u>' end = '</u>' + end return start, end
def recv_adl(self, msg): """ ADL 0 86\r\n <ml><d n="hotmail.com"><c n="digsby06" t="1" l="8" f="digsby%20oh%20sicks" /></d></ml> ADL 19 60\r\n <ml><d n="yahoo.com"><c n="digsby04" l="2" t="32" /></d></ml> """ 'ADL 0 81\r\n<ml><d n="yahoo.com"><c n="digsby06" t="32" l="8" f="asdlkj%20asdlkj" /></d></ml>\r\n' t = xml_tag.tag(str(msg.payload)) for d in t._children: domain = d["n"] for c in d._children: username = c["n"] type = int(c["t"]) l_id = int(c["l"]) mfn = c["f"].decode("url").decode("fuzzy utf8") name = "%s@%s" % (username, domain) if not msg.trid: self._sync_memberships(False) # self.event('recv_contact', name, l_id, None, None) # self.event('contact_alias', name, mfn) if not self.CONNECTED: log.info("got ADL, changing to connected") self.CONNECTED = True
def load(self): emoticons_txt = self.path / 'Emoticons.plist' if not emoticons_txt.isfile(): return None, None title = self.path.name with file(emoticons_txt) as f: plist = tag(f.read()) toplevel = plist._children[0] converted = plisttype_to_pytype(toplevel) emoticons = odict() bitmaps = odict() for img_name, info in sorted(converted['Emoticons'].items()): smileys = info['Equivalents'] imgpath = self.path / img_name if imgpath.isfile(): for smiley in smileys: if not smiley: continue # for badly formed plists with <string></string> emoticons[smiley] = S(path = imgpath) if not imgpath in bitmaps: bitmaps[imgpath] = [smiley] else: bitmaps[imgpath].append(smiley) self.name = title self.emoticons = emoticons self.bitmaps = bitmaps self.post_load()
def get_config(self, w, h): 'returns an embed tag with the parsed values of a given widget config file' url = 'http://config.digsby.com/%s' % (self.id) data = urlopen(url).read() xml = tag(data) sc = xml.style.text.status['color'] bc = xml.style.background['color'] tc = xml.style.title['color'] fc = xml.style.field['color'] xc = xml.style.text['color'] tt = xml.o['title'] nt = xml.o['nick'] d = dict(title=tt, nick=nt, statustext=sc, bgcolor=bc, titletext=tc, field=fc, text=xc) flashvars = urlencode(d) #local_widget = skin.resourcedir() / 'widget' / 'digsby_widget.swf' widget_url = 'http://w.digsby.com/dw.swf' return ( '<embed src="%s%s" type="application/x-shockwave-flash" wmode="transparent" width="%s" height="%s"' '></embed>' % (widget_url, '?STATE=creator&' + flashvars, w, h))
def recv_adl(self, msg): ''' ADL 0 86\r\n <ml><d n="hotmail.com"><c n="digsby06" t="1" l="8" f="digsby%20oh%20sicks" /></d></ml> ADL 19 60\r\n <ml><d n="yahoo.com"><c n="digsby04" l="2" t="32" /></d></ml> ''' 'ADL 0 81\r\n<ml><d n="yahoo.com"><c n="digsby06" t="32" l="8" f="asdlkj%20asdlkj" /></d></ml>\r\n' t = xml_tag.tag(str(msg.payload)) for d in t._children: domain = d['n'] for c in d._children: username = c['n'] type = int(c['t']) l_id = int(c['l']) mfn = c['f'].decode('url').decode('fuzzy utf8') name = '%s@%s' % (username,domain) if not msg.trid: self._sync_memberships(False) # self.event('recv_contact', name, l_id, None, None) # self.event('contact_alias', name, mfn) if not self.CONNECTED: log.info('got ADL, changing to connected') self.CONNECTED = True
def to_tag(self): p = tag('p') for thing in self: p._add_child(thing.to_tag()) return p
def send_uux(self, msg='', callback=sentinel): data = xml_tag.tag('Data') data.PSM = msg data.CurrentMedia = '' data.MachineGuid = uuid.uuid1() self.socket.send(Message('UUX', payload=data._to_xml(pretty=False).encode('utf-8')), trid=True, callback=callback)
def to_tag(self): p = tag('p')#MSNSpaceElement.to_tag(self) for thing in self.contents: p._add_child(thing.to_tag()) return p
def send_uux(self, msg="", callback=sentinel): data = xml_tag.tag("Data") data.PSM = msg data.CurrentMedia = "" data.MachineGuid = uuid.uuid1() self.socket.send( Message("UUX", payload=data._to_xml(pretty=False).encode("utf-8")), trid=True, callback=callback )
def _as_tag(self): t = tag('Ymsg') t['Command'] = self.Command t['Status'] = self.Status t['Version'] = self.Version t['VendorId'] = self.VendorId t['SessionId'] = self.SessionId t._cdata = self.data return t
def send_message(self, fmsg, callback=None): text = fmsg.format_as('plaintext') log.info('OfflineSBAdapter send_message: %r', text) env = soap(self.OIM_NS[1]) env.Header += tag('From', memberName=self.self_buddy.name, #friendlyName=make_header(self.self_buddy.remote_alias), proxy='MSNMSGR', msnpVer=self.version, buildVer=self.CLIENT_STR) env.Header += tag('To',memberName=self.buddy.name) env.Header += tag('Ticket', passport=self.token.encode('xml'), appid=self.appid, lockkey = self.lockkey, ) env.Header += (tag((self.WSRM_NS, 'Sequence')) (tag((self.WSUTIL_NS, 'Identifier'), 'http://messenger.msn.com'), tag('MessageNumber',self.msgnum)) ) env.Body += tag('MessageType','text') env.Body += tag('Content',self._build_message(text)) self.event('send_text_msg', text) def post_success(result): log.info('Post result: %r', result._to_xml(pretty=False)) fault = result._findOne("Fault") if fault: if (OIMExceptions.AuthFailed in fault.faultcode._cdata.strip()): # try authentication again... self.authenticate(fault, success=lambda: self.send_message(fmsg, callback=callback), error =lambda e,*a,**k: (callback.error(e), log.info('Error from authenticate: %r, %r', a,k)) ) else: log.info('Sending message failed: %r', result._to_xml(pretty=False)) callback.error(result) elif result.Header.SequenceAcknowledgment: log.info('Got SequenceAcknowledgment') self.msgnum += 1 callback.success() else: log.info('Unknown response from posting OIM: %r', result._to_xml(pretty=False)) def post_error(exception): log.info('Post exception: %r, %r, %r', type(exception), (exception._to_xml(pretty=False) if hasattr(exception, '_to_xml') else ''), vars(exception)) callback.error(exception) self.post(env, success=post_success, error=post_error)
def recv_ipg(self, msg): log.debug('Received IPG command') log.debug(str(msg)) n = tag(msg.payload) sender = n.FROM['name'] message = n.MSG.BODY.TEXT if sender.startswith('tel:+'): sender = sender[4:] self.event('recv_sms', sender, unicode(message))
def icq_cli_07d0_1482(o, phone, message): from util.xml_tag import tag icq_sms_message = tag('icq_sms_message') icq_sms_message.destination = phone icq_sms_message.text = message icq_sms_message.senders_UIN = o.username try: name = o.self_buddy.first + o.self_buddy.last except Exception: name = o.username icq_sms_message.senders_name = name icq_sms_message.delivery_receipt = 'Yes' icq_sms_message.time = str(datetime.today()) return icq_cli_07d0(o, struct.pack('<HHHQ',0x1482, 1, 16, 0) + oscar.util.tlv(0, str(icq_sms_message._to_xml(pretty=False))))
def recv_ipg(self, msg): log.debug("Received IPG command") log.debug(str(msg)) n = tag(msg.payload) sender = n.FROM["name"] message = n.MSG.BODY.TEXT if sender.startswith("tel:+"): sender = sender[4:] self.event("recv_sms", sender, unicode(message))
def __init__(self, msn, name=None): ''' MSNBuddy(msn, name=None) Create a new MSNBuddy object with an MSN 'owner' object and (optionally) a name. MSNBuddies default to not blocked, offline, not mobile, and idle since the start of the UNIX epoch. @param msn: @param name: ''' self._status = 'unknown' self._status_message = '' self._got_presence = False self.phone_home = \ self.phone_work = \ self.phone_mobile = \ self.allow_mobile = \ self.enable_wireless = \ self.remote_alias = \ self.has_blog = None self.msn_obj = None self._idle_start = 0 self.info = {} self.role_ids = {} self.pending_auth = False fixedname = ''.join(url_decode(name).split()) common.buddy.__init__(self, fixedname, msn) if self is self.protocol.self_buddy: from common import profile profile.account_manager.buddywatcher.unregister(self) #assert is_email(fixedname), fixedname self.CID = 0 self.space = None if self._space: try: self.update_contact_card(tag(self._space)) except: self._space = None self.mships = {} self.contactsoap = None self.membersoap = None self._btype = 1
def send_rml(self, buddy, l_id): if buddy._btype == "mob": return n = buddy.name u, d = n.split("@") ml = xml_tag.tag("ml") ml.d["n"] = d ml.d.c["n"] = u ml.d.c["l"] = dict(forward=1, allow=2, block=4, reverse=8, pending=16)[l_id.lower()] ml.d.c["t"] = dict(im=1, msn=1, mob=4, fed=32)[buddy._btype] self.socket.send(Message("RML", payload=ml._to_xml(pretty=False).strip()), **defcb)
def send_rml(self, buddy, l_id): if buddy._btype == 'mob': return n = buddy.name u, d = n.split('@') ml = xml_tag.tag('ml') ml.d['n']=d ml.d.c['n']=u ml.d.c['l']=dict(forward=1, allow=2, block=4, reverse=8, pending=16)[l_id.lower()] ml.d.c['t']=dict(im=1, msn=1, mob=4, fed=32)[buddy._btype] self.socket.send(Message('RML', payload=ml._to_xml(pretty=False).strip()), **defcb)
def __str__(self): t = tag('Session') t['Payload'] = self.Payload t['Channel'] = self.Channel session_id = getattr(self.session, 'session_id', None) if session_id: t['ClientHash'] = self.ClientHash t['SessionId'] = self.SessionId else: t['Secret'] = self.session.Secret t['ClientCounter'] = self.cc t['ClientSeqno'] = self.cc if self.server: server_seqno = getattr(self.session, 'ServerSeqno', None) if server_seqno: t['ServerSeqno'] = server_seqno if self.payload: t.Ymsg = self.payload._as_tag() #should all be utf-8 already, but we don't want to accidently go back to unicode via ascii l = t._to_xml(pretty=False, self_closing=False, return_list=True) return ''.join((s if isinstance(s, bytes) else s.encode('utf-8')) for s in l)
def recieve_response(self, req, resp=None): if resp is None: #urllib compatibility resp = req del req #should probably all be treated the same, who knows what can come back from where, nor should we care. data = resp.read() log.debug_s('yahoo recieved\n%r', data) Session = tag(data) #deal with sequence numbers if Session['Payload'] == 'yes': ymsg = Session.Ymsg if not isinstance(ymsg, list): ymsg = [ymsg] for pkt in ymsg: self.handle_packet(pkt, Session) try: self.ServerSeqno = Session['ServerSeqno'] except KeyError: pass
def attrToHTML(textattr): font = textattr.Font attrs = {} if textattr.HasTextColour() and textattr.GetTextColour() != wx.BLACK: attrs['color'] = textattr.GetTextColour().GetAsString(wx.C2S_HTML_SYNTAX) attrs.update(size = str(aimsizes.get(font.PointSize // 15, 4)), face = unicode(font.FaceName)) start = tag('font', **attrs)._to_xml(self_closing = False, pretty = False)[:-7] end = '</font>' if font.Weight == wx.FONTWEIGHT_BOLD: start += '<b>'; end = '</b>' + end if font.Style == wx.FONTSTYLE_ITALIC: start += '<i>'; end = '</i>' + end if font.Underlined: start += '<u>'; end = '</u>' + end return start, end
def send_fqy(self, n, flags): 'FQY 10 51\r\n<ml l="1"><d n="yahoo.com"><c n="synae" /></d></ml>' 'FQY 17 53\r\n<ml l="2"><d n="yahoo.com"><c n="digbsy04" /></d></ml>' u, d = n.split('@') ml = xml_tag.tag('ml') ml.d['n']=d ml.d.c['n']=u if not isint(flags): d = dict(f=1, a=2, b=4, r=8, p=16) if isinstance(flags, basestring): flags = [flags] flags = sum(d[f[0].lower()] for f in flags) if flags == 1: flags = 2 ml['l']=flags xml = ml._to_xml(pretty=False) self.socket.send(Message('FQY', payload=xml), trid=True, callback=sentinel)
def send_fqy(self, n, flags): 'FQY 10 51\r\n<ml l="1"><d n="yahoo.com"><c n="synae" /></d></ml>' 'FQY 17 53\r\n<ml l="2"><d n="yahoo.com"><c n="digbsy04" /></d></ml>' u, d = n.split("@") ml = xml_tag.tag("ml") ml.d["n"] = d ml.d.c["n"] = u if not isint(flags): d = dict(f=1, a=2, b=4, r=8, p=16) if isinstance(flags, basestring): flags = [flags] flags = sum(d[f[0].lower()] for f in flags) if flags == 1: flags = 2 ml["l"] = flags xml = ml._to_xml(pretty=False) self.socket.send(Message("FQY", payload=xml), trid=True, callback=sentinel)
def __str__(self): t = tag('Session') t['Payload'] = self.Payload t['Channel'] = self.Channel session_id = getattr(self.session, 'session_id', None) if session_id: t['ClientHash'] = self.ClientHash t['SessionId'] = self.SessionId else: t['Secret'] = self.session.Secret t['ClientCounter'] = self.cc t['ClientSeqno'] = self.cc if self.server: server_seqno = getattr(self.session, 'ServerSeqno', None) if server_seqno: t['ServerSeqno'] = server_seqno if self.payload: t.Ymsg = self.payload._as_tag() #should all be utf-8 already, but we don't want to accidently go back to unicode via ascii l = t._to_xml(pretty=False, self_closing=False, return_list=True) return ''.join( (s if isinstance(s, bytes) else s.encode('utf-8')) for s in l)
def get_config(self,w,h): 'returns an embed tag with the parsed values of a given widget config file' url = 'http://config.digsby.com/%s' % (self.id) data = urlopen(url).read() xml = tag(data) sc = xml.style.text.status['color'] bc = xml.style.background['color'] tc = xml.style.title['color'] fc = xml.style.field['color'] xc = xml.style.text['color'] tt = xml.o['title'] nt = xml.o['nick'] d = dict(title=tt, nick=nt, statustext=sc, bgcolor=bc, titletext=tc, field=fc, text=xc) flashvars = urlencode(d) #local_widget = skin.resourcedir() / 'widget' / 'digsby_widget.swf' widget_url = 'http://w.digsby.com/dw.swf' return ('<embed src="%s%s" type="application/x-shockwave-flash" wmode="transparent" width="%s" height="%s"' '></embed>' % (widget_url, '?STATE=creator&' + flashvars, w, h))
</element> </elements> <lastUpdate> 2007-04-18T08:20:01.167-07:00 </lastUpdate> <theme> <name> personalspacegree </name> <titleBar foreground="333333" fontFace="" background="f4fbf7" /> <clientArea foreground="444444" backgroundImage="http://shared.live.com/jdIfE-NNCwb0XZTwVBd6PpCWk!2k7FEfmc0OX5OC0rZ-I0WjzyccY5aYuUiTkMo2blaFQRxUooU/personalspacegree/3379/img/green_card_bkgd.gif" fontFace="" background="FFFFFF" /> <toolbar foreground="333333" fontFace="" background="f4fbf7" /> <border topLeftImage="http://sc1.sclive.net/11.01.3810.0000/Web/Contacts/images/card_ul.gif" bottomLeftImage="http://sc2.sclive.net/11.01.3810.0000/Web/Contacts/images/card_ll.gif" bottomRightImage="http://sc4.sclive.net/11.01.3810.0000/Web/Contacts/images/card_lr.gif" outline="7F7F7F" topRightImage="http://sc3.sclive.net/11.01.3810.0000/Web/Contacts/images/card_ur.gif" /> </theme> <liveTheme> <themeName> personalspacegree </themeName> <head backgroundImage="http://shared.live.com/jdIfE-NNCwb0XZTwVBd6PpCWk!2k7FEfmc0OX5OC0rZ-I0WjzyccY5aYuUiTkMo2blaFQRxUooU/personalspacegree/3379/img/SmallBannerImage.jpg" textColor="333333" linkColor="006629" backgroundColor="f4fbf7" /> <body accordionHoverColor="aad2ba" secondaryLinkColor="7F7F7F" dividerColor="8ed4ab" backgroundImage="" backgroundColor="f4fbf7" linkColor="006629" textColor="333333" /> <actions linkColor="333333" backgroundColor="f4fbf7" /> </liveTheme> </contactCard> '''.strip().replace('&', '&') if __name__ == '__main__': b = Storage(name='*****@*****.**') card = MSNSpace(b, tag(CONTACT_CARD)) print card.to_tag()._to_xml()
def to_tag(self): a = tag('a', href=self.url) a._add_child('b', self.title) return a
def soap(ns): env = tag((('soap',SOAP_NS), 'Envelope'), xmlns=ns) env += ('soap','Header'), env += ('soap','Body'), return env
def send_message(self, fmsg, callback=None): text = fmsg.format_as('plaintext') log.info('OfflineSBAdapter send_message: %r', text) env = soap(self.OIM_NS[1]) env.Header += tag( 'From', memberName=self.self_buddy.name, #friendlyName=make_header(self.self_buddy.remote_alias), proxy='MSNMSGR', msnpVer=self.version, buildVer=self.CLIENT_STR) env.Header += tag('To', memberName=self.buddy.name) env.Header += tag( 'Ticket', passport=self.token.encode('xml'), appid=self.appid, lockkey=self.lockkey, ) env.Header += (tag( (self.WSRM_NS, 'Sequence'))(tag((self.WSUTIL_NS, 'Identifier'), 'http://messenger.msn.com'), tag('MessageNumber', self.msgnum))) env.Body += tag('MessageType', 'text') env.Body += tag('Content', self._build_message(text)) self.event('send_text_msg', text) def post_success(result): log.info('Post result: %r', result._to_xml(pretty=False)) fault = result._findOne("Fault") if fault: if (OIMExceptions.AuthFailed in fault.faultcode._cdata.strip()): # try authentication again... self.authenticate( fault, success=lambda: self.send_message(fmsg, callback=callback), error=lambda e, *a, **k: (callback.error(e), log.info('Error from authenticate: %r, %r', a, k))) else: log.info('Sending message failed: %r', result._to_xml(pretty=False)) callback.error(result) elif result.Header.SequenceAcknowledgment: log.info('Got SequenceAcknowledgment') self.msgnum += 1 callback.success() else: log.info('Unknown response from posting OIM: %r', result._to_xml(pretty=False)) def post_error(exception): log.info( 'Post exception: %r, %r, %r', type(exception), (exception._to_xml( pretty=False) if hasattr(exception, '_to_xml') else ''), vars(exception)) callback.error(exception) self.post(env, success=post_success, error=post_error)
def soap(ns): env = tag((('soap', SOAP_NS), 'Envelope'), xmlns=ns) env += ('soap', 'Header'), env += ('soap', 'Body'), return env
def to_tag(self): return tag('p', '%s<br />%s' % (self.title, self.description))
def get_carrier(yahoo, sms_number, callback = None): ''' Uses a Yahoo webservice to find a carrier string (like 'pcsms.us.version') for a mobile phone number. Requires Yahoo web cookies (in the yahoo.cookie_str property). These carrier strings can be used to send SMS messages through the Yahoo servers (see the send_sms function below). ''' # has this number's carrier already been looked up? global _carriers if sms_number in _carriers: return callback.success(_carriers[sms_number]) # options for the request version = '8.1.0.209' intl = 'us' # build request XML validate = tag('validate', intl = intl, version = version, qos = '0') validate.mobile_no['msisdn'] = sms_number validate._cdata = '\n' # setup callbacks def on_response(validate): log.info('HTTP response to get_carrier:\n%s', validate._to_xml()) status = unicode(validate.mobile_no.status) log.info('<status> tag contents: %s', status) if status == 'Valid': # got a valid carrier string; memoize it and return to the success callback. carrier = str(validate.mobile_no.carrier) _carriers[sms_number] = carrier log.info('carrier for %s: %s', sms_number, carrier) return callback.success(carrier) elif status == 'Unknown': log.critical('unknown carrier for %s', sms_number) return callback.error() else: log.critical('unknown XML returned from mobile carrier lookup service') return callback.error() def on_error(validate): log.critical('could not connect to mobile carrier lookup web service') return callback.error() # setup HTTP POST url = 'http://validate.msg.yahoo.com/mobileno?intl=%s&version=%s' % (intl, version) headers = {'Cookie': yahoo.cookie_str, 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5)', 'Cache-Control': 'no-cache'} log.info('POSTing SMS carrier request to %s', url) xmlstr = validate._to_xml(self_closing = False, pretty = False) log.info(xmlstr) # POST post_xml(url, xmlstr, success = on_response, error = on_error, **headers) ''' POST /mobileno?intl=us&version=8.1.0.209 HTTP/1.1 Cookie: T=z=Vr0OGBVxJPGB9u7bOG1linxMjI2BjUyNjA2NU81NzA-&a=QAE&sk=DAAGhaQDlIYJTS&d=c2wBTlRVeEFUSTFNVGN4TWpneU1EYy0BYQFRQUUBenoBVnIwT0dCZ1dBAXRpcAFCV0JvaUE-; path=/; domain=.yahoo.com; Y=v=1&n=50s9nph28dhu3&l=386i1oqs/o&p=m2g0e3d012000000&r=g6&lg=us&intl=us&np=1; path=/; domain=.yahoo.com ;B=a6d0ooh2qsp2r&b=3&s=ko User-Agent: Mozilla/4.0 (compatible; MSIE 5.5) Host: validate.msg.yahoo.com Content-Length: 105 Cache-Control: no-cache <validate intl="us" version="8.1.0.209" qos="0"><mobile_no msisdn="17248406085"></mobile_no> </validate> ''' success = \ ''' HTTP/1.1 200 OK Date: Fri, 04 May 2007 15:09:26 GMT P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV" Content-Length: 140 Connection: close Content-Type: text/html <validate> <mobile_no msisdn="17248406085"> <status>Valid</status> <carrier>pcsms.us.verizon</carrier> </mobile_no> </validate> ''' error = \ '''
def to_tag(self): a = tag('a', href=self.url) a._add_child(tag('img', src=self.web_url, alt=self.tooltip, width=self.WIDTH, height=self.HEIGHT)) return a
def to_tag(self): link = tag('a', self.title, href=self.url) return tag('p', 'New post: %s<br />%s' % (link._to_xml(), self.description))
def get_carrier(yahoo, sms_number, callback=None): """ Uses a Yahoo webservice to find a carrier string (like 'pcsms.us.version') for a mobile phone number. Requires Yahoo web cookies (in the yahoo.cookie_str property). These carrier strings can be used to send SMS messages through the Yahoo servers (see the send_sms function below). """ # has this number's carrier already been looked up? global _carriers if sms_number in _carriers: return callback.success(_carriers[sms_number]) # options for the request version = "8.1.0.209" intl = "us" # build request XML validate = tag("validate", intl=intl, version=version, qos="0") validate.mobile_no["msisdn"] = sms_number validate._cdata = "\n" # setup callbacks def on_response(validate): log.info("HTTP response to get_carrier:\n%s", validate._to_xml()) status = unicode(validate.mobile_no.status) log.info("<status> tag contents: %s", status) if status == "Valid": # got a valid carrier string; memoize it and return to the success callback. carrier = str(validate.mobile_no.carrier) _carriers[sms_number] = carrier log.info("carrier for %s: %s", sms_number, carrier) return callback.success(carrier) elif status == "Unknown": log.critical("unknown carrier for %s", sms_number) return callback.error() else: log.critical("unknown XML returned from mobile carrier lookup service") return callback.error() def on_error(validate): log.critical("could not connect to mobile carrier lookup web service") return callback.error() # setup HTTP POST url = "http://validate.msg.yahoo.com/mobileno?intl=%s&version=%s" % (intl, version) headers = { "Cookie": yahoo.cookie_str, "User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5)", "Cache-Control": "no-cache", } log.info("POSTing SMS carrier request to %s", url) xmlstr = validate._to_xml(self_closing=False, pretty=False) log.info(xmlstr) # POST post_xml(url, xmlstr, success=on_response, error=on_error, **headers) """ POST /mobileno?intl=us&version=8.1.0.209 HTTP/1.1 Cookie: T=z=Vr0OGBVxJPGB9u7bOG1linxMjI2BjUyNjA2NU81NzA-&a=QAE&sk=DAAGhaQDlIYJTS&d=c2wBTlRVeEFUSTFNVGN4TWpneU1EYy0BYQFRQUUBenoBVnIwT0dCZ1dBAXRpcAFCV0JvaUE-; path=/; domain=.yahoo.com; Y=v=1&n=50s9nph28dhu3&l=386i1oqs/o&p=m2g0e3d012000000&r=g6&lg=us&intl=us&np=1; path=/; domain=.yahoo.com ;B=a6d0ooh2qsp2r&b=3&s=ko User-Agent: Mozilla/4.0 (compatible; MSIE 5.5) Host: validate.msg.yahoo.com Content-Length: 105 Cache-Control: no-cache <validate intl="us" version="8.1.0.209" qos="0"><mobile_no msisdn="17248406085"></mobile_no> </validate> """ success = """ HTTP/1.1 200 OK Date: Fri, 04 May 2007 15:09:26 GMT P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV" Content-Length: 140 Connection: close Content-Type: text/html <validate> <mobile_no msisdn="17248406085"> <status>Valid</status> <carrier>pcsms.us.verizon</carrier> </mobile_no> </validate> """ error = """