home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2012 January / maximum-cd-2012-01.iso / DiscContents / digsby_setup.exe / lib / plugins / feed_trends / geo_trends.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-10-05  |  10.7 KB  |  274 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. import hooks
  5. import random
  6. from util.net import UrlQuery
  7. from util import Storage as S
  8. import common.asynchttp as asynchttp
  9. import common
  10. import lxml.etree as ET
  11. from logging import getLogger
  12. log = getLogger('geo_trends')
  13. active_geoip = None
  14. did_receive_geoip = False
  15.  
  16. def on_geoip(geoip, *a, **k):
  17.     global did_receive_geoip, active_geoip
  18.     did_receive_geoip = True
  19.     active_geoip = geoip
  20.  
  21.  
  22. class PlacementMethodReprMeta(type):
  23.     
  24.     def __repr__(cls):
  25.         return '<PlacementMethod %r>' % cls.__name__
  26.  
  27.  
  28.  
  29. class PlacementMethod(object):
  30.     __metaclass__ = PlacementMethodReprMeta
  31.     
  32.     def supports_location(cls, location):
  33.         return (all,)((lambda .0: for a in .0:
  34. location.get(a, None))(cls.location_attrs))
  35.  
  36.     supports_location = classmethod(supports_location)
  37.  
  38.  
  39. class citystate(PlacementMethod):
  40.     location_attrs = ('city', 'state')
  41.     
  42.     def urlargs(location):
  43.         return dict(where = '%s, %s' % (location['city'], location['state']))
  44.  
  45.     urlargs = staticmethod(urlargs)
  46.  
  47.  
  48. class ipaddress(PlacementMethod):
  49.     location_attrs = ('ip',)
  50.     
  51.     def urlargs(location):
  52.         return dict(client_ip = '%s' % location['ip'])
  53.  
  54.     urlargs = staticmethod(urlargs)
  55.  
  56.  
  57. class zipcode(PlacementMethod):
  58.     location_attrs = ('postal',)
  59.     
  60.     def urlargs(location):
  61.         return dict(where = '%s' % location['postal'])
  62.  
  63.     urlargs = staticmethod(urlargs)
  64.  
  65. location_methods = [
  66.     citystate,
  67.     ipaddress,
  68.     zipcode]
  69.  
  70. def _get_possible_methods(location):
  71.     if not location:
  72.         return []
  73.     return _[1]
  74.  
  75. from feed_trends import NewsItem
  76.  
  77. class CityGridNewsItem(NewsItem):
  78.     __slots__ = ()
  79.     
  80.     def notify_click(self):
  81.         ppe = self.content['net_ppe']
  82.         if ppe is not None:
  83.             cents = int(ppe * 100)
  84.             hooks.notify('digsby.statistics.feed_ads.citygrid.click_cents', cents)
  85.         
  86.         hooks.notify('digsby.statistics.feed_ads.citygrid.click')
  87.  
  88.     
  89.     def _notify_impression_hook(self):
  90.         hooks.notify('digsby.statistics.feed_ads.citygrid.impression')
  91.  
  92.  
  93. ad_keywords = '\n    food\n    lunch\n    restaurant\n    cuisine\n    bar\n    pub\n    clothing\n    shopping\n    beauty\n    spa\n    automotive\n    jewelry\n    furniture\n    fitness\n    education\n'.strip().split()
  94.  
  95. def _get_ad_url(location, method, keyword):
  96.     url_kwargs = dict(placement = method.__name__, what = keyword)
  97.     publisher = common.pref('social.feed_ads_publisher', 'digsby')
  98.     if publisher and publisher.lower() != 'none':
  99.         url_kwargs['publisher'] = publisher
  100.     
  101.     url_kwargs.update(method.urlargs(location))
  102.     url_kwargs = dict((lambda .0: for k, v in .0:
  103. (k, to_utf8(v)))(url_kwargs.iteritems()))
  104.     url = UrlQuery('http://api.citygridmedia.com/ads/custom/v2/where', **url_kwargs)
  105.     return url
  106.  
  107.  
  108. def to_utf8(s):
  109.     if isinstance(s, unicode):
  110.         return s.encode('utf8')
  111.     return s
  112.  
  113. httpopen = asynchttp.httpopen
  114.  
  115. class CityGridAdSource(object):
  116.     
  117.     def __init__(self, campaign):
  118.         self.set_location(active_geoip)
  119.  
  120.     
  121.     def enabled(cls):
  122.         if active_geoip:
  123.             pass
  124.         return active_geoip.get('country', '').upper() == 'US'
  125.  
  126.     enabled = classmethod(enabled)
  127.     
  128.     def set_location(self, location):
  129.         self.location = location
  130.  
  131.     
  132.     def request_ads(self, success, error = None):
  133.         NewsItemList = NewsItemList
  134.         import feed_trends
  135.         if error is None:
  136.             
  137.             def error(*a):
  138.                 print 'ERROR:',
  139.                 if not a:
  140.                     pass
  141.                 print 
  142.                 print 
  143.  
  144.         
  145.         location = self.location
  146.         possible_methods = _get_possible_methods(location)
  147.         if not possible_methods:
  148.             return success([])
  149.         placement_method = random.choice(possible_methods)
  150.         NUM_KEYWORDS = 2
  151.         keywords_copy = ad_keywords[:]
  152.         random.shuffle(keywords_copy)
  153.         chosen_keywords = keywords_copy[:NUM_KEYWORDS]
  154.         used_urls = []
  155.         ctx = dict(count = 0)
  156.         all_ads = []
  157.         all_errors = []
  158.         
  159.         def maybe_done():
  160.             ctx['count'] += 1
  161.             if ctx['count'] < NUM_KEYWORDS:
  162.                 return None
  163.             if all_ads:
  164.                 self.endpoints = []
  165.                 ad_objects = []
  166.                 for url, data, ads, kwd in all_ads:
  167.                     ad_objects.extend(ads)
  168.                     datetime = datetime
  169.                     import datetime
  170.                     self.endpoints.append(S(last_received_xml = prettyxml(data), last_keyword = kwd, last_url = url, last_update_time = datetime.now().isoformat()))
  171.                 
  172.                 return success(NewsItemList(1, 0, 0, items = ad_objects))
  173.             all_ads(error if all_errors else None)
  174.  
  175.         
  176.         def _url_success(url, data, ads, keyword):
  177.             all_ads.append((url, data, ads, keyword))
  178.             maybe_done()
  179.  
  180.         
  181.         def _url_error(url, e, keyword):
  182.             all_errors.append(e)
  183.             maybe_done(keyword)
  184.  
  185.         for kwd in chosen_keywords:
  186.             url = _get_ad_url(location, placement_method, kwd)
  187.             
  188.             def on_success(req, resp, url = (None, (None, (None, None, None, None, None, None, None, possible_methods))), keyword = (url, kwd)):
  189.                 
  190.                 try:
  191.                     data = resp.read()
  192.                     ads = newsitems_from_citygrid_xml(data)
  193.                 except Exception:
  194.                     e = None
  195.                     _url_error(url, e, keyword)
  196.  
  197.                 _url_success(url, data, ads, keyword)
  198.  
  199.             httpopen(url, success = on_success, error = _url_error)
  200.         
  201.  
  202.  
  203. _default_image_url_path = None
  204.  
  205. def _default_image_url():
  206.     global _default_image_url_path
  207.     path = path
  208.     import path
  209.     if _default_image_url_path is None:
  210.         _default_image_url_path = (path(__file__).parent / 'res' / 'information.png').url()
  211.     
  212.     return _default_image_url_path
  213.  
  214.  
  215. def newsitems_from_citygrid_xml(xmlstring):
  216.     NewsItemList = NewsItemList
  217.     strip_html = strip_html
  218.     import feed_trends
  219.     xml = ET.fromstring(xmlstring)
  220.     items = []
  221.     for findtext in xml:
  222.         ad = None
  223.         if ad.tag != 'ad':
  224.             continue
  225.         
  226.         
  227.         def find(s):
  228.             elem = ad.find(s)
  229.             if elem is not None:
  230.                 return elem.text
  231.             return ''
  232.  
  233.         
  234.         def findurl(s):
  235.             url = find(s)
  236.             if url and not url.startswith('http'):
  237.                 url = 'http://' + url
  238.             
  239.             return url
  240.  
  241.         
  242.         def findfloat(s):
  243.             f = find(s)
  244.             
  245.             try:
  246.                 return float(f)
  247.             except Exception:
  248.                 return None
  249.  
  250.  
  251.         name = findtext('name')
  252.         tagline = findtext('tagline')
  253.         if name:
  254.             pass
  255.         elif not findtext('description'):
  256.             pass
  257.         snippet = ''
  258.         if not name:
  259.             pass
  260.         if not findurl('ad_image_url'):
  261.             pass
  262.         item = CityGridNewsItem(title = tagline, display_url = findurl('ad_display_url'), snippet = snippet, source = '', source_logo_url = _default_image_url(), redirect_url = findurl('ad_destination_url'), tracking_url = '', shortened_url = None, keyword = _('Featured Content'), content = dict(street = findtext('street'), phone = findtext('phone'), reviews = findtext('reviews'), net_ppe = findfloat('net_ppe')), show_snippet = True)
  263.         items.append(item)
  264.     
  265.     return NewsItemList(version = '1', time = 0, max_age = 1080000, items = items)
  266.  
  267.  
  268. def prettyxml(xml):
  269.     if isinstance(xml, basestring):
  270.         xml = ET.fromstring(xml)
  271.     
  272.     return ET.tostring(xml, pretty_print = True)
  273.  
  274.