lib/awesome-privacy-readme-gen.py

294 lines · 11780 bytes

  1"""
  2Reads app list from awesome-privacy.yml,
  3formats into markdown, and inserts into README.md
  4"""
  5
  6import os
  7import re
  8import yaml
  9import logging
 10from urllib.parse import urlparse, quote
 11
 12# Configure Logging
 13LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
 14logging.basicConfig(level=LOG_LEVEL)
 15logger = logging.getLogger(__name__)
 16
 17# Determine the project root based on the script's location
 18project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 19app_list_file_path = os.path.join(project_root, 'awesome-privacy.yml')
 20readme_path = os.path.join(project_root, '.github/README.md')
 21icon_size=16
 22
 23# Read the main YAML file, where all data lives
 24logger.info("Reading the awesome-privacy file...")
 25with open(app_list_file_path, 'r') as file:
 26    data = yaml.safe_load(file)
 27
 28def iconElement(serviceUrl, serviceIcon):
 29  path = serviceIcon or f"https://icon.horse/icon/{urlparse(serviceUrl).netloc}"
 30  return f"<img src='{path}' width='{icon_size}' height='{icon_size}' alt='icon' />"
 31
 32def repoElement(repoUrl):
 33    if not repoUrl:
 34        return ""
 35    return (
 36        f"[![GitHub: {repoUrl}](https://img.shields.io/github/stars/{repoUrl}"
 37        f"?style=flat&logo=github&label={repoUrl.split('/')[1]}"
 38        "&color=%235f53f4&cacheSeconds=3600)]"
 39        f"(https://github.com/{repoUrl})"
 40    )
 41
 42def tosElement(tosdrId):
 43    if not tosdrId:
 44        return ""
 45    return f"[![Privacy Policy](https://shields.tosdr.org/en_{tosdrId}.svg)](https://tosdr.org/en/service/{tosdrId})"
 46
 47def statsElement(app, categoryName, sectionName):
 48    statsStr = ""
 49    if app.get('openSource') == True:
 50        github = app.get('github')
 51        if github:
 52            link = f"https://github.com/{github}"
 53        elif app.get('url'):
 54            link = app.get('url')
 55        else:
 56            link = f"https://awesome-privacy.xyz/{slugify(categoryName)}/{slugify(sectionName)}/{slugify(app.get('name'))}"
 57        statsStr += (
 58            f"[![Open Source](https://img.shields.io/badge/-Open_Source-3DA639"
 59            f"?style=flat&logo=opensourceinitiative&logoColor=white)]({link}) "
 60        )
 61    if app.get('securityAudited') == True:
 62        statsStr += (
 63            "![Security Audited](https://img.shields.io/badge/-Security_Audited-3DA639"
 64            "?style=flat&logo=data:image/svg+xml;base64,"
 65            "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0xMiAxTDMgNXY2YzAgNS41NSAzLjg0IDEwLjc0IDkgMTIgNS4xNi0xLjI2IDktNi40NSA5LTEyVjVsLTktNHoiLz48L3N2Zz4="
 66            "&logoColor=white) "
 67        )
 68    if app.get('acceptsCrypto') == True:
 69        statsStr += (
 70            "![Accepts Anonymous Payment](https://img.shields.io/badge/-Anon_Payment_Accepted"
 71            "%EF%B8%8F-3DA639?style=flat&logo=bitcoincash&logoColor=white) "
 72        )
 73    return statsStr
 74
 75def slugify(title):
 76    if not title:
 77        return ''
 78    title = title.lower()
 79    title = re.sub(r'\s+', '-', title)
 80    title = re.sub(r'\+|&', 'and', title)
 81    title = title.replace('?', '')
 82    return title
 83
 84def shieldsEncode(text):
 85    if not text: return ''
 86    text = text.strip().replace('-', '--').replace('_', '__').replace(' ', '_')
 87    return quote(text, safe='_-.')
 88
 89def awesomePrivacyReport(categoryName, sectionName, serviceName):
 90  if not serviceName:
 91      return ""
 92  return (
 93      f"[![{serviceName} on Awesome Privacy]"
 94      f"(https://img.shields.io/badge/View%20Report-FC60A8?style=flat&logo=awesomelists&label={serviceName.replace(' ', '_')})]"
 95      f"(https://awesome-privacy.xyz/{slugify(categoryName)}/{slugify(sectionName)}/{slugify(serviceName)})"
 96  )
 97
 98def playStoreBadge(name, androidApp):
 99    if not androidApp: return ""
100    encoded = shieldsEncode(name)
101    return (
102        f"[![{name} on Google Play](https://img.shields.io/badge/-{encoded}-3bd47f"
103        f"?style=flat&logo=android&logoColor=white)]"
104        f"(https://play.google.com/store/apps/details?id={androidApp}) "
105    )
106
107def appStoreBadge(name, iosApp):
108    if not iosApp: return ""
109    encoded = shieldsEncode(name)
110    return (
111        f"[![{name} on App Store](https://img.shields.io/badge/-{encoded}-0D96F6"
112        f"?style=flat&logo=appstore&logoColor=white)]"
113        f"({iosApp}) "
114    )
115
116def redditBadge(subreddit):
117    if not subreddit or not subreddit.strip(): return ""
118    sub = subreddit.strip()
119    return (
120        f"[![r/{sub} on Reddit](https://img.shields.io/badge/-{sub}-FF4500"
121        f"?style=flat&logo=reddit&logoColor=white)]"
122        f"(https://reddit.com/r/{sub}) "
123    )
124
125def discordBadge(name, discordInvite):
126    if not discordInvite or not discordInvite.strip(): return ""
127    invite = discordInvite.strip()
128    encoded = shieldsEncode(name)
129    link = invite if invite.startswith('https://') else f"https://discord.gg/{invite}"
130    return (
131        f"[![{name} on Discord](https://img.shields.io/badge/-{encoded}-5865F2"
132        f"?style=flat&logo=discord&logoColor=white)]"
133        f"({link}) "
134    )
135
136_MD_PATTERNS = [
137    re.compile(r'\[([^\]]*)\]\([^)]*\)'),    # [text](url) — group 1 = visible text
138    re.compile(r'\*\*(.+?)\*\*'),             # **bold**
139    re.compile(r'`([^`]+)`'),                 # `code`
140    re.compile(r'(?<!\*)\*([^*]+)\*(?!\*)'),  # *italic*
141]
142
143def truncateMarkdown(text, maxLen=200):
144    """Returns (truncated_text, was_truncated) preserving markdown constructs."""
145    if len(text) <= maxLen:
146        return text, False
147
148    result = []
149    visible = 0
150    i = 0
151
152    while i < len(text) and visible < maxLen:
153        for pattern in _MD_PATTERNS:
154            m = pattern.match(text, i)
155            if m:
156                result.append(m.group(0))
157                visible += len(m.group(1))
158                i = m.end()
159                break
160        else:
161            result.append(text[i])
162            visible += 1
163            i += 1
164
165    return ''.join(result).rstrip(), True
166
167def makeHref(text):
168    if not text: return "#"
169    return re.sub(r'[^\w\s-]', '', text.lower()).replace(" ", "-")
170
171def makeContents():
172    contents = "<blockquote><details open>\n"
173    contents += "<summary>📋 <b>Contents</b></summary>\n"
174
175    for category in data.get('categories'):
176        contents += f"\n- **{category.get('name')}**"
177        for section in category.get('sections'):
178            if (len(section.get('services') or []) > 0):
179                contents += (
180                    f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
181                    f"({len(section.get('services') or [])})"
182            )
183    contents += "\n</details></blockquote>\n\n"
184    return contents
185
186def makeAwesomePrivacy():
187  markdown = ""
188  for category in data.get('categories'):
189      markdown += f"## {category.get('name')}\n\n"
190      for section in category.get('sections'):
191          markdown += f"### {section.get('name')}\n\n"
192          # Add intro
193          if section.get('intro'):
194            markdown += f"{section.get('intro')}\n"
195          # No services yet
196          if not section.get('services') or len(section.get('services')) == 0:
197            markdown += (
198              "<p  align=\"center\">"
199              "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
200              "<i>Check back soon, or help us complete it by submitting a pull request</i>"
201              "</p>"
202            )
203          # For each service, list it's name, icon, url, and description
204          for app in section.get('services') or []:
205              description, was_truncated = truncateMarkdown(' '.join(app.get('description', '').split()))
206              ap_link = (
207                  f"https://awesome-privacy.xyz/"
208                  f"{slugify(category.get('name'))}/{slugify(section.get('name'))}/{slugify(app.get('name'))}"
209              )
210              ellipsis = f"[…]({ap_link} \"View full {app.get('name')} report\")" if was_truncated else ""
211              markdown += (
212                  f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
213                  f"({app.get('url')})** - {description}{ellipsis} \n"
214              )
215              badges = ' '.join(filter(None, [
216                  repoElement(app.get('github')),
217                  tosElement(app.get('tosdrId')),
218                  awesomePrivacyReport(category.get('name'), section.get('name'), app.get('name')),
219                  statsElement(app, category.get('name'), section.get('name')).rstrip(),
220                  playStoreBadge(app.get('name'), app.get('androidApp')).rstrip(),
221                  appStoreBadge(app.get('name'), app.get('iosApp')).rstrip(),
222                  redditBadge(app.get('subreddit')).rstrip(),
223                  discordBadge(app.get('name'), app.get('discordInvite')).rstrip(),
224              ]))
225              if badges:
226                  markdown += (
227                      f"\t- <details>\n\t\t<summary>Stats</summary>\n\n\t\t"
228                      f"{badges}ㅤ \n"
229                      f"\n\t\t</details>\n"
230                  )
231          markdown += "\n"
232          # If word of warning exists, append it
233          if section.get('wordOfWarning'):
234            markdown += "<details>\n<summary>⚠️ <b>Word of Warning</b></summary>\n\n"
235            markdown += f"> {section.get('wordOfWarning')}\n\n"
236            markdown += "</details>\n\n"
237          # If notable mentions exists, append it (either as a list or a single string)
238          if section.get('notableMentions'):
239            markdown += "<details>\n<summary>✳️ <b>Notable Mentions</b></summary>\n\n"
240            if isinstance(section.get('notableMentions'), list):
241              for mention in section.get('notableMentions'):
242                markdown += f"> - [{mention.get('name')}]({mention.get('url')})" + (
243                  f" - {mention.get('description')}" if mention.get('description') else "\n"
244              )
245            else:
246              notable_mentions = section.get('notableMentions').replace('\n', '\n> ')
247              markdown += f"> {notable_mentions}"
248
249            markdown += "</details>\n\n"
250          # If further info exists, append it
251          if section.get('furtherInfo'):
252            markdown += "<details>\n<summary>ℹ️ <b>Further Info</b></summary>\n\n"
253            markdown += f"> {section.get('furtherInfo')}"
254            markdown += "</details>\n\n"
255          markdown += "<p align=\"right\"><sup><a href=\"#top\">⬆️ [Back to Top]</a></sub></p>\n"
256          markdown += "\n---\n\n"
257  return markdown
258
259awesome_privacy_results = makeContents() + makeAwesomePrivacy()
260
261# Update the README.md between markers
262logger.info("Reading README.md file...")
263with open(readme_path, 'r') as file:
264    readme_content = file.read()
265
266def update_content_between_markers(content, start_marker, end_marker, new_content):
267    logger.info(f"Updating content between {start_marker} and {end_marker} markers...")
268    start_index = content.find(start_marker)
269    end_index = content.find(end_marker)
270
271    if start_index != -1 and end_index != -1:
272        before_section = content[:start_index + len(start_marker)]
273        after_section = content[end_index:]
274        updated_content = before_section + '\n' + new_content + after_section
275        return updated_content
276    else:
277        logger.error(f"Markers {start_marker} and {end_marker} not found.")
278        return content
279
280# Update guides and resources in README.md
281readme_content = update_content_between_markers(
282  readme_content,
283  "<!-- awesome-privacy-start -->",
284  "<!-- awesome-privacy-end -->",
285  awesome_privacy_results
286)
287
288# Write back the updated content to README.md
289logger.info("Writing back to README.md...")
290with open(readme_path, 'w') as file:
291    file.write(readme_content)
292
293# All done. Time to go home for tea and medals.
294logger.info("Script completed successfully!")