home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / jabber / JabberBuddy.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  19.4 KB  |  567 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from peak.util.imports import lazyModule
  5. import common
  6. import hashlib
  7. import jabber
  8. from jabber import JID, Presence
  9. from util import callsback, Storage as S, odict, threaded
  10. from util.cacheable import urlcacheopen, cproperty
  11. from common.actions import action
  12. from jabber.objects.nick import NICK_NS, Nick
  13. from common import pref
  14. skin = lazyModule('gui.skin')
  15. from urllib import quote
  16. from pyxmpp.jabber.vcard import VCardString
  17.  
  18. VCardString.decode = lambda s, *a: s.value.decode(*a)
  19. from jabber import VCard
  20. from util.observe import ObservableProperty as oproperty
  21. import logging
  22. log = logging.getLogger('jabber.buddy')
  23. GTALK = 'gtalk'
  24. GTALK_MOBILE_DOMAINS = ('sms.talk.google.com',)
  25. GTALK_DOMAINS = ('gmail.com', 'googlemail.com') + GTALK_MOBILE_DOMAINS
  26. JABBER = 'jabber'
  27.  
  28. def isGTalk(resource):
  29.     if not isinstance(resource, basestring):
  30.         return False
  31.     reslower = resource.lower()
  32.     return (any,)((lambda .0: for x in .0:
  33. reslower.startswith(x))(('talk.', 'gmail.', 'talkgadget', 'ics')))
  34.  
  35.  
  36. no_widget = lambda self: if getattr(self, 'iswidget', False):
  37. NoneTrue
  38. ADDRESS_KEYS = 'street,extadr,locality,region,pcode,ctry'.split(',')
  39. WORK_KEYS = 'company department postition role'.split()
  40. SUBSCRIPTION_TO = ('to', 'both')
  41. SUBSCRIPTION_FROM = ('from', 'both')
  42.  
  43. class JabberBuddy(common.buddy):
  44.     resource_class = jabber.resource
  45.     
  46.     def __init__(self, jabber_, jid, rosteritem = None):
  47.         uname = JID(jid).bare().as_unicode()
  48.         self.jid = JID(jid).bare()
  49.         self.username = uname
  50.         self.resources = { }
  51.         self.subscription = None if rosteritem else None
  52.         self.rostername = None if rosteritem else None
  53.         if rosteritem:
  54.             self.notify('rostername')
  55.             self.notify('remote_alias')
  56.         
  57.         self.ask = None if rosteritem else None
  58.         self.groups = None if rosteritem else []
  59.         self.profile = False
  60.         common.buddy.__init__(self, uname, jabber_)
  61.         self._gen_pretty_profile()
  62.         self.pending_adds = set()
  63.  
  64.     
  65.     def __call__(self, item):
  66.         self.subscription = item.subscription
  67.         self.ask = item.ask
  68.         self.rostername = item.name
  69.         self.groups = item.groups
  70.         self.check_subscription()
  71.         self.notify('rostername')
  72.         self.notify('remote_alias')
  73.         return self
  74.  
  75.     
  76.     def check_subscription(self):
  77.         if self.subscription not in SUBSCRIPTION_TO and self.resources and self is not getattr(self.protocol, 'self_buddy', sentinel):
  78.             self.resources.clear()
  79.             self.notify()
  80.         
  81.  
  82.     
  83.     def service(self):
  84.         if self.jid.domain in GTALK_DOMAINS:
  85.             return GTALK
  86.         return JABBER
  87.  
  88.     service = property(service)
  89.     
  90.     def serviceicon(self):
  91.         service = self.service
  92.         if service is GTALK and self.protocol.service == 'gtalk' or any((lambda .0: for j in .0:
  93. isGTalk(j.resource))(self.resources)):
  94.             service = GTALK
  95.         
  96.         return skin.get('serviceicons.' + service)
  97.  
  98.     serviceicon = property(serviceicon)
  99.     
  100.     def id(self):
  101.         return self.jid
  102.  
  103.     id = property(id)
  104.     
  105.     def equals_chat_buddy(self, chat_buddy):
  106.         if hasattr(chat_buddy, 'user'):
  107.             user = chat_buddy.user
  108.             if user.real_jid is not None:
  109.                 return user.real_jid.bare() == self.jid.bare()
  110.         
  111.         return common.buddy.equals_chat_buddy(self, chat_buddy)
  112.  
  113.     
  114.     def away(self):
  115.         if self.away_is_idle:
  116.             if self.resources and not (self.idle):
  117.                 pass
  118.             return not any((lambda .0: for r in .0:
  119. r.available)(self.resources.itervalues()))
  120.         if self.resources:
  121.             pass
  122.         return all((lambda .0: for r in .0:
  123. r.away)(self.resources.itervalues()))
  124.  
  125.     away = property(away)
  126.     
  127.     def mobile(self):
  128.         if self.jid.domain in GTALK_MOBILE_DOMAINS and self.resources:
  129.             pass
  130.         return all((lambda .0: for r in .0:
  131. r.mobile)(self.resources.itervalues()))
  132.  
  133.     mobile = property(mobile)
  134.     
  135.     def blocked(self):
  136.         return False
  137.  
  138.     blocked = property(blocked)
  139.     
  140.     def online(self):
  141.         if bool(self.resources):
  142.             pass
  143.         return self.protocol.is_connected
  144.  
  145.     online = property(online)
  146.     
  147.     def away_is_idle(self):
  148.         return self.service == GTALK
  149.  
  150.     away_is_idle = property(away_is_idle)
  151.     
  152.     def idle(self):
  153.         if self.away_is_idle:
  154.             if self.resources:
  155.                 pass
  156.             return all((lambda .0: for r in .0:
  157. r.idle)(self.resources.itervalues()))
  158.         return False
  159.  
  160.     idle = property(idle)
  161.     
  162.     def get_caps(self):
  163.         caps = common.buddy.get_caps(self)
  164.         for r in self.resources.values():
  165.             res = r.jid.resource
  166.             if res and not isGTalk(res):
  167.                 break
  168.                 continue
  169.         
  170.         return caps
  171.  
  172.     caps = property(get_caps)
  173.     
  174.     def _gen_pretty_profile(self):
  175.         profile = odict()
  176.         ok = False
  177.         fullname = self.vcard_get('fn')
  178.         if fullname:
  179.             profile['Full Name:'] = fullname
  180.             ok = True
  181.         
  182.         mapping = {
  183.             'birthday': ('bday',),
  184.             'email_address': ('email', 'address'),
  185.             'phone': ('tel', 'number'),
  186.             'company': ('org', 'name'),
  187.             'department': ('org', 'unit'),
  188.             'postition': ('title',),
  189.             'role': ('role',) }
  190.         for key in ('birthday', 'email_address', 'phone'):
  191.             val = self.vcard_get(*mapping[key])
  192.             if val is not None:
  193.                 profile[key.replace('_', ' ').title() + ':'] = val
  194.                 ok = True
  195.                 continue
  196.         
  197.         homepage = self.vcard_get('url')
  198.         if homepage:
  199.             profile['Website'] = (homepage, homepage)
  200.             ok = True
  201.         
  202.         about = self.vcard_get('desc')
  203.         if about:
  204.             if ok:
  205.                 profile['sep1'] = 4
  206.             
  207.             profile['Additional Information:'] = ''.join([
  208.                 '\n',
  209.                 about])
  210.         
  211.         
  212.         def prettyaddy(addict):
  213.             addy = []
  214.             
  215.             add = lambda s: addy.insert(0, s)
  216.             mstr = '%(street)s %(extadr)s %(locality)s %(region)s %(pcode)s %(ctry)s' % addict
  217.             if isinstance(mstr, unicode):
  218.                 mstr = mstr.encode('utf-8')
  219.             
  220.             murl = 'http://maps.google.com/maps?q=' + quote(mstr)
  221.             if addict.ctry:
  222.                 add('\n' + addict.ctry)
  223.             
  224.             if addict.pcode:
  225.                 add(addict.pcode)
  226.             
  227.             if addict.region:
  228.                 if addict.pcode:
  229.                     add(' ')
  230.                 
  231.                 add(addict.region)
  232.             
  233.             if addict.locality:
  234.                 if addict.region or addict.pcode:
  235.                     add(', ')
  236.                 
  237.                 add(addict.locality)
  238.             
  239.             if addict.extadr:
  240.                 if any((addict.locality, addict.region, addict.pcode)):
  241.                     add('\n')
  242.                 
  243.                 add(addict.extadr)
  244.             
  245.             if addict.street:
  246.                 if any((addict.locality, addict.region, addict.pcode, addict.extadr)):
  247.                     add('\n')
  248.                 
  249.                 add(addict.street)
  250.             
  251.             if addy:
  252.                 add([
  253.                     '(',
  254.                     (murl, 'map'),
  255.                     ')\n'])
  256.             
  257.             return addy
  258.  
  259.         address = self.vcard_get('adr')
  260.         if ok:
  261.             profile['sep3'] = 4
  262.         
  263.         for key in WORK_KEYS:
  264.             val = self.vcard_get(*mapping[key])
  265.             profile[key.title() + ':'] = val
  266.         
  267.         self.last_pretty_profile = profile
  268.         return profile
  269.  
  270.     
  271.     def pretty_profile(self):
  272.         profile = getattr(self, ('last_pretty_profile',), (lambda : self._gen_pretty_profile()))
  273.         for key in profile.keys():
  274.             if not key.startswith('sep') and profile[key]:
  275.                 break
  276.                 continue
  277.         else:
  278.             return None
  279.  
  280.     pretty_profile = property(pretty_profile)
  281.     
  282.     def get_status_message(self):
  283.         
  284.         try:
  285.             res = self.get_highest_priority_resource()
  286.             if res:
  287.                 if not res.status_message:
  288.                     pass
  289.                 return ''
  290.             return ''
  291.         except Exception:
  292.             e = None
  293.             log.warning('status_message(self) on %r: %r', self, e)
  294.             raise 
  295.  
  296.  
  297.     
  298.     def set_status_message(self, value):
  299.         r = self.get_highest_priority_resource()
  300.         if r:
  301.             old = r.status_message
  302.             r.status_message = value
  303.             self.notify('status_message', old, value)
  304.         
  305.  
  306.     status_message = property(get_status_message, set_status_message)
  307.     
  308.     def status(self):
  309.         if self.mobile:
  310.             return 'mobile'
  311.         if self.subscription not in SUBSCRIPTION_TO and self is not getattr(self.protocol, 'self_buddy', sentinel):
  312.             return 'unknown'
  313.         if not getattr(self, 'resources', []):
  314.             return 'offline'
  315.         if self.idle:
  316.             return 'idle'
  317.         if not self.away:
  318.             return 'available'
  319.         return 'away'
  320.  
  321.     status = property(status)
  322.     
  323.     def update_presence(self, presence, notify = True, buddy = None):
  324.         if not presence.get_from():
  325.             pass
  326.         buddy = buddy
  327.         presence_type = presence.get_type()
  328.         if not presence_type or presence_type == 'available':
  329.             old_length = len(self.resources)
  330.             self.resources[buddy] = self.resource_class(self.protocol, buddy, presence)
  331.             children = presence.xmlnode.get_children()
  332.             nicks = jabber.jabber_util.xpath_eval(presence.xmlnode, 'n:nick', {
  333.                 'n': NICK_NS })
  334.             if nicks:
  335.                 self.nick = Nick(nicks[0]).nick
  336.                 self.notify('nick')
  337.                 self.notify('remote_alias')
  338.             
  339.             self._presence_updated(presence)
  340.         elif presence_type == 'unavailable':
  341.             if buddy in self.resources:
  342.                 del self.resources[buddy]
  343.             
  344.         
  345.         if notify:
  346.             self.notify('status')
  347.         
  348.  
  349.     
  350.     def _presence_updated(self, presence):
  351.         if self.jid.domain not in pref('digsby.guest.domains', [
  352.             'guest.digsby.org']):
  353.             self.protocol.get_buddy_icon(self.username)
  354.         
  355.  
  356.     
  357.     def get_highest_priority_resource(self):
  358.         if getattr(self, 'resources', []):
  359.             return self[0]
  360.  
  361.     
  362.     def set_vcard(self, stanza):
  363.         log.info('incoming vcard for %s', self)
  364.         self._vcard_incoming = False
  365.         q = stanza.get_query()
  366.         if not q:
  367.             return None
  368.         
  369.         try:
  370.             pass
  371.         except ValueError:
  372.             q
  373.             q
  374.         except:
  375.             q
  376.  
  377.         self._incoming_icon(vc.photo)
  378.         self._gen_pretty_profile()
  379.         self.notify('vcard')
  380.         self.notify('remote_alias')
  381.  
  382.     
  383.     def set_vc(self, vcard):
  384.         self._vcard = vcard
  385.  
  386.     
  387.     def get_vc(self):
  388.         return self._vcard
  389.  
  390.     vcard = property(get_vc, set_vc)
  391.     _vcard = cproperty(None, (lambda o: if o is not None:
  392. o.rfc2426()), (lambda o: if o is not None:
  393. VCard(o)))
  394.     
  395.     def vcard_get(self, *stuffs):
  396.         if self.vcard:
  397.             stuff = stuffs[0]
  398.             stuffs = stuffs[1:]
  399.             thing = getattr(self.vcard, stuff, None)
  400.             if isinstance(thing, list) and thing:
  401.                 thing = thing[0]
  402.                 while stuffs:
  403.                     thing = getattr(thing, stuffs[0])
  404.                     stuffs = stuffs[1:]
  405.             elif thing:
  406.                 if stuffs:
  407.                     log.warning_s('%r', stuffs)
  408.                     log.warning_s(self.vcard.as_xml())
  409.                 
  410.             
  411.             if thing:
  412.                 return unicode(thing)
  413.             return thing
  414.  
  415.     nick = cproperty(None)
  416.     
  417.     def _incoming_icon(self, photos):
  418.         if photos and photos[0].image:
  419.             img = photos[0].image
  420.             self._update_photo_image(img)
  421.         elif photos and photos[0].uri:
  422.             
  423.             def success(result):
  424.                 (_response, content) = result
  425.                 self._update_photo_image(content)
  426.  
  427.             meth = threaded(urlcacheopen)
  428.             meth.verbose = False
  429.             meth(photos[0].uri, success = success)
  430.         
  431.  
  432.     
  433.     def _update_photo_image(self, data):
  434.         hash = hashlib.sha1(data).hexdigest()
  435.         self.cache_icon(data, hash)
  436.         self.icon_hash = hash
  437.  
  438.     
  439.     def get_remote_alias(self):
  440.         for attr in ('rostername', 'nick'):
  441.             nick = getattr(self, attr, None)
  442.             if nick:
  443.                 return unicode(nick)
  444.         
  445.         for attr in ('nickname', 'fn'):
  446.             nick = self.vcard_get(attr)
  447.             if nick:
  448.                 return unicode(nick)
  449.         
  450.  
  451.     remote_alias = oproperty(get_remote_alias, observe = [
  452.         'vcard',
  453.         'rostername',
  454.         'nick'])
  455.     
  456.     def add_to_group(self, groupname, callback = None):
  457.         log.info('%s add_to_group %s', self, groupname)
  458.         pending = self.pending_adds
  459.         if groupname in pending:
  460.             log.info('ignoring request.')
  461.         else:
  462.             pending.add(groupname)
  463.         item = self.protocol.roster.get_item_by_jid(self.id).clone()
  464.         if groupname not in item.groups:
  465.             item.groups.append(groupname)
  466.             query = item.make_roster_push()
  467.             
  468.             def onsuccess(_s):
  469.                 pending.discard(groupname)
  470.                 callback.success()
  471.  
  472.             
  473.             def onerror(_s = (None, (None, None, None), None)):
  474.                 pending.discard(groupname)
  475.                 log.warning('error adding %r to %s', self.id, groupname)
  476.  
  477.             self.protocol.send_cb(query, success = onsuccess, error = onerror, timeout = onerror)
  478.         
  479.  
  480.     add_to_group = action(needs = ((unicode, 'Group name'),))(callsback(add_to_group))
  481.     
  482.     def remove(self, callback = None):
  483.         
  484.         try:
  485.             item = self.protocol.roster.get_item_by_jid(self.id).clone()
  486.         except KeyError:
  487.             return None
  488.  
  489.         item.subscription = 'remove'
  490.         self.protocol.send_cb(item.make_roster_push(), callback = callback)
  491.  
  492.     remove = action()(callsback(remove))
  493.     
  494.     def subscribed(self):
  495.         self.protocol.send_presence(Presence(to_jid = self.id, stanza_type = 'subscribed'))
  496.  
  497.     subscribed = action((lambda self: if no_widget(self) is None:
  498. Noneif self.subscription in SUBSCRIPTION_FROM:
  499. NoneTrue))(subscribed)
  500.     
  501.     def unsubscribed(self):
  502.         self.protocol.send_presence(Presence(to_jid = self.id, stanza_type = 'unsubscribed'))
  503.  
  504.     unsubscribed = action((lambda self: if no_widget(self) is None:
  505. Noneif self.subscription not in SUBSCRIPTION_FROM:
  506. NoneTrue))(unsubscribed)
  507.     
  508.     def subscribe(self):
  509.         self.protocol.send_presence(Presence(to_jid = self.id, stanza_type = 'subscribe'))
  510.  
  511.     subscribe = action((lambda self: if no_widget(self) is None:
  512. Noneif self.subscription in SUBSCRIPTION_TO:
  513. NoneTrue))(subscribe)
  514.     
  515.     def unsubscribe(self):
  516.         self.protocol.send_presence(Presence(to_jid = self.id, stanza_type = 'unsubscribe'))
  517.  
  518.     unsubscribe = action((lambda self: if no_widget(self) is None:
  519. Noneif self.subscription not in SUBSCRIPTION_TO:
  520. NoneTrue))(unsubscribe)
  521.     
  522.     def appear_offline_to(self):
  523.         self.protocol.send_presence(Presence(stanza_type = 'unavailable', status = 'Logged Out', to_jid = self.id))
  524.  
  525.     
  526.     def expand(self):
  527.         print 'expand %r' % self
  528.  
  529.     expand = action()(expand)
  530.     
  531.     def sorted_resources(self):
  532.         return sorted(self.resources.itervalues(), key = (lambda r: (r.priority, r.jid)), reverse = True)
  533.  
  534.     
  535.     def __iter__(self):
  536.         return iter(self.sorted_resources())
  537.  
  538.     
  539.     def __len__(self):
  540.         return len(self.resources)
  541.  
  542.     
  543.     def __getitem__(self, index):
  544.         return self.sorted_resources()[index]
  545.  
  546.     
  547.     def __repr__(self):
  548.         
  549.         try:
  550.             res = len(self.resources)
  551.         except Exception:
  552.             res = 0
  553.  
  554.         
  555.         try:
  556.             n = self.name
  557.         except Exception:
  558.             n = ''
  559.  
  560.         return '<%s %r %d>' % (type(self).__name__, n, res)
  561.  
  562.  
  563.  
  564. def dupe_presence(p):
  565.     return Presence(p.get_node())
  566.  
  567.