|
28 | 28 | Thing, Relation, NotFound, MultiRelation, CreationError)
|
29 | 29 | from r2.lib.db.operators import desc
|
30 | 30 | from r2.lib.errors import RedditError
|
| 31 | +from r2.lib.tracking import ( |
| 32 | + get_site, |
| 33 | +) |
31 | 34 | from r2.lib.utils import (
|
32 | 35 | base_url,
|
33 | 36 | domain,
|
@@ -471,6 +474,62 @@ def markdown_link_slow(self):
|
471 | 474 | title = title.replace("]", r"\]")
|
472 | 475 | return "[%s](%s)" % (title, self.make_permalink_slow())
|
473 | 476 |
|
| 477 | + @classmethod |
| 478 | + def tracking_link(cls, |
| 479 | + link, |
| 480 | + wrapped_thing=None, |
| 481 | + element_name=None, |
| 482 | + context=None, |
| 483 | + site_name=None): |
| 484 | + """Add utm query parameters to reddit.com links to track navigation. |
| 485 | +
|
| 486 | + context => ?utm_medium (listing page, post listing on hybrid page) |
| 487 | + site_name => ?utm_name (subreddit that user is currently browsing) |
| 488 | + element_name => ?utm_content (what element leads to this link) |
| 489 | + """ |
| 490 | + |
| 491 | + if (c.user_is_admin or |
| 492 | + not feature.is_enabled('utm_comment_links')): |
| 493 | + return link |
| 494 | + |
| 495 | + urlparser = UrlParser(link) |
| 496 | + if not urlparser.path: |
| 497 | + # `href="#some_anchor"` |
| 498 | + return link |
| 499 | + if urlparser.scheme == 'javascript': |
| 500 | + return link |
| 501 | + if not urlparser.is_reddit_url(): |
| 502 | + return link |
| 503 | + |
| 504 | + query_params = {} |
| 505 | + |
| 506 | + query_params["utm_source"] = "reddit" |
| 507 | + |
| 508 | + if context is None: |
| 509 | + if (hasattr(wrapped_thing, 'context') and |
| 510 | + wrapped_thing.context != cls.get_default_context()): |
| 511 | + context = wrapped_thing.context |
| 512 | + else: |
| 513 | + context = request.route_dict["controller"] |
| 514 | + if context: |
| 515 | + query_params["utm_medium"] = context |
| 516 | + |
| 517 | + if element_name: |
| 518 | + query_params["utm_content"] = element_name |
| 519 | + |
| 520 | + if site_name is None: |
| 521 | + site_name = get_site() |
| 522 | + if site_name: |
| 523 | + query_params["utm_name"] = site_name |
| 524 | + |
| 525 | + query_params = {k: v for (k, v) in query_params.iteritems() if ( |
| 526 | + v is not None)} |
| 527 | + |
| 528 | + if query_params: |
| 529 | + urlparser.update_query(**query_params) |
| 530 | + return urlparser.unparse() |
| 531 | + return link |
| 532 | + |
474 | 533 | def _gild(self, user):
|
475 | 534 | now = datetime.now(g.tz)
|
476 | 535 |
|
@@ -885,6 +944,10 @@ def add_props(cls, user, wrapped):
|
885 | 944 | # Run this last
|
886 | 945 | Printable.add_props(user, wrapped)
|
887 | 946 |
|
| 947 | + @classmethod |
| 948 | + def get_default_context(cls): |
| 949 | + return request.route_dict["action_name"] |
| 950 | + |
888 | 951 | @property
|
889 | 952 | def post_hint(self):
|
890 | 953 | """Returns a string that suggests the content of this link.
|
|
0 commit comments