code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def get_commit_url(self): """Return the commit URL.""" repo_url = self.project.repo if self.is_external: if "github" in repo_url: user, repo = get_github_username_repo(repo_url) if not user and not repo: return "" return GITHUB_PULL_REQUEST_COMMIT_URL.format( user=user, repo=repo, number=self.get_version_name(), commit=self.commit, ) if "gitlab" in repo_url: user, repo = get_gitlab_username_repo(repo_url) if not user and not repo: return "" return GITLAB_MERGE_REQUEST_COMMIT_URL.format( user=user, repo=repo, number=self.get_version_name(), commit=self.commit, ) # TODO: Add External Version Commit URL for Bitbucket. else: if "github" in repo_url: user, repo = get_github_username_repo(repo_url) if not user and not repo: return "" return GITHUB_COMMIT_URL.format(user=user, repo=repo, commit=self.commit) if "gitlab" in repo_url: user, repo = get_gitlab_username_repo(repo_url) if not user and not repo: return "" return GITLAB_COMMIT_URL.format(user=user, repo=repo, commit=self.commit) if "bitbucket" in repo_url: user, repo = get_bitbucket_username_repo(repo_url) if not user and not repo: return "" return BITBUCKET_COMMIT_URL.format(user=user, repo=repo, commit=self.commit) return None
Return the commit URL.
get_commit_url
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def finished(self): """Return if build has an end state.""" return self.state in BUILD_FINAL_STATES
Return if build has an end state.
finished
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def is_stale(self): """Return if build state is triggered & date more than 5m ago.""" mins_ago = timezone.now() - datetime.timedelta(minutes=5) return self.state == BUILD_STATE_TRIGGERED and self.date < mins_ago
Return if build state is triggered & date more than 5m ago.
is_stale
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def can_rebuild(self): """ Check if external build can be rebuilt. Rebuild can be done only if the build is external, build version is active and it's the latest build for the version. see https://github.com/readthedocs/readthedocs.org/pull/6995#issuecomment-852918969 """ if self.is_external: is_latest_build = ( self == Build.objects.filter(project=self.project, version=self.version) .only("id") .first() ) return self.version and self.version.active and is_latest_build return False
Check if external build can be rebuilt. Rebuild can be done only if the build is external, build version is active and it's the latest build for the version. see https://github.com/readthedocs/readthedocs.org/pull/6995#issuecomment-852918969
can_rebuild
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def reset(self): """ Reset the build so it can be re-used when re-trying. Dates and states are usually overridden by the build, we care more about deleting the commands. """ self.state = BUILD_STATE_TRIGGERED self.status = "" self.success = True self.output = "" self.error = "" self.exit_code = None self.builder = "" self.cold_storage = False self.commands.all().delete() self.notifications.all().delete() self.save()
Reset the build so it can be re-used when re-trying. Dates and states are usually overridden by the build, we care more about deleting the commands.
reset
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def successful(self): """Did the command exit with a successful exit code.""" return self.exit_code == 0
Did the command exit with a successful exit code.
successful
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def failed(self): """ Did the command exit with a failing exit code. Helper for inverse of :py:meth:`successful` """ return not self.successful
Did the command exit with a failing exit code. Helper for inverse of :py:meth:`successful`
failed
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def run_time(self): """Total command runtime in seconds.""" if self.start_time is not None and self.end_time is not None: diff = self.end_time - self.start_time return diff.seconds
Total command runtime in seconds.
run_time
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def get_match_arg(self): """Get the match arg defined for `predefined_match_arg` or the match from user.""" match_arg = PREDEFINED_MATCH_ARGS_VALUES.get( self.predefined_match_arg, ) return match_arg or self.match_arg
Get the match arg defined for `predefined_match_arg` or the match from user.
get_match_arg
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def run(self, version, **kwargs): """ Run an action if `version` matches the rule. :type version: readthedocs.builds.models.Version :returns: True if the action was performed """ if version.type != self.version_type: return False match, result = self.match(version, self.get_match_arg()) if match: self.apply_action(version, result) AutomationRuleMatch.objects.register_match( rule=self, version=version, ) return True return False
Run an action if `version` matches the rule. :type version: readthedocs.builds.models.Version :returns: True if the action was performed
run
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def match(self, version, match_arg): """ Returns True and the match result if the version matches the rule. :type version: readthedocs.builds.models.Version :param str match_arg: Additional argument to perform the match :returns: A tuple of (boolean, match_resul). The result will be passed to `apply_action`. """ return False, None
Returns True and the match result if the version matches the rule. :type version: readthedocs.builds.models.Version :param str match_arg: Additional argument to perform the match :returns: A tuple of (boolean, match_resul). The result will be passed to `apply_action`.
match
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def apply_action(self, version, match_result): """ Apply the action from allowed_actions_on_*. :type version: readthedocs.builds.models.Version :param any match_result: Additional context from the match operation :raises: NotImplementedError if the action isn't implemented or supported for this rule. """ action = self.allowed_actions_on_create.get( self.action ) or self.allowed_actions_on_delete.get(self.action) if action is None: raise NotImplementedError action(version, match_result, self.action_arg)
Apply the action from allowed_actions_on_*. :type version: readthedocs.builds.models.Version :param any match_result: Additional context from the match operation :raises: NotImplementedError if the action isn't implemented or supported for this rule.
apply_action
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def move(self, steps): """ Change the priority of this Automation Rule. This is done by moving it ``n`` steps, relative to the other priority rules. The priority from the other rules are updated too. :param steps: Number of steps to be moved (it can be negative) """ total = self.project.automation_rules.count() current_priority = self.priority new_priority = (current_priority + steps) % total self.priority = new_priority self.save()
Change the priority of this Automation Rule. This is done by moving it ``n`` steps, relative to the other priority rules. The priority from the other rules are updated too. :param steps: Number of steps to be moved (it can be negative)
move
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def save(self, *args, **kwargs): """Override method to update the other priorities before save.""" self._position_manager.change_position_before_save(self) if not self.description: self.description = self.get_description() super().save(*args, **kwargs)
Override method to update the other priorities before save.
save
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def delete(self, *args, **kwargs): """Override method to update the other priorities after delete.""" super().delete(*args, **kwargs) self._position_manager.change_position_after_delete(self)
Override method to update the other priorities after delete.
delete
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def match(self, version, match_arg): """ Find a match using regex.search. .. note:: We use the regex module with the timeout arg to avoid ReDoS. We could use a finite state machine type of regex too, but there isn't a stable library at the time of writing this code. """ try: match = regex.search( match_arg, version.verbose_name, # Compatible with the re module flags=regex.VERSION0, timeout=self.TIMEOUT, ) return bool(match), match except TimeoutError: log.warning( "Timeout while parsing regex.", pattern=match_arg, version_slug=version.slug, ) except Exception: log.exception("Error parsing regex.", exc_info=True) return False, None
Find a match using regex.search. .. note:: We use the regex module with the timeout arg to avoid ReDoS. We could use a finite state machine type of regex too, but there isn't a stable library at the time of writing this code.
match
python
readthedocs/readthedocs.org
readthedocs/builds/models.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/models.py
MIT
def forwards_func(apps, schema_editor): """Migrate all data from versions to builds.""" Build = apps.get_model("builds", "Build") for build in Build.objects.all().iterator(): # When the build is saved, the fields are updated. build.save()
Migrate all data from versions to builds.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0032_migrate_version_data_to_build.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0032_migrate_version_data_to_build.py
MIT
def forwards_func(apps, schema_editor): """ Migrate all private versions to public and hidden. .. note:: This migration is skipped for the corporate site. """ if settings.ALLOW_PRIVATE_REPOS: return Version = apps.get_model("builds", "Version") (Version.objects.filter(privacy_level="private").update(privacy_level="public", hidden=True))
Migrate all private versions to public and hidden. .. note:: This migration is skipped for the corporate site.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0025_migrate_private_versions.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0025_migrate_private_versions.py
MIT
def forwards_func(apps, schema_editor): """Copy build config to JSONField.""" # Do migration in chunks, because prod Build table is a big boi. # We don't use `iterator()` here because `update()` will be quicker. Build = apps.get_model("builds", "Build") step = 10000 build_pks = Build.objects.aggregate(min_pk=Min("id"), max_pk=Max("id")) build_min_pk, build_max_pk = (build_pks["min_pk"], build_pks["max_pk"]) # Protection for tests, which have no build instances if not all([build_min_pk, build_max_pk]): return for first_pk in range(build_min_pk, build_max_pk, step): last_pk = first_pk + step build_update = ( Build.objects.filter( pk__gte=first_pk, pk__lt=last_pk, _config_json__isnull=True, ) .annotate( _config_in_json=Cast("_config", output_field=JSONField()), ) .update(_config_json=F("_config_in_json")) ) print(f"Migrated builds: first_pk={first_pk} last_pk={last_pk} updated={build_update}")
Copy build config to JSONField.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0039_migrate_config_data.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0039_migrate_config_data.py
MIT
def forwards_func(apps, schema_editor): """Migrate ``Project.documentation_type`` to ``Version.documentation_type``.""" Version = apps.get_model("builds", "Version") Project = apps.get_model("projects", "Project") Version.objects.all().update( documentation_type=Subquery( Project.objects.filter(pk=OuterRef("project")).values("documentation_type")[:1] ), )
Migrate ``Project.documentation_type`` to ``Version.documentation_type``.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0014_migrate-doctype-from-project-to-version.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0014_migrate-doctype-from-project-to-version.py
MIT
def forwards_func(apps, schema_editor): """ Migrate all protected versions. For .org, we mark them as public, and for .com we mark them as private. """ Version = apps.get_model("builds", "Version") target_privacy_level = "private" if settings.ALLOW_PRIVATE_REPOS else "public" Version.objects.filter(privacy_level="protected").update( privacy_level=target_privacy_level, )
Migrate all protected versions. For .org, we mark them as public, and for .com we mark them as private.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0022_migrate_protected_versions.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0022_migrate_protected_versions.py
MIT
def migrate(apps, schema_editor): """ Migrate the created and modified fields of the Version model to have a non-null value. This date corresponds to the release date of 5.6.5, when the created field was added to the Version model at https://github.com/readthedocs/readthedocs.org/commit/d72ee6e27dc398b97e884ccec8a8cf135134faac. """ Version = apps.get_model("builds", "Version") date = datetime.datetime(2020, 11, 23, tzinfo=datetime.timezone.utc) Version.objects.filter(created=None).update(created=date) Version.objects.filter(modified=None).update(modified=date)
Migrate the created and modified fields of the Version model to have a non-null value. This date corresponds to the release date of 5.6.5, when the created field was added to the Version model at https://github.com/readthedocs/readthedocs.org/commit/d72ee6e27dc398b97e884ccec8a8cf135134faac.
migrate
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0057_migrate_timestamp_fields.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0057_migrate_timestamp_fields.py
MIT
def forwards_func(apps, schema_editor): """ Migrate external Versions with `active=False` to use `state=Closed` and `active=True`. """ Version = apps.get_model("builds", "Version") # NOTE: we can't use `Version.external` because the Django's __fake__ # object does not declare it. So, we need to pass `type=external` in the # filter Version.objects.filter(type="external", active=False).update( active=True, state="closed", )
Migrate external Versions with `active=False` to use `state=Closed` and `active=True`.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0042_version_state.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0042_version_state.py
MIT
def forwards_func(apps, schema_editor): """Make all hidden fields not none.""" Version = apps.get_model("builds", "Version") Version.objects.filter(hidden=None).update(hidden=False)
Make all hidden fields not none.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0020_migrate_null_hidden_field.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0020_migrate_null_hidden_field.py
MIT
def forwards_func(apps, schema_editor): """Migrate all protected versions to be hidden.""" Version = apps.get_model("builds", "Version") Version.objects.filter(privacy_level="protected").update(hidden=True)
Migrate all protected versions to be hidden.
forwards_func
python
readthedocs/readthedocs.org
readthedocs/builds/migrations/0019_migrate_protected_versions_to_hidden.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/builds/migrations/0019_migrate_protected_versions_to_hidden.py
MIT
def to_item(self): """ Return a tuple with the feature type and the feature itself. Useful to use it as a dictionary item. """ return self.type, self
Return a tuple with the feature type and the feature itself. Useful to use it as a dictionary item.
to_item
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def __add__(self, other: "RTDProductFeature"): """Add the values of two features.""" if self.type != other.type: raise ValueError("Cannot add features of different types") new_feature = copy.copy(self) if self.unlimited or other.unlimited: new_feature.unlimited = True else: new_feature.value = self.value + other.value return new_feature
Add the values of two features.
__add__
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def __mul__(self, value: int): """Multiply the value of a feature by a number.""" new_feature = copy.copy(self) if self.unlimited: return new_feature new_feature.value = self.value * value return new_feature
Multiply the value of a feature by a number.
__mul__
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def to_item(self): """ Return a tuple with the stripe_id and the product itself. Useful to use it as a dictionary item. """ return self.stripe_id, self
Return a tuple with the stripe_id and the product itself. Useful to use it as a dictionary item.
to_item
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def get_product(stripe_id) -> RTDProduct: """Return the product with the given stripe_id.""" return settings.RTD_PRODUCTS.get(stripe_id)
Return the product with the given stripe_id.
get_product
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def get_listed_products(): """Return a list of products that are available to users to purchase.""" return [product for product in settings.RTD_PRODUCTS.values() if product.listed]
Return a list of products that are available to users to purchase.
get_listed_products
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def get_products_with_feature(feature_type) -> list[RTDProduct]: """Return a list of products that have the given feature.""" return [ product for product in settings.RTD_PRODUCTS.values() if feature_type in product.features ]
Return a list of products that have the given feature.
get_products_with_feature
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def get_feature(obj, feature_type) -> RTDProductFeature: """ Get the feature object for the given type of the object. If the object doesn't have the feature, return the default feature or None. :param obj: An organization or project instance. :param type: The type of the feature (readthedocs.subscriptions.constants.TYPE_*). """ # Hit the DB only if subscriptions and organizations are enabled. if not settings.RTD_PRODUCTS or not settings.RTD_ALLOW_ORGANIZATIONS: return settings.RTD_DEFAULT_FEATURES.get(feature_type) from readthedocs.organizations.models import Organization from readthedocs.projects.models import Project if isinstance(obj, Project): organization = obj.organizations.first() elif isinstance(obj, Organization): organization = obj else: raise TypeError # This happens when running tests on .com only. # In production projects are always associated with an organization. if not organization: return settings.RTD_DEFAULT_FEATURES.get(feature_type) # A subscription can have multiple products, but we only want # the products from the organization that has the feature we are looking for. available_stripe_products_id = [ product.stripe_id for product in get_products_with_feature(feature_type) ] stripe_subscription = organization.stripe_subscription if stripe_subscription: subscription_items = stripe_subscription.items.filter( price__product__id__in=available_stripe_products_id ).select_related("price__product") final_rtd_feature = None for subscription_item in subscription_items: rtd_feature = settings.RTD_PRODUCTS[subscription_item.price.product.id].features[ feature_type ] if final_rtd_feature is None: final_rtd_feature = rtd_feature * subscription_item.quantity else: final_rtd_feature += rtd_feature * subscription_item.quantity if final_rtd_feature: return final_rtd_feature # Fallback to the default feature if the organization # doesn't have a subscription with the feature. return settings.RTD_DEFAULT_FEATURES.get(feature_type)
Get the feature object for the given type of the object. If the object doesn't have the feature, return the default feature or None. :param obj: An organization or project instance. :param type: The type of the feature (readthedocs.subscriptions.constants.TYPE_*).
get_feature
python
readthedocs/readthedocs.org
readthedocs/subscriptions/products.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/products.py
MIT
def create_stripe_customer(organization): """Create a stripe customer for organization.""" stripe_data = stripe.Customer.create( email=organization.email, name=organization.name, description=organization.name, metadata=organization.get_stripe_metadata(), ) stripe_customer = djstripe.Customer.sync_from_stripe_data(stripe_data) organization.stripe_customer = stripe_customer organization.save() return stripe_customer
Create a stripe customer for organization.
create_stripe_customer
python
readthedocs/readthedocs.org
readthedocs/subscriptions/utils.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/utils.py
MIT
def get_or_create_stripe_customer(organization): """ Retrieve the stripe customer or create a new one. If `organization.stripe_customer` is `None`, a new customer is created. """ log.bind(organization_slug=organization.slug) stripe_customer = organization.stripe_customer if stripe_customer: return stripe_customer log.info("No stripe customer found, creating one.") return create_stripe_customer(organization)
Retrieve the stripe customer or create a new one. If `organization.stripe_customer` is `None`, a new customer is created.
get_or_create_stripe_customer
python
readthedocs/readthedocs.org
readthedocs/subscriptions/utils.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/utils.py
MIT
def get_or_create_stripe_subscription(organization): """ Get the stripe subscription attached to the organization or create one. The subscription will be created with the default price and a trial period. """ stripe_customer = get_or_create_stripe_customer(organization) stripe_subscription = organization.get_stripe_subscription() if not stripe_subscription: # TODO: djstripe 2.6.x doesn't return the subscription object # on subscribe(), but 2.7.x (unreleased) does! stripe_customer.subscribe( items=[{"price": settings.RTD_ORG_DEFAULT_STRIPE_SUBSCRIPTION_PRICE}], trial_period_days=settings.RTD_ORG_TRIAL_PERIOD_DAYS, ) stripe_subscription = stripe_customer.subscriptions.latest() if organization.stripe_subscription != stripe_subscription: organization.stripe_subscription = stripe_subscription organization.save() return stripe_subscription
Get the stripe subscription attached to the organization or create one. The subscription will be created with the default price and a trial period.
get_or_create_stripe_subscription
python
readthedocs/readthedocs.org
readthedocs/subscriptions/utils.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/utils.py
MIT
def redirect_to_checkout(self, form): """ Redirect to Stripe Checkout for users to buy a subscription. Users can buy a new subscription if the current one has been deleted after they canceled it. """ stripe_subscription = self.get_object() if not stripe_subscription or stripe_subscription.status != SubscriptionStatus.canceled: raise Http404() stripe_price = get_object_or_404(djstripe.Price, id=form.cleaned_data["plan"]) url = self.request.build_absolute_uri(self.get_success_url()) organization = self.get_organization() # pylint: disable=broad-except try: stripe_customer = get_or_create_stripe_customer(organization) checkout_session = stripe.checkout.Session.create( customer=stripe_customer.id, payment_method_types=["card"], line_items=[ { "price": stripe_price.id, "quantity": 1, } ], mode="subscription", success_url=url + "?upgraded=true", cancel_url=url, ) return HttpResponseRedirect(checkout_session.url) except Exception: log.exception( "Error while creating a Stripe checkout session.", organization_slug=organization.slug, price=stripe_price.id, ) messages.error( self.request, _("There was an error connecting to Stripe, please try again in a few minutes."), ) return HttpResponseRedirect(self.get_success_url())
Redirect to Stripe Checkout for users to buy a subscription. Users can buy a new subscription if the current one has been deleted after they canceled it.
redirect_to_checkout
python
readthedocs/readthedocs.org
readthedocs/subscriptions/views.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/views.py
MIT
def get_object(self): """ Get or create a default subscription for the organization. In case an error happened during the organization creation, the organization may not have a subscription attached to it. We retry the operation when the user visits the subscription page. """ org = self.get_organization() return get_or_create_stripe_subscription(org)
Get or create a default subscription for the organization. In case an error happened during the organization creation, the organization may not have a subscription attached to it. We retry the operation when the user visits the subscription page.
get_object
python
readthedocs/readthedocs.org
readthedocs/subscriptions/views.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/views.py
MIT
def post(self, request, *args, **kwargs): """Redirect the user to the Stripe billing portal.""" organization = self.get_organization() stripe_customer = organization.stripe_customer return_url = request.build_absolute_uri(self.get_success_url()) try: billing_portal = stripe.billing_portal.Session.create( customer=stripe_customer.id, return_url=return_url, ) return HttpResponseRedirect(billing_portal.url) except: # noqa log.exception( "There was an error connecting to Stripe to create the billing portal session.", stripe_customer=stripe_customer.id, organization_slug=organization.slug, ) messages.error( request, _("There was an error connecting to Stripe, please try again in a few minutes"), ) return HttpResponseRedirect(self.get_success_url())
Redirect the user to the Stripe billing portal.
post
python
readthedocs/readthedocs.org
readthedocs/subscriptions/views.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/views.py
MIT
def update_stripe_customer(sender, instance, created, **kwargs): """Update email and metadata attached to the stripe customer.""" if created: return organization = instance log.bind(organization_slug=organization.slug) stripe_customer = organization.stripe_customer if not stripe_customer: log.warning("Organization doesn't have a stripe customer attached.") return fields_to_update = {} if organization.email != stripe_customer.email: fields_to_update["email"] = organization.email if organization.name != stripe_customer.description: fields_to_update["description"] = organization.name if organization.name != stripe_customer.name: fields_to_update["name"] = organization.name org_metadata = organization.get_stripe_metadata() current_metadata = stripe_customer.metadata or {} for key, value in org_metadata.items(): if current_metadata.get(key) != value: current_metadata.update(org_metadata) fields_to_update["metadata"] = current_metadata break if fields_to_update: # pylint: disable=broad-except try: stripe.Customer.modify( stripe_customer.id, **fields_to_update, ) except stripe.error.StripeError: log.exception("Unable to update stripe customer.") except Exception: log.exception("Unknown error when updating stripe customer.")
Update email and metadata attached to the stripe customer.
update_stripe_customer
python
readthedocs/readthedocs.org
readthedocs/subscriptions/signals.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/signals.py
MIT
def trial_ending(self, days=7): """Get all subscriptions where their trial will end in the next `days`.""" now = timezone.now() ending = now + timedelta(days=days) return self.filter( status=SubscriptionStatus.trialing, trial_end__gt=now, trial_end__lt=ending, ).distinct()
Get all subscriptions where their trial will end in the next `days`.
trial_ending
python
readthedocs/readthedocs.org
readthedocs/subscriptions/querysets.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/querysets.py
MIT
def created_days_ago(self, days): """Get all subscriptions that were created exactly `days` ago.""" when = timezone.now() - timedelta(days=days) return self.filter(created__date=when)
Get all subscriptions that were created exactly `days` ago.
created_days_ago
python
readthedocs/readthedocs.org
readthedocs/subscriptions/querysets.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/querysets.py
MIT
def daily_email(): """Daily email beat task for organization notifications.""" organizations = OrganizationDisabledNotification.for_organizations().distinct() for organization in organizations: for owner in organization.owners.all(): notification = OrganizationDisabledNotification( context_object=organization, user=owner, ) log.info( "Notification sent.", recipient=owner, organization_slug=organization.slug, ) notification.send() for subscription in TrialEndingNotification.for_subscriptions(): organization = subscription.customer.rtd_organization if not organization: log.error( "Susbscription isn't attached to an organization", stripe_subscription_id=subscription.id, ) continue for owner in organization.owners.all(): notification = TrialEndingNotification( context_object=organization, user=owner, ) log.info( "Notification sent.", recipient=owner, organization_slug=organization.slug, ) notification.send()
Daily email beat task for organization notifications.
daily_email
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tasks.py
MIT
def weekly_subscription_stats_email(recipients=None): """ Weekly email to communicate stats about subscriptions. :param list recipients: List of emails to send the stats to. """ if not recipients: log.info("No recipients to send stats to.") return last_week = timezone.now() - datetime.timedelta(weeks=1) yesterday = timezone.now() - datetime.timedelta(days=1) projects = Project.objects.filter(pub_date__gte=last_week).count() builds = Build.objects.filter(date__gte=last_week).count() organizations = Organization.objects.filter(pub_date__gte=last_week).count() domains = Domain.objects.filter(created__gte=last_week).count() organizations_to_disable = Organization.objects.disable_soon(days=30).count() users = User.objects.filter(date_joined__gte=last_week).count() subscriptions = ( djstripe.Subscription.objects.filter( created__gte=last_week, created__lte=yesterday, ) .values("status", "items__price__product__name") .annotate(total_status=Count("status")) .order_by("status") ) context = { "projects": projects, "builds": builds, "organizations": organizations, "domains": domains, "organizations_to_disable": organizations_to_disable, "users": users, "subscriptions": list(subscriptions), } log.info("Sending weekly subscription stats email.") send_email( from_email="Read the Docs <[email protected]>", subject="Weekly subscription stats", recipient=recipients[0], template="subscriptions/notifications/subscription_stats_email.txt", template_html=None, context=context, # Use ``cc`` here because our ``send_email`` does not accept a list of recipients cc=recipients[1:], )
Weekly email to communicate stats about subscriptions. :param list recipients: List of emails to send the stats to.
weekly_subscription_stats_email
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tasks.py
MIT
def handler(*args, **kwargs): """ Register handlers only if organizations are enabled. Wrapper around the djstripe's webhooks.handler decorator, to register the handler only if organizations are enabled. """ def decorator(func): if settings.RTD_ALLOW_ORGANIZATIONS: return webhooks.handler(*args, **kwargs)(func) return func return decorator
Register handlers only if organizations are enabled. Wrapper around the djstripe's webhooks.handler decorator, to register the handler only if organizations are enabled.
handler
python
readthedocs/readthedocs.org
readthedocs/subscriptions/event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/event_handlers.py
MIT
def subscription_created_event(event): """ Handle the creation of a new subscription. When a new subscription is created, the latest subscription of the organization is updated to point to this new subscription. If the organization attached to the customer is disabled, we re-enable it, since the user just subscribed to a plan. """ stripe_subscription_id = event.data["object"]["id"] log.bind(stripe_subscription_id=stripe_subscription_id) stripe_subscription = djstripe.Subscription.objects.filter(id=stripe_subscription_id).first() if not stripe_subscription: log.info("Stripe subscription not found.") return organization = getattr(stripe_subscription.customer, "rtd_organization", None) if not organization: log.error("Subscription isn't attached to an organization") return if organization.disabled: log.info("Re-enabling organization.", organization_slug=organization.slug) organization.disabled = False old_subscription_id = ( organization.stripe_subscription.id if organization.stripe_subscription else None ) log.info( "Attaching new subscription to organization.", organization_slug=organization.slug, old_stripe_subscription_id=old_subscription_id, ) organization.stripe_subscription = stripe_subscription organization.save()
Handle the creation of a new subscription. When a new subscription is created, the latest subscription of the organization is updated to point to this new subscription. If the organization attached to the customer is disabled, we re-enable it, since the user just subscribed to a plan.
subscription_created_event
python
readthedocs/readthedocs.org
readthedocs/subscriptions/event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/event_handlers.py
MIT
def subscription_updated_event(event): """ Handle subscription updates. We need to cancel trial subscriptions manually when their trial period ends, otherwise Stripe will keep them active. If the organization attached to the subscription is disabled, and the subscription is now active, we re-enable the organization. We also re-evaluate the latest subscription attached to the organization, in case it changed. """ stripe_subscription_id = event.data["object"]["id"] log.bind(stripe_subscription_id=stripe_subscription_id) stripe_subscription = djstripe.Subscription.objects.filter(id=stripe_subscription_id).first() if not stripe_subscription: log.info("Stripe subscription not found.") return trial_ended = stripe_subscription.trial_end and stripe_subscription.trial_end < timezone.now() is_trial_subscription = stripe_subscription.items.filter( price__id=settings.RTD_ORG_DEFAULT_STRIPE_SUBSCRIPTION_PRICE ).exists() if ( is_trial_subscription and trial_ended and stripe_subscription.status != SubscriptionStatus.canceled ): log.info( "Trial ended, canceling subscription.", ) cancel_stripe_subscription(stripe_subscription.id) return organization = getattr(stripe_subscription.customer, "rtd_organization", None) if not organization: log.error("Subscription isn't attached to an organization") return if stripe_subscription.status == SubscriptionStatus.active and organization.disabled: log.info("Re-enabling organization.", organization_slug=organization.slug) organization.disabled = False if stripe_subscription.status not in ( SubscriptionStatus.active, SubscriptionStatus.trialing, ): log.info( "Organization disabled due its subscription is not active anymore.", organization_slug=organization.slug, ) organization.disabled = True new_stripe_subscription = organization.get_stripe_subscription() if organization.stripe_subscription != new_stripe_subscription: old_subscription_id = ( organization.stripe_subscription.id if organization.stripe_subscription else None ) log.info( "Attaching new subscription to organization.", organization_slug=organization.slug, old_stripe_subscription_id=old_subscription_id, ) organization.stripe_subscription = stripe_subscription organization.save()
Handle subscription updates. We need to cancel trial subscriptions manually when their trial period ends, otherwise Stripe will keep them active. If the organization attached to the subscription is disabled, and the subscription is now active, we re-enable the organization. We also re-evaluate the latest subscription attached to the organization, in case it changed.
subscription_updated_event
python
readthedocs/readthedocs.org
readthedocs/subscriptions/event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/event_handlers.py
MIT
def subscription_canceled(event): """ Send a notification to all owners if the subscription has ended. We send a different notification if the subscription that ended was a "trial subscription", since those are from new users. """ stripe_subscription_id = event.data["object"]["id"] log.bind(stripe_subscription_id=stripe_subscription_id) stripe_subscription = djstripe.Subscription.objects.filter(id=stripe_subscription_id).first() if not stripe_subscription: log.info("Stripe subscription not found.") return total_spent = ( stripe_subscription.customer.charges.filter(status=ChargeStatus.succeeded) .aggregate(total=Sum("amount")) .get("total") or 0 ) log.bind(total_spent=total_spent) # Using `getattr` to avoid the `RelatedObjectDoesNotExist` exception # when the subscription doesn't have an organization attached to it. organization = getattr(stripe_subscription.customer, "rtd_organization", None) if not organization: log.error("Subscription isn't attached to an organization") return log.bind(organization_slug=organization.slug) is_trial_subscription = stripe_subscription.items.filter( price__id=settings.RTD_ORG_DEFAULT_STRIPE_SUBSCRIPTION_PRICE ).exists() notification_class = ( SubscriptionRequiredNotification if is_trial_subscription else SubscriptionEndedNotification ) for owner in organization.owners.all(): notification = notification_class( context_object=organization, user=owner, ) notification.send() log.info( "Notification sent.", username=owner.username, organization_slug=organization.slug, ) if settings.SLACK_WEBHOOK_SALES_CHANNEL and total_spent > 0: start_date = stripe_subscription.start_date.strftime("%b %-d, %Y") timesince = humanize.naturaltime(stripe_subscription.start_date).split(",")[0] domains = Domain.objects.filter(project__organizations__in=[organization]).count() try: sso_integration = organization.ssointegration.provider except SSOIntegration.DoesNotExist: sso_integration = "Read the Docs Auth" # https://api.slack.com/surfaces/messages#payloads slack_message = { "blocks": [ { "type": "section", "text": {"type": "mrkdwn", "text": ":x: *Subscription canceled*"}, }, {"type": "divider"}, { "type": "section", "fields": [ { "type": "mrkdwn", "text": f":office: *Name:* <{settings.ADMIN_URL}/organizations/organization/{organization.pk}/change/|{organization.name}>", }, { "type": "mrkdwn", "text": f":dollar: *Plan:* <https://dashboard.stripe.com/customers/{stripe_subscription.customer_id}|{stripe_subscription.plan.product.name}> (${str(total_spent)})", }, { "type": "mrkdwn", "text": f":date: *Customer since:* {start_date} (~{timesince})", }, { "type": "mrkdwn", "text": f":books: *Projects:* {organization.projects.count()}", }, {"type": "mrkdwn", "text": f":link: *Domains:* {domains}"}, { "type": "mrkdwn", "text": f":closed_lock_with_key: *Authentication:* {sso_integration}", }, { "type": "mrkdwn", "text": f":busts_in_silhouette: *Teams:* {organization.teams.count()}", }, ], }, { "type": "context", "elements": [ { "type": "mrkdwn", "text": "We should contact this customer and see if we can get some feedback from them.", } ], }, ] } try: response = requests.post( settings.SLACK_WEBHOOK_SALES_CHANNEL, json=slack_message, timeout=3, ) if not response.ok: log.error("There was an issue when sending a message to Slack webhook") except requests.Timeout: log.warning("Timeout sending a message to Slack webhook")
Send a notification to all owners if the subscription has ended. We send a different notification if the subscription that ended was a "trial subscription", since those are from new users.
subscription_canceled
python
readthedocs/readthedocs.org
readthedocs/subscriptions/event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/event_handlers.py
MIT
def customer_updated_event(event): """Update the organization with the new information from the stripe customer.""" stripe_customer = event.data["object"] log.bind(stripe_customer_id=stripe_customer["id"]) organization = Organization.objects.filter(stripe_id=stripe_customer["id"]).first() if not organization: log.error("Customer isn't attached to an organization.") new_email = stripe_customer["email"] if organization.email != new_email: organization.email = new_email organization.save() log.info( "Organization billing email updated.", organization_slug=organization.slug, email=new_email, )
Update the organization with the new information from the stripe customer.
customer_updated_event
python
readthedocs/readthedocs.org
readthedocs/subscriptions/event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/event_handlers.py
MIT
def _add_custom_manager(self): """ Add a custom manager to the djstripe Subscription model. Patching the model directly isn't recommended, since there may be an additional setup done by django when adding a manager. Using django's contribute_to_class is the recommended way of adding a custom manager to a third party model. The new manager will be accessible from ``Subscription.readthedocs``. """ from djstripe.models import Subscription from readthedocs.subscriptions.querysets import StripeSubscriptionQueryset manager = StripeSubscriptionQueryset.as_manager() manager.contribute_to_class(Subscription, "readthedocs")
Add a custom manager to the djstripe Subscription model. Patching the model directly isn't recommended, since there may be an additional setup done by django when adding a manager. Using django's contribute_to_class is the recommended way of adding a custom manager to a third party model. The new manager will be accessible from ``Subscription.readthedocs``.
_add_custom_manager
python
readthedocs/readthedocs.org
readthedocs/subscriptions/apps.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/apps.py
MIT
def test_subscription_updated_event(self, cancel_subscription_mock): """Test handled event.""" start_date = timezone.now() end_date = timezone.now() + timezone.timedelta(days=30) stripe_subscription = get( djstripe.Subscription, id="sub_9LtsU02uvjO6Ed", status=SubscriptionStatus.active, current_period_start=start_date, current_period_end=end_date, trial_end=end_date, ) event = get( djstripe.Event, data={ "object": { "id": "sub_9LtsU02uvjO6Ed", "object": "subscription", } }, ) event_handlers.subscription_updated_event(event=event) cancel_subscription_mock.assert_not_called()
Test handled event.
test_subscription_updated_event
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tests/test_event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tests/test_event_handlers.py
MIT
def test_reenable_organization_on_subscription_updated_event(self): """Organization is re-enabled when subscription is active.""" customer = get(djstripe.Customer, id="cus_KMiHJXFHpLkcRP") self.organization.stripe_customer = customer self.organization.disabled = True self.organization.save() start_date = timezone.now() end_date = timezone.now() + timezone.timedelta(days=30) stripe_subscription = get( djstripe.Subscription, id="sub_9LtsU02uvjO6Ed", customer=customer, status=SubscriptionStatus.active, current_period_start=start_date, current_period_end=end_date, trial_end=end_date, ) event = get( djstripe.Event, data={ "object": { "id": "sub_9LtsU02uvjO6Ed", "object": "subscription", } }, ) self.assertTrue(self.organization.disabled) event_handlers.subscription_updated_event(event=event) self.organization.refresh_from_db() self.assertFalse(self.organization.disabled)
Organization is re-enabled when subscription is active.
test_reenable_organization_on_subscription_updated_event
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tests/test_event_handlers.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tests/test_event_handlers.py
MIT
def test_trial_ending(self, mock_send_email): """Trial ending daily email.""" now = timezone.now() owner1 = get(User) org1 = get(Organization, owners=[owner1]) customer1 = get(djstripe.Customer) org1.stripe_customer = customer1 org1.save() get( djstripe.Subscription, status=SubscriptionStatus.trialing, trial_start=now, trial_end=now + timedelta(days=7), created=now - timedelta(days=24), customer=customer1, ) owner2 = get(User) org2 = fixture.get(Organization, owners=[owner2]) customer2 = get(djstripe.Customer) org2.stripe_customer = customer2 org2.save() get( djstripe.Subscription, status=SubscriptionStatus.trialing, trial_start=now, trial_end=now + timedelta(days=7), created=now - timedelta(days=25), ) daily_email() self.assertEqual(mock_send_email.call_count, 1) mock_send_email.assert_has_calls( [ mock.call( subject="Your trial is ending soon", recipient=owner1.email, template=mock.ANY, template_html=mock.ANY, context=mock.ANY, ), ] )
Trial ending daily email.
test_trial_ending
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tests/test_tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tests/test_tasks.py
MIT
def test_organizations_to_be_disabled_email(self, mock_send_email): """Subscription ended ``DISABLE_AFTER_DAYS`` days ago daily email.""" customer1 = get(djstripe.Customer) latest_invoice1 = get( djstripe.Invoice, due_date=timezone.now() - timedelta(days=30), status=InvoiceStatus.open, ) sub1 = get( djstripe.Subscription, status=SubscriptionStatus.past_due, latest_invoice=latest_invoice1, customer=customer1, ) owner1 = get(User) get( Organization, owners=[owner1], stripe_customer=customer1, stripe_subscription=sub1, ) customer2 = get(djstripe.Customer) latest_invoice2 = get( djstripe.Invoice, due_date=timezone.now() - timedelta(days=35), status=InvoiceStatus.open, ) sub2 = get( djstripe.Subscription, status=SubscriptionStatus.past_due, latest_invoice=latest_invoice2, customer=customer2, ) owner2 = get(User) get( Organization, owners=[owner2], stripe_customer=customer2, stripe_subscription=sub2, ) daily_email() self.assertEqual(mock_send_email.call_count, 1) mock_send_email.assert_has_calls( [ mock.call( subject="Your Read the Docs organization will be disabled soon", recipient=owner1.email, template=mock.ANY, template_html=mock.ANY, context=mock.ANY, ), ] )
Subscription ended ``DISABLE_AFTER_DAYS`` days ago daily email.
test_organizations_to_be_disabled_email
python
readthedocs/readthedocs.org
readthedocs/subscriptions/tests/test_tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/subscriptions/tests/test_tasks.py
MIT
def _expand_regex(pattern): """ Expand a pattern with the patterns from pattern_opts. This is used to avoid having a long regex. """ return re.compile( pattern.format( language=f"(?P<language>{pattern_opts['lang_slug']})", version=f"(?P<version>{pattern_opts['version_slug']})", filename=f"(?P<filename>{pattern_opts['filename_slug']})", subproject=f"(?P<subproject>{pattern_opts['project_slug']})", ) )
Expand a pattern with the patterns from pattern_opts. This is used to avoid having a long regex.
_expand_regex
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def unresolve_url(self, url, append_indexhtml=True): """ Turn a URL into the component parts that our views would use to process them. This is useful for lots of places, like where we want to figure out exactly what file a URL maps to. :param url: Full URL to unresolve (including the protocol and domain part). :param append_indexhtml: If `True` directories will be normalized to end with ``/index.html``. """ parsed_url = urlparse(url) if parsed_url.scheme not in ["http", "https"]: raise InvalidSchemeError(parsed_url.scheme) domain = parsed_url.hostname unresolved_domain = self.unresolve_domain(domain) return self._unresolve( unresolved_domain=unresolved_domain, parsed_url=parsed_url, append_indexhtml=append_indexhtml, )
Turn a URL into the component parts that our views would use to process them. This is useful for lots of places, like where we want to figure out exactly what file a URL maps to. :param url: Full URL to unresolve (including the protocol and domain part). :param append_indexhtml: If `True` directories will be normalized to end with ``/index.html``.
unresolve_url
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def unresolve_path(self, unresolved_domain, path, append_indexhtml=True): """ Unresolve a path given a unresolved domain. This is the same as the unresolve method, but this method takes an unresolved domain from unresolve_domain as input. :param unresolved_domain: An UnresolvedDomain object. :param path: Path to unresolve (this shouldn't include the protocol or querystrings). :param append_indexhtml: If `True` directories will be normalized to end with ``/index.html``. """ # Make sure we always have a leading slash. path = self._normalize_filename(path) # We don't call unparse() on the path, # since it could be parsed as a full URL if it starts with a protocol. parsed_url = ParseResult(scheme="", netloc="", path=path, params="", query="", fragment="") return self._unresolve( unresolved_domain=unresolved_domain, parsed_url=parsed_url, append_indexhtml=append_indexhtml, )
Unresolve a path given a unresolved domain. This is the same as the unresolve method, but this method takes an unresolved domain from unresolve_domain as input. :param unresolved_domain: An UnresolvedDomain object. :param path: Path to unresolve (this shouldn't include the protocol or querystrings). :param append_indexhtml: If `True` directories will be normalized to end with ``/index.html``.
unresolve_path
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _unresolve(self, unresolved_domain, parsed_url, append_indexhtml): """ The actual unresolver. Extracted into a separate method so it can be re-used by the unresolve and unresolve_path methods. """ current_project, version, filename = self._unresolve_path_with_parent_project( parent_project=unresolved_domain.project, path=parsed_url.path, external_version_slug=unresolved_domain.external_version_slug, ) if append_indexhtml and filename.endswith("/"): filename += "index.html" return UnresolvedURL( parent_project=unresolved_domain.project, project=current_project, version=version, filename=filename, parsed_url=parsed_url, domain=unresolved_domain.domain, external=unresolved_domain.is_from_external_domain, )
The actual unresolver. Extracted into a separate method so it can be re-used by the unresolve and unresolve_path methods.
_unresolve
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _normalize_filename(filename): """Normalize filename to always start with ``/``.""" filename = filename or "/" if not filename.startswith("/"): filename = "/" + filename return filename
Normalize filename to always start with ``/``.
_normalize_filename
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _match_multiple_versions_with_translations_project( self, parent_project, path, external_version_slug=None ): """ Try to match a multiversion project. An exception is raised if we weren't able to find a matching version or language, this exception has the current project (useful for 404 pages). :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match. """ custom_prefix = parent_project.custom_prefix if custom_prefix: if not path.startswith(custom_prefix): return None # pep8 and black don't agree on having a space before :, # so syntax is black with noqa for pep8. path = self._normalize_filename(path[len(custom_prefix) :]) # noqa match = self.multiple_versions_with_translations_pattern.match(path) if not match: return None language = match.group("language") # Normalize old language codes to lowercase with dashes. language = language.lower().replace("_", "-") version_slug = match.group("version") filename = self._normalize_filename(match.group("filename")) if parent_project.language == language: project = parent_project else: project = parent_project.translations.filter(language=language).first() if not project: raise TranslationNotFoundError( project=parent_project, language=language, version_slug=version_slug, filename=filename, ) # If only the language part was given, # we can't resolve the version. if version_slug is None: raise TranslationWithoutVersionError( project=project, language=language, ) if external_version_slug and external_version_slug != version_slug: raise InvalidExternalVersionError( project=project, version_slug=version_slug, external_version_slug=external_version_slug, ) manager = EXTERNAL if external_version_slug else INTERNAL version = project.versions(manager=manager).filter(slug=version_slug).first() if not version: raise VersionNotFoundError( project=project, version_slug=version_slug, filename=filename ) return project, version, filename
Try to match a multiversion project. An exception is raised if we weren't able to find a matching version or language, this exception has the current project (useful for 404 pages). :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match.
_match_multiple_versions_with_translations_project
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _match_subproject(self, parent_project, path, external_version_slug=None): """ Try to match a subproject. If the subproject exists, we try to resolve the rest of the path with the subproject as the canonical project. :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match. """ custom_prefix = parent_project.custom_subproject_prefix or "/projects/" if not path.startswith(custom_prefix): return None # pep8 and black don't agree on having a space before :, # so syntax is black with noqa for pep8. path = self._normalize_filename(path[len(custom_prefix) :]) # noqa match = self.subproject_pattern.match(path) if not match: return None subproject_alias = match.group("subproject") filename = self._normalize_filename(match.group("filename")) project_relationship = ( parent_project.subprojects.filter(alias=subproject_alias) .select_related("child") .first() ) if project_relationship: # We use the subproject as the new parent project # to resolve the rest of the path relative to it. subproject = project_relationship.child response = self._unresolve_path_with_parent_project( parent_project=subproject, path=filename, check_subprojects=False, external_version_slug=external_version_slug, ) return response return None
Try to match a subproject. If the subproject exists, we try to resolve the rest of the path with the subproject as the canonical project. :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match.
_match_subproject
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _match_single_version_without_translations_project( self, parent_project, path, external_version_slug=None ): """ Try to match a single version project. By default any path will match. If `external_version_slug` is given, that version is used instead of the project's default version. An exception is raised if we weren't able to find a matching version, this exception has the current project (useful for 404 pages). :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match. """ custom_prefix = parent_project.custom_prefix if custom_prefix: if not path.startswith(custom_prefix): return None # pep8 and black don't agree on having a space before :, # so syntax is black with noqa for pep8. path = path[len(custom_prefix) :] # noqa # In single version projects, any path is allowed, # so we don't need a regex for that. filename = self._normalize_filename(path) if external_version_slug: version_slug = external_version_slug manager = EXTERNAL else: version_slug = parent_project.default_version manager = INTERNAL version = parent_project.versions(manager=manager).filter(slug=version_slug).first() if not version: raise VersionNotFoundError( project=parent_project, version_slug=version_slug, filename=filename ) return parent_project, version, filename
Try to match a single version project. By default any path will match. If `external_version_slug` is given, that version is used instead of the project's default version. An exception is raised if we weren't able to find a matching version, this exception has the current project (useful for 404 pages). :returns: A tuple with the current project, version and filename. Returns `None` if there isn't a total or partial match.
_match_single_version_without_translations_project
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _unresolve_path_with_parent_project( self, parent_project, path, check_subprojects=True, external_version_slug=None ): """ Unresolve `path` with `parent_project` as base. The returned project, version, and filename are guaranteed to not be `None`. An exception is raised if we weren't able to resolve the project, version or path/filename. The checks are done in the following order: - Check for multiple versions if the parent project isn't a single version project. - Check for subprojects. - Check for single versions if the parent project isn't a multi version project. :param parent_project: The project that owns the path. :param path: The path to unresolve. :param check_subprojects: If we should check for subprojects, this is used to call this function recursively when resolving the path from a subproject (we don't support subprojects of subprojects). :param external_version_slug: Slug of the external version. Used instead of the default version for single version projects being served under an external domain. :returns: A tuple with: project, version, and filename. """ # Multiversion project. if parent_project.versioning_scheme == MULTIPLE_VERSIONS_WITH_TRANSLATIONS: response = self._match_multiple_versions_with_translations_project( parent_project=parent_project, path=path, external_version_slug=external_version_slug, ) if response: return response # Subprojects. if check_subprojects: response = self._match_subproject( parent_project=parent_project, path=path, external_version_slug=external_version_slug, ) if response: return response # Single language project. if parent_project.versioning_scheme == MULTIPLE_VERSIONS_WITHOUT_TRANSLATIONS: response = self._match_multiple_versions_without_translations_project( parent_project=parent_project, path=path, external_version_slug=external_version_slug, ) if response: return response # Single version project. if parent_project.versioning_scheme == SINGLE_VERSION_WITHOUT_TRANSLATIONS: response = self._match_single_version_without_translations_project( parent_project=parent_project, path=path, external_version_slug=external_version_slug, ) if response: return response raise InvalidPathForVersionedProjectError( project=parent_project, path=self._normalize_filename(path), )
Unresolve `path` with `parent_project` as base. The returned project, version, and filename are guaranteed to not be `None`. An exception is raised if we weren't able to resolve the project, version or path/filename. The checks are done in the following order: - Check for multiple versions if the parent project isn't a single version project. - Check for subprojects. - Check for single versions if the parent project isn't a multi version project. :param parent_project: The project that owns the path. :param path: The path to unresolve. :param check_subprojects: If we should check for subprojects, this is used to call this function recursively when resolving the path from a subproject (we don't support subprojects of subprojects). :param external_version_slug: Slug of the external version. Used instead of the default version for single version projects being served under an external domain. :returns: A tuple with: project, version, and filename.
_unresolve_path_with_parent_project
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def get_domain_from_host(host): """ Get the normalized domain from a hostname. A hostname can include the port. """ return host.lower().split(":")[0]
Get the normalized domain from a hostname. A hostname can include the port.
get_domain_from_host
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def unresolve_domain(self, domain): """ Unresolve domain by extracting relevant information from it. :param str domain: Domain to extract the information from. It can be a full URL, in that case, only the domain is used. :returns: A UnresolvedDomain object. """ parsed_domain = urlparse(domain) if parsed_domain.scheme: if parsed_domain.scheme not in ["http", "https"]: raise InvalidSchemeError(parsed_domain.scheme) domain = parsed_domain.hostname if not domain: raise InvalidSubdomainError(domain) public_domain = self.get_domain_from_host(settings.PUBLIC_DOMAIN) external_domain = self.get_domain_from_host(settings.RTD_EXTERNAL_VERSION_DOMAIN) subdomain, *root_domain = domain.split(".", maxsplit=1) root_domain = root_domain[0] if root_domain else "" # Serve from the PUBLIC_DOMAIN, ensuring it looks like `foo.PUBLIC_DOMAIN`. if public_domain == root_domain: project_slug = subdomain log.debug("Public domain.", domain=domain) return UnresolvedDomain( source_domain=domain, source=DomainSourceType.public_domain, project=self._resolve_project_slug(project_slug, domain), ) # Serve from the RTD_EXTERNAL_VERSION_DOMAIN, ensuring it looks like # `project--version.RTD_EXTERNAL_VERSION_DOMAIN`. if external_domain == root_domain: try: project_slug, version_slug = subdomain.rsplit("--", maxsplit=1) log.debug("External versions domain.", domain=domain) return UnresolvedDomain( source_domain=domain, source=DomainSourceType.external_domain, project=self._resolve_project_slug(project_slug, domain), external_version_slug=version_slug, ) except ValueError as exc: log.info("Invalid format of external versions domain.", domain=domain) raise InvalidExternalDomainError(domain=domain) from exc if public_domain in domain or external_domain in domain: # NOTE: This can catch some possibly valid domains (docs.readthedocs.io.com) # for example, but these might be phishing, so let's block them for now. log.debug("Weird variation of our domain.", domain=domain) raise SuspiciousHostnameError(domain=domain) # Custom domain. domain_object = Domain.objects.filter(domain=domain).select_related("project").first() if not domain_object: log.info("Invalid domain.", domain=domain) raise InvalidCustomDomainError(domain=domain) log.debug("Custom domain.", domain=domain) return UnresolvedDomain( source_domain=domain, source=DomainSourceType.custom_domain, project=domain_object.project, domain=domain_object, )
Unresolve domain by extracting relevant information from it. :param str domain: Domain to extract the information from. It can be a full URL, in that case, only the domain is used. :returns: A UnresolvedDomain object.
unresolve_domain
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def _resolve_project_slug(self, slug, domain): """Get the project from the slug or raise an exception if not found.""" try: return Project.objects.get(slug=slug) except Project.DoesNotExist as exc: raise InvalidSubdomainError(domain=domain) from exc
Get the project from the slug or raise an exception if not found.
_resolve_project_slug
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def unresolve_domain_from_request(self, request): """ Unresolve domain by extracting relevant information from the request. We first check if the ``X-RTD-Slug`` header has been set for explicit project mapping, otherwise we unresolve by calling `self.unresolve_domain` on the host. :param request: Request to extract the information from. :returns: A UnresolvedDomain object. """ host = self.get_domain_from_host(request.get_host()) log.bind(host=host) # Explicit Project slug being passed in. header_project_slug = request.headers.get("X-RTD-Slug", "").lower() if header_project_slug: project = Project.objects.filter( slug=header_project_slug, feature__feature_id=Feature.RESOLVE_PROJECT_FROM_HEADER, ).first() if project: log.info( "Setting project based on X_RTD_SLUG header.", project_slug=project.slug, ) return UnresolvedDomain( source_domain=host, source=DomainSourceType.http_header, project=project, ) log.warning( "X-RTD-Header passed for project without it enabled.", project_slug=header_project_slug, ) raise InvalidXRTDSlugHeaderError return unresolver.unresolve_domain(host)
Unresolve domain by extracting relevant information from the request. We first check if the ``X-RTD-Slug`` header has been set for explicit project mapping, otherwise we unresolve by calling `self.unresolve_domain` on the host. :param request: Request to extract the information from. :returns: A UnresolvedDomain object.
unresolve_domain_from_request
python
readthedocs/readthedocs.org
readthedocs/core/unresolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/unresolver.py
MIT
def process_email_confirmed(request, email_address, **kwargs): """ Steps to take after a users email address is confirmed. We currently: * Subscribe the user to the mailing list if they set this in their signup. * Add them to a drip campaign for new users in the new user group. """ # email_address is an object # https://github.com/pennersr/django-allauth/blob/6315e25/allauth/account/models.py#L15 user = email_address.user profile = UserProfile.objects.filter(user=user).first() if profile and profile.mailing_list: # TODO: Unsubscribe users if they unset `mailing_list`. log.bind( email=email_address.email, username=user.username, ) log.info("Subscribing user to newsletter and onboarding group.") # Try subscribing user to a group, then fallback to normal subscription API url = settings.MAILERLITE_API_ONBOARDING_GROUP_URL if not url: url = settings.MAILERLITE_API_SUBSCRIBERS_URL payload = { "email": email_address.email, "resubscribe": True, } headers = { "X-MailerLite-ApiKey": settings.MAILERLITE_API_KEY, } try: # TODO: migrate this signal to a Celery task since it has a `requests.post` on it. resp = requests.post( url, json=payload, headers=headers, timeout=3, # seconds ) resp.raise_for_status() except requests.Timeout: log.warning("Timeout subscribing user to newsletter.") except Exception: # noqa log.exception("Unknown error subscribing user to newsletter.")
Steps to take after a users email address is confirmed. We currently: * Subscribe the user to the mailing list if they set this in their signup. * Add them to a drip campaign for new users in the new user group.
process_email_confirmed
python
readthedocs/readthedocs.org
readthedocs/core/signals.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/signals.py
MIT
def delete_projects_and_organizations(sender, instance, *args, **kwargs): """ Delete projects and organizations where the user is the only owner. We delete projects that don't belong to an organization first, then full organizations. """ user = instance for project in Project.objects.single_owner(user): project.delete() for organization in Organization.objects.single_owner(user): organization.delete()
Delete projects and organizations where the user is the only owner. We delete projects that don't belong to an organization first, then full organizations.
delete_projects_and_organizations
python
readthedocs/readthedocs.org
readthedocs/core/signals.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/signals.py
MIT
def full_clean(self): """ Extend full clean method with prevalidation cleaning. Where :py:method:`forms.Form.full_clean` bails out if there is no bound data on the form, this method always checks prevalidation no matter what. This gives errors before submission and after submission. """ # Always call prevalidation, ``full_clean`` bails if the form is unbound self._clean_prevalidation() super().full_clean() # ``full_clean`` sets ``self._errors``, so we prepend prevalidation # errors after calling the parent ``full_clean`` if self._prevalidation_errors is not None: non_field_errors = [] non_field_errors.extend(self._prevalidation_errors) non_field_errors.extend(self._errors.get(NON_FIELD_ERRORS, [])) self._errors[NON_FIELD_ERRORS] = non_field_errors
Extend full clean method with prevalidation cleaning. Where :py:method:`forms.Form.full_clean` bails out if there is no bound data on the form, this method always checks prevalidation no matter what. This gives errors before submission and after submission.
full_clean
python
readthedocs/readthedocs.org
readthedocs/core/forms.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/forms.py
MIT
def _clean_prevalidation(self): """ Catch validation errors raised by the subclassed ``clean_validation()``. This wraps ``clean_prevalidation()`` using the same pattern that :py:method:`form.Form._clean_form` wraps :py:method:`clean`. Validation errors raised in the subclass method will be eventually added to the form error list but :py:method:`full_clean`. """ try: self.clean_prevalidation() except forms.ValidationError as validation_error: self._prevalidation_errors = [validation_error]
Catch validation errors raised by the subclassed ``clean_validation()``. This wraps ``clean_prevalidation()`` using the same pattern that :py:method:`form.Form._clean_form` wraps :py:method:`clean`. Validation errors raised in the subclass method will be eventually added to the form error list but :py:method:`full_clean`.
_clean_prevalidation
python
readthedocs/readthedocs.org
readthedocs/core/forms.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/forms.py
MIT
def valid_value(self, value): """ Although this is a choice field, no choices need to be supplied. Instead, we just validate that the value is in the correct format for facet filtering (facet_name:value) """ if ":" not in value: return False return True
Although this is a choice field, no choices need to be supplied. Instead, we just validate that the value is in the correct format for facet filtering (facet_name:value)
valid_value
python
readthedocs/readthedocs.org
readthedocs/core/forms.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/forms.py
MIT
def get_filterset(self, **kwargs): """ Construct filterset for view. This does not automatically execute like it would with BaseFilterView. Instead, this should be called directly from ``get_context_data()``. Unlike the parent methods, this method can be used to pass arguments directly to the ``FilterSet.__init__``. :param kwargs: Arguments to pass to ``FilterSet.__init__`` """ # This method overrides the method from FilterMixin with differing # arguments. We can switch this later if we ever resturcture the view # pylint: disable=arguments-differ if not getattr(self, "filterset", None): filterset_class = self.get_filterset_class() all_kwargs = self.get_filterset_kwargs(filterset_class) all_kwargs.update(kwargs) self.filterset = filterset_class(**all_kwargs) return self.filterset
Construct filterset for view. This does not automatically execute like it would with BaseFilterView. Instead, this should be called directly from ``get_context_data()``. Unlike the parent methods, this method can be used to pass arguments directly to the ``FilterSet.__init__``. :param kwargs: Arguments to pass to ``FilterSet.__init__``
get_filterset
python
readthedocs/readthedocs.org
readthedocs/core/filters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/filters.py
MIT
def readthedocs_processor(request): """ Context processor to include global settings to templates. Note that we are not using the ``request`` object at all here. It's preferable to keep it like that since it's used from places where there is no request. If you need to add something that depends on the request, create a new context processor. """ exports = { "PUBLIC_DOMAIN": settings.PUBLIC_DOMAIN, "PRODUCTION_DOMAIN": settings.PRODUCTION_DOMAIN, # TODO this can be removed with RTD_EXT_THEME_ENABLED "SWITCH_PRODUCTION_DOMAIN": settings.SWITCH_PRODUCTION_DOMAIN, "GLOBAL_ANALYTICS_CODE": settings.GLOBAL_ANALYTICS_CODE, "DASHBOARD_ANALYTICS_CODE": settings.DASHBOARD_ANALYTICS_CODE, "SITE_ROOT": settings.SITE_ROOT + "/", "TEMPLATE_ROOT": settings.TEMPLATE_ROOT + "/", "DO_NOT_TRACK_ENABLED": settings.DO_NOT_TRACK_ENABLED, "USE_PROMOS": settings.USE_PROMOS, "USE_ORGANIZATIONS": settings.RTD_ALLOW_ORGANIZATIONS, "SUPPORT_EMAIL": settings.SUPPORT_EMAIL, "PUBLIC_API_URL": settings.PUBLIC_API_URL, "RTD_EXT_THEME_ENABLED": settings.RTD_EXT_THEME_ENABLED, "ADMIN_URL": settings.ADMIN_URL, } return exports
Context processor to include global settings to templates. Note that we are not using the ``request`` object at all here. It's preferable to keep it like that since it's used from places where there is no request. If you need to add something that depends on the request, create a new context processor.
readthedocs_processor
python
readthedocs/readthedocs.org
readthedocs/core/context_processors.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/context_processors.py
MIT
def user_notifications(request): """ Context processor to include user's notification to templates. We can't use ``request.user.notifications.all()`` because we are not using a ``CustomUser``. If we want to go that route, we should define a ``CustomUser`` and define a ``GenericRelation``. See https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-AUTH_USER_MODEL """ # Import here due to circular import from readthedocs.notifications.models import Notification user_notifications = Notification.objects.none() if request.user.is_authenticated: user_notifications = Notification.objects.for_user( request.user, resource=request.user, ) return { "user_notifications": user_notifications, }
Context processor to include user's notification to templates. We can't use ``request.user.notifications.all()`` because we are not using a ``CustomUser``. If we want to go that route, we should define a ``CustomUser`` and define a ``GenericRelation``. See https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-AUTH_USER_MODEL
user_notifications
python
readthedocs/readthedocs.org
readthedocs/core/context_processors.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/context_processors.py
MIT
def load_settings(cls, module_name): """ Export class variables and properties to module namespace. This will export and class variable that is all upper case and doesn't begin with ``_``. These members will be set as attributes on the module ``module_name``. """ self = cls() module = sys.modules[module_name] for member, value in inspect.getmembers(self): if member.isupper() and not member.startswith("_"): if isinstance(value, property): value = value.fget(self) setattr(module, member, value)
Export class variables and properties to module namespace. This will export and class variable that is all upper case and doesn't begin with ``_``. These members will be set as attributes on the module ``module_name``.
load_settings
python
readthedocs/readthedocs.org
readthedocs/core/settings.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/settings.py
MIT
def projects(cls, user, admin=False, member=False): """ Return all the projects the user has access to as ``admin`` or ``member``. If `RTD_ALLOW_ORGANIZATIONS` is enabled This function takes into consideration VCS SSO and Google SSO. It includes: - projects where the user has access to via VCS SSO. - Projects where the user has access via Team, if VCS SSO is not enabled for the organization of that team. .. note:: SSO is taken into consideration, but isn't implemented in .org yet. :param user: user object to filter projects :type user: django.contrib.admin.models.User :param bool admin: include projects where the user has admin access to the project :param bool member: include projects where the user has read access to the project """ from readthedocs.projects.models import Project from readthedocs.sso.models import SSOIntegration projects = Project.objects.none() if not user or not user.is_authenticated: return projects if not settings.RTD_ALLOW_ORGANIZATIONS: # All users are admin and member of a project # when we aren't using organizations. return user.projects.all() if admin: # Project Team Admin admin_teams = user.teams.filter(access=ADMIN_ACCESS) for team in admin_teams: if not cls.has_sso_enabled(team.organization, SSOIntegration.PROVIDER_ALLAUTH): projects |= team.projects.all() # Org Admin for org in user.owner_organizations.all(): if not cls.has_sso_enabled(org, SSOIntegration.PROVIDER_ALLAUTH): # Do not grant admin access on projects for owners if the # organization has SSO enabled with Authorization on the provider. projects |= org.projects.all() projects |= cls._get_projects_for_sso_user(user, admin=True) if member: # Project Team Member member_teams = user.teams.filter(access=READ_ONLY_ACCESS) for team in member_teams: if not cls.has_sso_enabled(team.organization, SSOIntegration.PROVIDER_ALLAUTH): projects |= team.projects.all() projects |= cls._get_projects_for_sso_user(user, admin=False) return projects
Return all the projects the user has access to as ``admin`` or ``member``. If `RTD_ALLOW_ORGANIZATIONS` is enabled This function takes into consideration VCS SSO and Google SSO. It includes: - projects where the user has access to via VCS SSO. - Projects where the user has access via Team, if VCS SSO is not enabled for the organization of that team. .. note:: SSO is taken into consideration, but isn't implemented in .org yet. :param user: user object to filter projects :type user: django.contrib.admin.models.User :param bool admin: include projects where the user has admin access to the project :param bool member: include projects where the user has read access to the project
projects
python
readthedocs/readthedocs.org
readthedocs/core/permissions.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/permissions.py
MIT
def owners(cls, obj): """ Return the owners of `obj`. If organizations are enabled, we return the owners of the project organization instead. """ from readthedocs.organizations.models import Organization from readthedocs.projects.models import Project if isinstance(obj, Project): if settings.RTD_ALLOW_ORGANIZATIONS: obj = obj.organizations.first() else: return obj.users.all() if isinstance(obj, Organization): return obj.owners.all()
Return the owners of `obj`. If organizations are enabled, we return the owners of the project organization instead.
owners
python
readthedocs/readthedocs.org
readthedocs/core/permissions.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/permissions.py
MIT
def members(cls, obj, user=None): """ Return the users that are members of `obj`. If `user` is provided, we return the members of `obj` that are visible to `user`. For a project this means the users that have access to the project, and for an organization, this means the users that are on the same teams as `user`, including the organization owners. """ from readthedocs.organizations.models import Organization from readthedocs.organizations.models import Team from readthedocs.projects.models import Project if isinstance(obj, Project): project_owners = obj.users.all() if user and user not in project_owners: return User.objects.none() return project_owners if isinstance(obj, Organization): if user: teams = Team.objects.member(user, organization=obj) return User.objects.filter( Q(teams__in=teams) | Q(owner_organizations=obj), ).distinct() return User.objects.filter( Q(teams__organization=obj) | Q(owner_organizations=obj), ).distinct()
Return the users that are members of `obj`. If `user` is provided, we return the members of `obj` that are visible to `user`. For a project this means the users that have access to the project, and for an organization, this means the users that are on the same teams as `user`, including the organization owners.
members
python
readthedocs/readthedocs.org
readthedocs/core/permissions.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/permissions.py
MIT
def render_mail(self, template_prefix, email, context, headers=None): """ Wrapper around render_mail to send emails using a task. ``send_email`` makes use of the email object returned by this method, and calls ``send`` on it. We override this method to return a dummy object that has a ``send`` method, which in turn calls our task to send the email. """ email = super().render_mail(template_prefix, email, context, headers=headers) class DummyEmail: def __init__(self, email): self.email = email def send(self): send_email_from_object(self.email) return DummyEmail(email)
Wrapper around render_mail to send emails using a task. ``send_email`` makes use of the email object returned by this method, and calls ``send`` on it. We override this method to return a dummy object that has a ``send`` method, which in turn calls our task to send the email.
render_mail
python
readthedocs/readthedocs.org
readthedocs/core/adapters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/adapters.py
MIT
def save_user(self, request, user, form, commit=True): """Override default account signup to redeem invitations at sign-up.""" user = super().save_user(request, user, form) invitation_pk = request.session.get("invitation:pk") if invitation_pk: invitation = Invitation.objects.pending().filter(pk=invitation_pk).first() if invitation: log.info("Redeeming invitation at sign-up", invitation_pk=invitation_pk) invitation.redeem(user, request=request) invitation.delete() else: log.info("Invitation not found", invitation_pk=invitation_pk)
Override default account signup to redeem invitations at sign-up.
save_user
python
readthedocs/readthedocs.org
readthedocs/core/adapters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/adapters.py
MIT
def _filter_email_addresses(self, sociallogin): """ Remove all email addresses except the primary one. We don't want to populate all email addresses from the social account, it also makes it easy to mark only the primary email address as verified for providers that don't return information about email verification even if the email is verified (like GitLab). """ sociallogin.email_addresses = [ email for email in sociallogin.email_addresses if email.primary ]
Remove all email addresses except the primary one. We don't want to populate all email addresses from the social account, it also makes it easy to mark only the primary email address as verified for providers that don't return information about email verification even if the email is verified (like GitLab).
_filter_email_addresses
python
readthedocs/readthedocs.org
readthedocs/core/adapters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/adapters.py
MIT
def _connect_github_app_to_existing_github_account(self, request, sociallogin): """ Connect a GitHub App (new integration) account to an existing GitHub account (old integration). When a user signs up with the GitHub App we check if there is an existing GitHub account, and if it belongs to the same user, we connect the accounts instead of creating a new one. """ provider = sociallogin.account.get_provider() # If the provider is not GitHub App, nothing to do. if provider.id != GitHubAppProvider.id: return # If the user already signed up with the GitHub App, nothing to do. if sociallogin.is_existing: return social_account = SocialAccount.objects.filter( provider=GitHubProvider.id, uid=sociallogin.account.uid, ).first() # If there is an existing GH account, we check if that user can use the GH App, # otherwise we check for the current user. user_to_check = social_account.user if social_account else request.user if not self._can_use_github_app(user_to_check): raise ImmediateHttpResponse(HttpResponseRedirect(reverse("account_login"))) # If there isn't an existing GH account, nothing to do, # just let allauth create the new account. if not social_account: return # If the user is logged in, and the GH OAuth account belongs to # a different user, we should not connect the accounts, # this is the same as trying to connect an existing GH account to another user. if request.user.is_authenticated and request.user != social_account.user: message_template = "socialaccount/messages/account_connected_other.txt" get_account_adapter(request).add_message( request=request, level=messages.ERROR, message_template=message_template, ) url = reverse("socialaccount_connections") raise ImmediateHttpResponse(HttpResponseRedirect(url)) sociallogin.connect(request, social_account.user)
Connect a GitHub App (new integration) account to an existing GitHub account (old integration). When a user signs up with the GitHub App we check if there is an existing GitHub account, and if it belongs to the same user, we connect the accounts instead of creating a new one.
_connect_github_app_to_existing_github_account
python
readthedocs/readthedocs.org
readthedocs/core/adapters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/adapters.py
MIT
def _can_use_github_app(self, user): """ Check if the user can use the GitHub App. Only staff users can use the GitHub App for now. """ return user.is_staff
Check if the user can use the GitHub App. Only staff users can use the GitHub App for now.
_can_use_github_app
python
readthedocs/readthedocs.org
readthedocs/core/adapters.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/adapters.py
MIT
def set_change_reason(instance, reason): """ Set the change reason for the historical record created from the instance. This method should be called before calling ``save()`` or ``delete``. It sets `reason` to the `_change_reason` attribute of the instance, that's used to create the historical record on the save/delete signals. https://django-simple-history.readthedocs.io/en/latest/historical_model.html#change-reason # noqa """ instance._change_reason = reason
Set the change reason for the historical record created from the instance. This method should be called before calling ``save()`` or ``delete``. It sets `reason` to the `_change_reason` attribute of the instance, that's used to create the historical record on the save/delete signals. https://django-simple-history.readthedocs.io/en/latest/historical_model.html#change-reason # noqa
set_change_reason
python
readthedocs/readthedocs.org
readthedocs/core/history.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/history.py
MIT
def safe_update_change_reason(instance, reason): """ Wrapper around update_change_reason to catch exceptions. .. warning:: The implementation of django-simple-history's `update_change_reason` is very brittle, as it queries for a previous historical record that matches the attributes of the instance to update the ``change_reason``, which could end up updating the wrong record, or not finding it. If you already have control over the object, use `set_change_reason` before updating/deleting the object instead. That's more safe, since the attribute is passed to the signal and used at the creation time of the record. https://django-simple-history.readthedocs.io/en/latest/historical_model.html#change-reason # noqa """ try: update_change_reason(instance=instance, reason=reason) except Exception: log.exception( "An error occurred while updating the change reason of the instance.", instance=instance, )
Wrapper around update_change_reason to catch exceptions. .. warning:: The implementation of django-simple-history's `update_change_reason` is very brittle, as it queries for a previous historical record that matches the attributes of the instance to update the ``change_reason``, which could end up updating the wrong record, or not finding it. If you already have control over the object, use `set_change_reason` before updating/deleting the object instead. That's more safe, since the attribute is passed to the signal and used at the creation time of the record. https://django-simple-history.readthedocs.io/en/latest/historical_model.html#change-reason # noqa
safe_update_change_reason
python
readthedocs/readthedocs.org
readthedocs/core/history.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/history.py
MIT
def default_token(): """Generate default value for token field.""" return binascii.hexlify(os.urandom(20)).decode()
Generate default value for token field.
default_token
python
readthedocs/readthedocs.org
readthedocs/core/fields.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/fields.py
MIT
def send_email_task(recipient, subject, content, content_html=None, from_email=None, **kwargs): """ Send multipart email. recipient Email recipient address subject Email subject header content Plain text template to send content_html HTML content to send as new message part kwargs Additional options to the EmailMultiAlternatives option. """ msg = EmailMultiAlternatives( subject, content, from_email or settings.DEFAULT_FROM_EMAIL, [recipient], **kwargs ) if content_html: msg.attach_alternative(content_html, "text/html") log.info("Sending email to recipient.", recipient=recipient) msg.send()
Send multipart email. recipient Email recipient address subject Email subject header content Plain text template to send content_html HTML content to send as new message part kwargs Additional options to the EmailMultiAlternatives option.
send_email_task
python
readthedocs/readthedocs.org
readthedocs/core/tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/tasks.py
MIT
def cleanup_pidbox_keys(): """ Remove "pidbox" objects from Redis. Celery creates some "pidbox" objects with TTL=-1, producing a OOM on our Redis instance. This task is executed periodically to remove "pdibox" objects with an idletime bigger than 5 minutes from Redis and free some RAM. https://github.com/celery/celery/issues/6089 https://github.com/readthedocs/readthedocs-ops/issues/1260 """ client = redis.from_url(settings.BROKER_URL) keys = client.keys("*reply.celery.pidbox*") total_memory = 0 for key in keys: idletime = client.object("idletime", key) # seconds memory = math.ceil(client.memory_usage(key) / 1024 / 1024) # Mb total_memory += memory if idletime > (60 * 15): # 15 minutes client.delete(key) log.info("Redis pidbox objects.", memory=total_memory, keys=len(keys))
Remove "pidbox" objects from Redis. Celery creates some "pidbox" objects with TTL=-1, producing a OOM on our Redis instance. This task is executed periodically to remove "pdibox" objects with an idletime bigger than 5 minutes from Redis and free some RAM. https://github.com/celery/celery/issues/6089 https://github.com/readthedocs/readthedocs-ops/issues/1260
cleanup_pidbox_keys
python
readthedocs/readthedocs.org
readthedocs/core/tasks.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/tasks.py
MIT
def queryset(self, request, queryset): """ Add filters to queryset filter. ``PROJECT_ACTIVE`` and ``PROJECT_BUILT`` look for versions on projects, ``PROJECT_RECENT`` looks for projects with builds in the last year """ if self.value() == self.PROJECT_ACTIVE: return queryset.filter(projects__versions__active=True) if self.value() == self.PROJECT_BUILT: return queryset.filter(projects__versions__built=True) if self.value() == self.PROJECT_RECENT: recent_date = timezone.now() - timedelta(days=365) return queryset.filter(projects__builds__date__gt=recent_date)
Add filters to queryset filter. ``PROJECT_ACTIVE`` and ``PROJECT_BUILT`` look for versions on projects, ``PROJECT_RECENT`` looks for projects with builds in the last year
queryset
python
readthedocs/readthedocs.org
readthedocs/core/admin.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/admin.py
MIT
def base_resolve_path( self, filename, version_slug=None, language=None, versioning_scheme=None, project_relationship=None, custom_prefix=None, ): """ Build a path using the given fields. For example, if custom prefix is given, the path will be prefixed with it. In case of a subproject (project_relationship is given), the path will be prefixed with the subproject prefix (defaults to ``/projects/<subproject-slug>/``). Then we add the filename, version_slug and language to the path depending on the versioning scheme. """ path = "/" if project_relationship: path = unsafe_join_url_path(path, project_relationship.subproject_prefix) # If the project has a custom prefix, we use it. if custom_prefix: path = unsafe_join_url_path(path, custom_prefix) if versioning_scheme == SINGLE_VERSION_WITHOUT_TRANSLATIONS: path = unsafe_join_url_path(path, filename) elif versioning_scheme == MULTIPLE_VERSIONS_WITHOUT_TRANSLATIONS: path = unsafe_join_url_path(path, f"{version_slug}/{filename}") else: path = unsafe_join_url_path(path, f"{language}/{version_slug}/{filename}") return path
Build a path using the given fields. For example, if custom prefix is given, the path will be prefixed with it. In case of a subproject (project_relationship is given), the path will be prefixed with the subproject prefix (defaults to ``/projects/<subproject-slug>/``). Then we add the filename, version_slug and language to the path depending on the versioning scheme.
base_resolve_path
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def resolve_path( self, project, filename="", version_slug=None, language=None, ): """Resolve a URL with a subset of fields defined.""" version_slug = version_slug or project.get_default_version() language = language or project.language filename = self._fix_filename(filename) parent_project, project_relationship = self._get_canonical_project(project) # If the project is a subproject, we use the custom prefix and versioning scheme # of the child of the relationship, this is since the project # could be a translation. For a project that isn't a subproject, # we use the custom prefix and versioning scheme of the parent project. if project_relationship: custom_prefix = project_relationship.child.custom_prefix versioning_scheme = project_relationship.child.versioning_scheme else: custom_prefix = parent_project.custom_prefix versioning_scheme = parent_project.versioning_scheme return self.base_resolve_path( filename=filename, version_slug=version_slug, language=language, versioning_scheme=versioning_scheme, project_relationship=project_relationship, custom_prefix=custom_prefix, )
Resolve a URL with a subset of fields defined.
resolve_path
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def resolve_version(self, project, version=None, filename="/"): """ Get the URL for a specific version of a project. If no version is given, the default version is used. Use this instead of ``resolve`` if you have the version object already. """ if not version: default_version_slug = project.get_default_version() version = project.versions(manager=INTERNAL).get(slug=default_version_slug) domain, use_https = self._get_project_domain( project, external_version_slug=version.slug if version.is_external else None, ) path = self.resolve_path( project=project, filename=filename, version_slug=version.slug, language=project.language, ) protocol = "https" if use_https else "http" return urlunparse((protocol, domain, path, "", "", ""))
Get the URL for a specific version of a project. If no version is given, the default version is used. Use this instead of ``resolve`` if you have the version object already.
resolve_version
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def resolve_project(self, project, filename="/"): """ Get the URL for a project. This is the URL where the project is served from, it doesn't include the version or language. Useful to link to a known filename in the project. """ domain, use_https = self._get_project_domain(project) protocol = "https" if use_https else "http" return urlunparse((protocol, domain, filename, "", "", ""))
Get the URL for a project. This is the URL where the project is served from, it doesn't include the version or language. Useful to link to a known filename in the project.
resolve_project
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def _get_project_domain(self, project, external_version_slug=None, use_canonical_domain=True): """ Get the domain from where the documentation of ``project`` is served from. :param project: Project object :param bool use_canonical_domain: If `True` use its canonical custom domain if available. :returns: Tuple of ``(domain, use_https)``. Note that we are using ``lru_cache`` decorator on this function. This is useful when generating the flyout addons response since we call ``resolver.resolve`` multi times for the same ``Project``. This cache avoids hitting the DB to get the canonical custom domain over and over again. """ use_https = settings.PUBLIC_DOMAIN_USES_HTTPS canonical_project, _ = self._get_canonical_project(project) domain = self._get_project_subdomain(canonical_project) if external_version_slug: domain = self._get_external_subdomain(canonical_project, external_version_slug) elif use_canonical_domain and self._use_cname(canonical_project): domain_object = canonical_project.get_canonical_custom_domain() if domain_object: use_https = domain_object.https domain = domain_object.domain return domain, use_https
Get the domain from where the documentation of ``project`` is served from. :param project: Project object :param bool use_canonical_domain: If `True` use its canonical custom domain if available. :returns: Tuple of ``(domain, use_https)``. Note that we are using ``lru_cache`` decorator on this function. This is useful when generating the flyout addons response since we call ``resolver.resolve`` multi times for the same ``Project``. This cache avoids hitting the DB to get the canonical custom domain over and over again.
_get_project_domain
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def get_domain_without_protocol(self, project, use_canonical_domain=True): """ Get the domain from where the documentation of ``project`` is served from. This doesn't include the protocol. :param project: Project object :param bool use_canonical_domain: If `True` use its canonical custom domain if available. """ domain, _ = self._get_project_domain(project, use_canonical_domain=use_canonical_domain) return domain
Get the domain from where the documentation of ``project`` is served from. This doesn't include the protocol. :param project: Project object :param bool use_canonical_domain: If `True` use its canonical custom domain if available.
get_domain_without_protocol
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def resolve( self, project, filename="", query_params="", external=None, **kwargs, ): """ Resolve the URL of the project/version_slug/filename combination. :param project: Project to resolve. :param filename: exact filename the resulting URL should contain. :param query_params: query string params the resulting URL should contain. :param external: whether or not the resolved URL would be external (`*.readthedocs.build`). :param kwargs: extra attributes to be passed to ``resolve_path``. """ version_slug = kwargs.get("version_slug") if version_slug is None: version_slug = project.get_default_version() if external is None: external = self._is_external(project, version_slug) domain, use_https = self._get_project_domain( project, external_version_slug=version_slug if external else None, ) protocol = "https" if use_https else "http" path = self.resolve_path(project, filename=filename, **kwargs) return urlunparse((protocol, domain, path, "", query_params, ""))
Resolve the URL of the project/version_slug/filename combination. :param project: Project to resolve. :param filename: exact filename the resulting URL should contain. :param query_params: query string params the resulting URL should contain. :param external: whether or not the resolved URL would be external (`*.readthedocs.build`). :param kwargs: extra attributes to be passed to ``resolve_path``.
resolve
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def get_subproject_url_prefix(self, project, external_version_slug=None): """ Get the URL prefix from where the documentation of a subproject is served from. This doesn't include the version or language. For example: - https://docs.example.com/projects/<project-slug>/ This will respect the custom subproject prefix if it's defined. :param project: Project object to get the root URL from :param external_version_slug: If given, resolve using the external version domain. """ domain, use_https = self._get_project_domain( project, external_version_slug=external_version_slug ) protocol = "https" if use_https else "http" path = project.subproject_prefix return urlunparse((protocol, domain, path, "", "", ""))
Get the URL prefix from where the documentation of a subproject is served from. This doesn't include the version or language. For example: - https://docs.example.com/projects/<project-slug>/ This will respect the custom subproject prefix if it's defined. :param project: Project object to get the root URL from :param external_version_slug: If given, resolve using the external version domain.
get_subproject_url_prefix
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def _get_canonical_project(self, project): """ Get the parent project and subproject relationship from the canonical project of `project`. We don't support more than 2 levels of nesting subprojects and translations, This means, we can have the following cases: - The project isn't a translation or subproject We serve the documentation from the domain of the project itself (main.docs.com/). - The project is a translation of a project We serve the documentation from the domain of the main translation (main.docs.com/es/). - The project is a subproject of a project We serve the documentation from the domain of the super project (main.docs.com/projects/subproject/). - The project is a translation, and the main translation is a subproject of a project, like: - docs - api (subproject of ``docs``) - api-es (translation of ``api``, and current project to be served) We serve the documentation from the domain of the super project (docs.docs.com/projects/api/es/). - The project is a subproject, and the superproject is a translation of a project, like: - docs - docs-es (translation of ``docs``) - api-es (subproject of ``docs-es``, and current project to be served) We serve the documentation from the domain of the super project (the translation), this is docs-es.docs.com/projects/api-es/es/. We aren't going to support this case for now. In summary: If the project is a subproject, we don't care if the superproject is a translation, we always serve from the domain of the superproject. If the project is a translation, we need to check if the main translation is a subproject. """ parent_project = project main_language_project = parent_project.main_language_project if main_language_project: parent_project = main_language_project relationship = parent_project.parent_relationship if relationship: parent_project = relationship.parent return parent_project, relationship
Get the parent project and subproject relationship from the canonical project of `project`. We don't support more than 2 levels of nesting subprojects and translations, This means, we can have the following cases: - The project isn't a translation or subproject We serve the documentation from the domain of the project itself (main.docs.com/). - The project is a translation of a project We serve the documentation from the domain of the main translation (main.docs.com/es/). - The project is a subproject of a project We serve the documentation from the domain of the super project (main.docs.com/projects/subproject/). - The project is a translation, and the main translation is a subproject of a project, like: - docs - api (subproject of ``docs``) - api-es (translation of ``api``, and current project to be served) We serve the documentation from the domain of the super project (docs.docs.com/projects/api/es/). - The project is a subproject, and the superproject is a translation of a project, like: - docs - docs-es (translation of ``docs``) - api-es (subproject of ``docs-es``, and current project to be served) We serve the documentation from the domain of the super project (the translation), this is docs-es.docs.com/projects/api-es/es/. We aren't going to support this case for now. In summary: If the project is a subproject, we don't care if the superproject is a translation, we always serve from the domain of the superproject. If the project is a translation, we need to check if the main translation is a subproject.
_get_canonical_project
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT
def _get_external_subdomain(self, project, version_slug): """Determine domain for an external version.""" subdomain_slug = project.slug.replace("_", "-") # Version slug is in the domain so we can properly serve single-version projects # and have them resolve the proper version from the PR. return f"{subdomain_slug}--{version_slug}.{settings.RTD_EXTERNAL_VERSION_DOMAIN}"
Determine domain for an external version.
_get_external_subdomain
python
readthedocs/readthedocs.org
readthedocs/core/resolver.py
https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/core/resolver.py
MIT