def track_pageview(self, path, **kwargs): """ @variable str page @variable dict kwargs (optional) {'title', 'charset', 'referrer', 'load_time'} Sends page hit to GA with given path as the page """ page = Page(path) page.title = kwargs.get('title', None) page.charset = kwargs.get('charset', None) page.referrer = kwargs.get('referrer', None) page.load_time = kwargs.get('load_time', None) self.ga_tracker.track_pageview(page=page,session=self.ga_session,visitor=self.ga_visitor)
def ping(): """ping back to ga""" if not ga_account: return tracker = Tracker(ga_account, ga_domain) visitor = Visitor() visitor.ip_address = request.remote_addr session = Session() page = Page(request.path) if "referer" in request.headers: page.referrer = request.headers["referer"] tracker.track_pageview(page, session, visitor)
def ping(): """ping back to ga""" if not ga_account: return tracker = Tracker(ga_account, ga_domain) visitor = Visitor() visitor.ip_address = request.remote_addr session = Session() page = Page(request.path) if 'referer' in request.headers: page.referrer = request.headers['referer'] tracker.track_pageview(page, session, visitor)
def promo(params): # показ промо контента track_page_view('promo') track_page_view('promo',UATRACK=GATrack) tracker.track_pageview(Page('/promo'), session, visitor) http = GET('http://www.ivi.ru/mobileapi/promo/') if http == None: return False jsdata = json.loads(http) if jsdata: for video in jsdata: http=GET('http://www.ivi.ru/mobileapi/videoinfo/?id=%s'%video['content_id']) vdata = get_video_data(json.loads(http)) li = xbmcgui.ListItem(vdata['title'], iconImage = vdata['image'], thumbnailImage = vdata['image']) li.setProperty('fanart_image', addon_fanart) try: li.setInfo(type='video', infoLabels = vdata['info']) except: pass uri = '%s?%s' % (sys.argv[0], urllib.urlencode({'func':'playid', 'id': video['content_id']})) u=sys.argv[0]+"?func=playid&id="+str(video['content_id']) li.setProperty('IsPlayable', 'true') li.setProperty('fanart_image', addon_fanart) li.setInfo('video',{'plot': video['text']}) xbmcplugin.addDirectoryItem(hos, url=u, listitem= li) xbmcplugin.endOfDirectory(hos)
def track_event(category=None, action=None, label=None, value=None, identifier=None, first_use=None, add=None, noninteraction=True): anonymousConfig = Config() anonymousConfig.anonimize_ip_address = True tracker = Tracker('UA-86466078-1', 'none', conf=anonymousConfig) visitor = Visitor() # convert the last 8 bytes of the machine identifier to an integer to get a "unique" user visitor.unique_id = struct.unpack("!I", binascii.unhexlify(identifier[32:]))[0]/2 if add: # add visitor's ip address (will be anonymized) visitor.ip_address = add if first_use: visitor.first_visit_time = first_use session = Session() event = Event(category=category, action=action, label=label, value=value, noninteraction=noninteraction) path = u"/" + u"/".join([category, action, label]) page = Page(path.lower()) tracker.track_event(event, session, visitor) tracker.track_pageview(page, session, visitor)
def alloc_ga_obj_by_name(name): """ 通过名字生成对应的obj """ from pyga.requests import Tracker, Page, Session, Visitor, Transaction, Event, SocialInteraction, Campaign obj = None if name == 'tracker': obj = Tracker() elif name == 'campaign': obj = Campaign(Campaign.TYPE_REFERRAL) elif name == 'session': obj = Session() elif name == 'page': obj = Page(None) elif name == 'visitor': obj = Visitor() elif name == 'transaction': obj = Transaction() elif name == 'event': obj = Event() elif name == 'social_interaction': obj = SocialInteraction() return obj
def test_request(self): from pyga.requests import Tracker, Visitor, Session, Page from mock import Mock import urllib2 mocked = urllib2.urlopen = Mock() meta = dict( REMOTE_ADDR='134.321.0.1', HTTP_USER_AGENT='Test User Agent 1.0', HTTP_ACCEPT_LANGUAGE='en-US,en;q=0.8,ru;q=0.6', ) tracker = Tracker('UA-0000-0000', 'test.com') visitor = Visitor() visitor.extract_from_server_meta(meta) self.assertEqual(visitor.ip_address, '134.321.0.1') self.assertEqual(visitor.locale, 'en_US') self.assertEqual(visitor.user_agent, 'Test User Agent 1.0') session = Session() page = Page('/test_path') tracker.track_pageview(page, session, visitor) (request, ), _ = mocked.call_args_list.pop() self.assertEqual(request.headers.get('X-forwarded-for'), '134.321.0.1') self.assertEqual(request.headers.get('User-agent'), 'Test User Agent 1.0')
def test_request(self): from pyga.requests import Tracker, Visitor, Session, Page from mock import Mock mocked = six.moves.urllib.request.urlopen = Mock() meta = dict( REMOTE_ADDR='134.321.0.1', HTTP_USER_AGENT='Test User Agent 1.0', HTTP_ACCEPT_LANGUAGE='en-US,en;q=0.8,ru;q=0.6', ) tracker = Tracker('UA-0000-0000', 'test.com') visitor = Visitor() visitor.extract_from_server_meta(meta) self.assertEqual(visitor.ip_address, '134.321.0.1') self.assertEqual(visitor.locale, 'en_US') self.assertEqual(visitor.user_agent, 'Test User Agent 1.0') session = Session() page = Page('/test_path') tracker.track_pageview(page, session, visitor) (request, ), _ = mocked.call_args_list.pop() self.assertEqual(request.headers.get('X-forwarded-for'), '134.321.0.1') self.assertEqual(request.headers.get('User-agent'), 'Test User Agent 1.0') # Assert that &ua and &uip are passed along, and that &uip is properly # anonymized. qs = six.moves.urllib.parse.urlparse(request.get_full_url()).query params = six.moves.urllib.parse.parse_qs(qs) self.assertEqual(params['uip'][0], '134.321.0.0') self.assertEqual(params['ua'][0], 'Test User Agent 1.0')
def test_request(self, mocked): from pyga.requests import Tracker, Visitor, Session, Page meta = dict( REMOTE_ADDR="134.321.0.1", HTTP_USER_AGENT="Test User Agent 1.0", HTTP_ACCEPT_LANGUAGE="en-US,en;q=0.8,ru;q=0.6", ) tracker = Tracker("UA-0000-0000", "test.com") visitor = Visitor() visitor.extract_from_server_meta(meta) self.assertEqual(visitor.ip_address, "134.321.0.1") self.assertEqual(visitor.locale, "en_US") self.assertEqual(visitor.user_agent, "Test User Agent 1.0") session = Session() page = Page("/test_path") tracker.track_pageview(page, session, visitor) (request, ), _ = mocked.call_args_list.pop() self.assertEqual(request.headers.get("X-forwarded-for"), "134.321.0.1") self.assertEqual(request.headers.get("User-agent"), "Test User Agent 1.0") # Assert that &ua and &uip are passed along, and that &uip is properly # anonymized. qs = urlparse(request.get_full_url()).query params = parse_qs(qs) self.assertEqual(params["uip"][0], "134.321.0.0") self.assertEqual(params["ua"][0], "Test User Agent 1.0")
def middleware(request): if ga_id is not False: tracker = Tracker(ga_id, request.headers['Host']) visitor = Visitor() visitor.ip_address = request.META.get('REMOTE_ADDR') if request.headers['User-Agent']: visitor.user_agent = request.headers['User-Agent'] session = Session() path = request.path if request.META.get('QUERY_STRING'): path = f"{request.path}?{request.META.get('QUERY_STRING')}" page = Page(path) page.title = request.path tracker.track_pageview(page, session, visitor) response = get_response(request) return response
def track_pageview(self, page): try: if self.account_id: self.tracker.track_pageview(Page(page), self.session, self.visitor) except: print('Uncaught exception in Analytics process: \n' + unicode(traceback.format_exc(), 'utf8'))
def log_traffic(request): if not google_analytics: return url = urlparse(request.base_url) pyga_tracker = Tracker(google_analytics, url.hostname) pyga_visitor = Visitor() pyga_visitor.ip_address = request.access_route[0] pyga_visitor.user_agent = request.headers.get('User-Agent') user_locals = [] if 'Accept-Language' in request.headers: al = request.headers.get('Accept-Language') if al is not None: matched_locales = utils.validate_locale(al) if matched_locales: lang_lst = map((lambda x: x.replace('-', '_')), (i[1] for i in matched_locales)) quality_lst = map( (lambda x: x and x or 1), (float(i[4] and i[4] or '0') for i in matched_locales)) lang_quality_map = map((lambda x, y: (x, y)), lang_lst, quality_lst) user_locals = [ x[0] for x in sorted( lang_quality_map, key=itemgetter(1), reverse=True) ] if user_locals: pyga_visitor.locale = user_locals[0] pyga_session = Session() pyga_page = Page(url.path) pyga_page.referrer = request.headers.get('Referer') logger.info('Logging GA traffic from %s to host %s with page %s', pyga_visitor.ip_address, url.hostname, url.path) try: pyga_tracker.track_pageview(pyga_page, pyga_session, pyga_visitor) except URLError: logger.warn('Unable to connect to analytics') except: logger.error('Analytics logging failed') logger.error(sys.exc_info())
def get(self, request, path=None, **resources): """ Proxy request to GA. """ tracker = Tracker(self._meta.account_id, self._meta.domain or request.META.get('SERVER_NAME')) visitor = Visitor() visitor.extract_from_server_meta(request.META) session = Session() page = Page(path) tracker.track_pageview(page, session, visitor)
def track_page(path, force=False): if not plugin.get_setting("ga_disable", bool) or force: try: from pyga.requests import Page tracker, session, visitor = get_ga() plugin.log.info("GA: Tracking %s" % path) tracker.track_pageview(Page(path), session, visitor) except Exception, e: import traceback plugin.log.error("GA: Call failed.") plugin.log.error(traceback.format_exc())
def deliver(cls, entry): now = datetime.utcnow() # make the call to google analytics tracker = Tracker(entry['gacode'], entry['domain']) visitor = Visitor(entry) # possible other data: #visitor.flash_version = None #visitor.java_enabled = None #visitor.screen_colour_depth = None #visitor.screen_resolution = None session = Session() page = Page(entry['path']) page.referer = entry['referer'] page.title = entry['title'] #page.charset = entry['charset'] #page.load_time = entry['load_time'] tracker.track_pageview(page, session, visitor)
def process_request(self, request): if settings.GA_ENABLED: ip = request.META["REMOTE_ADDR"] if request.META.has_key("CF-Connecting-IP"): ip = request.META["CF-Connecting-IP"] tracker = Tracker(settings.GA_KEY, request.META["HTTP_HOST"]) visitor = Visitor() visitor.ip_address = ip session = Session() page = Page(request.path) tracker.track_pageview(page, session, visitor) return None
def ga_track(self, event={}): _req_list = [] no_tracking = self.get_argument('no_tracking', None) is_prod = getattr(config, 'RUN_IN_PROD', False) if not no_tracking and is_prod and hasattr(config, "GA_ACCOUNT"): _req = self.request remote_ip = _req.headers.get("X-Real-Ip", _req.headers.get("X-Forwarded-For", _req.remote_ip)) user_agent = _req.headers.get("User-Agent", None) visitor = Visitor() visitor.ip_address = remote_ip visitor.user_agent = user_agent #get visitor.locale visitor.extract_from_server_meta( {"HTTP_ACCEPT_LANGUAGE": _req.headers.get("Accept-Language", None)} ) session = Session() page = Page(_req.path) tracker = Tracker(config.GA_ACCOUNT, 'MyVariant.info') # tracker.track_pageview(page, session, visitor) #this is non-async request pvr = PageViewRequest(config=tracker.config, tracker=tracker, visitor=visitor, session=session, page=page) r = pvr.build_http_request() _req_list.append(HTTPRequest(r.get_full_url(), "POST" if (r.data) else "GET", headers=r.headers, body=r.data)) if event: evt = Event(**event) #tracker.track_event(evt, session, visitor) #this is non-async request er = EventRequest(config=tracker.config, tracker=tracker, visitor=visitor, session=session, event=evt) r = er.build_http_request() _req_list.append(HTTPRequest(r.get_full_url(), "POST" if (r.data) else "GET", headers=r.headers, body=r.data)) #now send actual async requests http_client = AsyncHTTPClient() for _req in _req_list: http_client.fetch(_req)
def run_search(params): # Поиск track_page_view('search') track_page_view('search',UATRACK=GATrack) tracker.track_pageview(Page('/search'), session, visitor) kbd = xbmc.Keyboard() kbd.setDefault('') kbd.setHeading(language(30021)) kbd.doModal() out='' if kbd.isConfirmed(): try: out = trans.detranslify(kbd.getText()) out=out.encode("utf-8") except: out = kbd.getText() params['from'] = 0 params['to']= int(show_len) params['query'] = out params['url'] = 'http://www.ivi.ru/mobileapi/search/v2/?subsite=15&%s' read_dir(params)
def track_event(category=None, action=None, label=None): if not settings.analytics.getboolean('enabled'): return anonymousConfig = Config() anonymousConfig.anonimize_ip_address = True tracker = Tracker('UA-138214134-3', 'none', conf=anonymousConfig) try: visitor = pickle.loads(base64.b64decode(settings.analytics.visitor)) except: visitor = Visitor() unique_id = long(random.getrandbits(32)) visitor.unique_id = unique_id session = Session() event = Event(category=category, action=action, label=label, value=1) path = u"/" + u"/".join([category, action, label]) page = Page(path.lower()) tracker.add_custom_variable(CustomVariable(index=1, name='BazarrVersion', value=os.environ["BAZARR_VERSION"], scope=1)) tracker.add_custom_variable(CustomVariable(index=2, name='PythonVersion', value=platform.python_version(), scope=1)) if settings.general.getboolean('use_sonarr'): tracker.add_custom_variable(CustomVariable(index=3, name='SonarrVersion', value=sonarr_version, scope=1)) if settings.general.getboolean('use_radarr'): tracker.add_custom_variable(CustomVariable(index=4, name='RadarrVersion', value=radarr_version, scope=1)) tracker.add_custom_variable(CustomVariable(index=5, name='OSVersion', value=platform.platform(), scope=1)) try: tracker.track_event(event, session, visitor) tracker.track_pageview(page, session, visitor) except: pass else: settings.analytics.visitor = base64.b64encode(pickle.dumps(visitor)) with open(os.path.join(args.config_dir, 'config', 'config.ini'), 'w+') as handle: settings.write(handle)
def read_category(params): show_len=get_len() categ=params['category'] if categ=='14': track_page_view('movies') track_page_view('movies',UATRACK=GATrack) tracker.track_pageview(Page('/movies'), session, visitor) if categ=='15': track_page_view('series') track_page_view('series',UATRACK=GATrack) tracker.track_pageview(Page('/series'), session, visitor) if categ=='16': track_page_view('shows') track_page_view('shows',UATRACK=GATrack) tracker.track_pageview(Page('/shows'), session, visitor) if categ=='17': track_page_view('animation') track_page_view('animation',UATRACK=GATrack) tracker.track_pageview(Page('/animation'), session, visitor) if categ=='20': track_page_view('child') track_page_view('child',UATRACK=GATrack) tracker.track_pageview(Page('/child'), session, visitor) http = GET('http://www.ivi.ru/mobileapi/categories/') jsdata = json.loads(http) for categoryes in jsdata: if categoryes['id']==int(params['category']): li = xbmcgui.ListItem(language(30016), iconImage = addon_icon, thumbnailImage = addon_icon) li.setProperty('fanart_image', addon_fanart) uri = construct_request({ 'func': 'run_search', 'category': categoryes['id'] }) xbmcplugin.addDirectoryItem(hos, uri, li, True) li = xbmcgui.ListItem(language(30017), iconImage = addon_icon, thumbnailImage = addon_icon) li.setProperty('fanart_image', addon_fanart) uri = construct_request({ 'func': 'read_dir', 'category': categoryes['id'], 'sort':'new', 'from':0, 'to':show_len-1 }) xbmcplugin.addDirectoryItem(hos, uri, li, True) li = xbmcgui.ListItem(language(30018), iconImage = addon_icon, thumbnailImage = addon_icon) li.setProperty('fanart_image', addon_fanart) uri = construct_request({ 'func': 'read_dir', 'category': categoryes['id'], 'sort':'pop', 'from':0, 'to':show_len-1 }) xbmcplugin.addDirectoryItem(hos, uri, li, True) for genre in categoryes['genres']: li = xbmcgui.ListItem(genre['title'], iconImage = addon_icon, thumbnailImage = addon_icon) li.setProperty('fanart_image', addon_fanart) uri = construct_request({ 'func': 'read_dir', 'genre': genre['id'], 'sorted':1, 'from':0, 'to':show_len-1 }) if genre['id']<>169 or adult: xbmcplugin.addDirectoryItem(hos, uri, li, True) xbmcplugin.endOfDirectory(hos)