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