Coverage for downtify/buy_links.py: 100%

54 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Where to buy a song, an album or an artist's music. 

2 

3Downtify downloads from YouTube; someone who likes what they found may 

4want to pay for it, so the artist is supported directly. For a song (or 

5an album, or an artist) this lists, in order: 

6 

7* the **iTunes Store** item itself, with its price, in the listener's 

8 store - looked up with the public iTunes Search API (see 

9 :func:`downtify.itunes.store_match`); when nothing there clearly is it, 

10 a search on Apple Music instead; 

11* a search on **Bandcamp**, where most of the money goes to the artist, 

12 and on **Qobuz**, which sells lossless downloads - neither has a public 

13 lookup, so a search is the honest link; 

14* the artist's own **website**, when their saved profile has one (see 

15 :mod:`downtify.artist_profile`). 

16 

17Nothing is bought, opened or tracked here: these are plain links, and the 

18only request made is the iTunes lookup. 

19""" 

20 

21from __future__ import annotations 

22 

23import re 

24from typing import Any, Callable, Optional 

25from urllib.parse import quote, quote_plus 

26 

27from loguru import logger 

28 

29from . import itunes 

30 

31KIND_TRACK = 'track' 

32KIND_ALBUM = 'album' 

33KIND_ARTIST = 'artist' 

34 

35DEFAULT_COUNTRY = 'US' 

36_COUNTRY = re.compile(r'^[A-Za-z]{2}$') 

37 

38# What each store calls the kind of item in its search. 

39_BANDCAMP_TYPES = {KIND_TRACK: 't', KIND_ALBUM: 'a', KIND_ARTIST: 'b'} 

40_QOBUZ_TYPES = { 

41 KIND_TRACK: 'tracks', 

42 KIND_ALBUM: 'albums', 

43 KIND_ARTIST: 'artists', 

44} 

45 

46StoreLookup = Callable[..., Optional[dict[str, Any]]] 

47 

48 

49def normalize_country(value: Any) -> str: 

50 """A two-letter store country, upper-case; the US store otherwise.""" 

51 

52 text = str(value or '').strip() 

53 return text.upper() if _COUNTRY.fullmatch(text) else DEFAULT_COUNTRY 

54 

55 

56def website_url(raw: Any) -> str: 

57 """An artist's website as a link: http(s) as it is, a bare domain made 

58 https, anything else (another scheme, nothing) ``''``.""" 

59 

60 text = str(raw or '').strip() 

61 if not text or any(ch.isspace() for ch in text): 

62 return '' 

63 if re.match(r'^https?://', text, re.IGNORECASE): 

64 return text 

65 if re.match(r'^[a-z][a-z0-9+.-]*:', text, re.IGNORECASE): 

66 return '' 

67 return f'https://{text}' 

68 

69 

70def kind_of(title: str, album: str) -> str: 

71 """What is being bought: a song when there is a title, else an album 

72 when there is one, else everything by the artist.""" 

73 

74 if title: 

75 return KIND_TRACK 

76 return KIND_ALBUM if album else KIND_ARTIST 

77 

78 

79def buy_links( 

80 artist: str, 

81 title: str = '', 

82 album: str = '', 

83 *, 

84 country: str = DEFAULT_COUNTRY, 

85 website: str = '', 

86 lookup: StoreLookup = itunes.store_match, 

87) -> dict[str, Any]: 

88 """``{kind, query, links}`` for a song, album or artist - each link 

89 ``{store, label, url, match, price, currency}``. ``match`` says the 

90 link opens the item itself (``False``: a search for it); ``price`` is 

91 set only on an iTunes Store item sold on its own.""" 

92 

93 artist = str(artist or '').strip() 

94 title = str(title or '').strip() 

95 album = str(album or '').strip() 

96 kind = kind_of(title, album) 

97 country = normalize_country(country) 

98 query = ' '.join( 

99 part 

100 for part in (artist, {KIND_TRACK: title, KIND_ALBUM: album}.get(kind)) 

101 if part 

102 ) 

103 links = [ 

104 _itunes_link(kind, artist, title, album, country, query, lookup), 

105 _link( 

106 'bandcamp', 

107 'Bandcamp', 

108 'https://bandcamp.com/search?q=' 

109 f'{quote_plus(query)}&item_type={_BANDCAMP_TYPES[kind]}', 

110 ), 

111 _link( 

112 'qobuz', 

113 'Qobuz', 

114 'https://www.qobuz.com/us-en/search/' 

115 f'{_QOBUZ_TYPES[kind]}/{quote(query, safe="")}', 

116 ), 

117 ] 

118 site = website_url(website) 

119 if site: 

120 links.append(_link('website', 'Official website', site, match=True)) 

121 return {'kind': kind, 'query': query, 'links': links} 

122 

123 

124def _link( 

125 store: str, 

126 label: str, 

127 url: str, 

128 *, 

129 match: bool = False, 

130 price: Optional[float] = None, 

131 currency: str = '', 

132) -> dict[str, Any]: 

133 return { 

134 'store': store, 

135 'label': label, 

136 'url': url, 

137 'match': match, 

138 'price': price, 

139 'currency': currency, 

140 } 

141 

142 

143def _itunes_link( 

144 kind: str, 

145 artist: str, 

146 title: str, 

147 album: str, 

148 country: str, 

149 query: str, 

150 lookup: StoreLookup, 

151) -> dict[str, Any]: 

152 found = None 

153 if artist: 

154 try: 

155 found = lookup(kind, artist, title, album, country) 

156 except Exception: 

157 logger.opt(exception=True).debug( 

158 'iTunes Store lookup failed for {!r}', query 

159 ) 

160 if found: 

161 return _link( 

162 'itunes', 

163 'iTunes Store', 

164 found['url'], 

165 match=True, 

166 price=found.get('price'), 

167 currency=str(found.get('currency') or ''), 

168 ) 

169 return _link( 

170 'itunes', 

171 'iTunes Store', 

172 f'https://music.apple.com/{country.lower()}/search?term=' 

173 f'{quote_plus(query)}', 

174 )