import requests import logging from urllib.parse import urlparse, parse_qs, urlencode def expand_short_url(short_url): """ Expand short URLs (like amzn.to) to their full URLs """ try: # Follow redirects to get the final URL response = requests.get(short_url, allow_redirects=True, timeout=10) final_url = response.url logging.info(f"Expanded URL: {short_url} -> {final_url}") return final_url except Exception as e: logging.error(f"Error expanding URL {short_url}: {str(e)}") return short_url # Return original URL if expansion fails def add_affiliate_tag_to_amazon_url(url, affiliate_tag='anrdcomm-21'): """ Add or replace affiliate tag in Amazon URLs """ try: parsed_url = urlparse(url) # Check if it's an Amazon URL if 'amazon' in parsed_url.netloc: query_params = parse_qs(parsed_url.query) # Check if our tag is already present existing_tag = query_params.get('tag', []) if existing_tag and existing_tag[0] == affiliate_tag: logging.info(f"Affiliate tag '{affiliate_tag}' already present, no change needed") return url # Remove existing tag if present and different if 'tag' in query_params and existing_tag[0] != affiliate_tag: logging.info(f"Removing existing tag: {query_params['tag']}") # Add our affiliate tag query_params['tag'] = [affiliate_tag] # Rebuild the URL with the new query parameters new_query = urlencode(query_params, doseq=True) affiliate_url = parsed_url._replace(query=new_query).geturl() logging.info(f"Added affiliate tag '{affiliate_tag}' to Amazon URL") return affiliate_url # Return original URL if not Amazon return url except Exception as e: logging.error(f"Error adding affiliate tag to URL {url}: {str(e)}") return url def is_amazon_short_link(url): """ Check if the URL is an Amazon short link (amzn.to) """ parsed_url = urlparse(url) return 'amzn.to' in parsed_url.netloc def is_flipkart_short_link(url): """ Check if the URL is a Flipkart short link (fkrt.it) """ parsed_url = urlparse(url) return 'fkrt.it' in parsed_url.netloc def is_amazon_url(url): """ Check if the URL is an Amazon URL """ parsed_url = urlparse(url) return 'amazon' in parsed_url.netloc def expand_ecommerce_url(url, add_affiliate_tag=True, affiliate_tag='anrdcomm-21'): """ Expand e-commerce short URLs and optionally add affiliate tags """ expanded_url = url # Expand short URLs if is_amazon_short_link(url) or is_flipkart_short_link(url): expanded_url = expand_short_url(url) # Add affiliate tag to Amazon URLs if requested if add_affiliate_tag and is_amazon_url(expanded_url): expanded_url = add_affiliate_tag_to_amazon_url(expanded_url, affiliate_tag) return expanded_url