tootfinder.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Tootfinder (social media)
  3. """
  4. from datetime import datetime
  5. from json import loads
  6. from searx.utils import html_to_text
  7. about = {
  8. 'website': "https://www.tootfinder.ch",
  9. 'official_api_documentation': "https://wiki.tootfinder.ch/index.php?name=the-tootfinder-rest-api",
  10. 'use_official_api': True,
  11. 'require_api_key': False,
  12. 'results': "JSON",
  13. }
  14. categories = ['social media']
  15. base_url = "https://www.tootfinder.ch"
  16. def request(query, params):
  17. params['url'] = f"{base_url}/rest/api/search/{query}"
  18. return params
  19. def response(resp):
  20. results = []
  21. # the API of tootfinder has an issue that errors on server side are appended to the API response as HTML
  22. # thus we're only looking for the line that contains the actual json data and ignore everything else
  23. json_str = ""
  24. for line in resp.text.split("\n"):
  25. if line.startswith("[{"):
  26. json_str = line
  27. break
  28. for result in loads(json_str):
  29. thumbnail = None
  30. attachments = result.get('media_attachments', [])
  31. images = [attachment['preview_url'] for attachment in attachments if attachment['type'] == 'image']
  32. if len(images) > 0:
  33. thumbnail = images[0]
  34. title = result.get('card', {}).get('title')
  35. if not title:
  36. title = html_to_text(result['content'])[:75]
  37. results.append(
  38. {
  39. 'url': result['url'],
  40. 'title': title,
  41. 'content': html_to_text(result['content']),
  42. 'thumbnail': thumbnail,
  43. 'publishedDate': datetime.strptime(result['created_at'], '%Y-%m-%d %H:%M:%S'),
  44. }
  45. )
  46. return results