9gag.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=invalid-name
  3. """9GAG (social media)"""
  4. from json import loads
  5. from datetime import datetime
  6. from urllib.parse import urlencode
  7. about = {
  8. "website": 'https://9gag.com/',
  9. "wikidata_id": 'Q277421',
  10. "official_api_documentation": None,
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'JSON',
  14. }
  15. categories = ['social media']
  16. paging = True
  17. search_url = "https://9gag.com/v1/search-posts?{query}"
  18. page_size = 10
  19. def request(query, params):
  20. query = urlencode({'query': query, 'c': (params['pageno'] - 1) * page_size})
  21. params['url'] = search_url.format(query=query)
  22. return params
  23. def response(resp):
  24. results = []
  25. json_results = loads(resp.text)['data']
  26. for result in json_results['posts']:
  27. result_type = result['type']
  28. # Get the not cropped version of the thumbnail when the image height is not too important
  29. if result['images']['image700']['height'] > 400:
  30. thumbnail = result['images']['imageFbThumbnail']['url']
  31. else:
  32. thumbnail = result['images']['image700']['url']
  33. if result_type == 'Photo':
  34. results.append(
  35. {
  36. 'template': 'images.html',
  37. 'url': result['url'],
  38. 'title': result['title'],
  39. 'content': result['description'],
  40. 'publishedDate': datetime.utcfromtimestamp(result['creationTs']),
  41. 'img_src': result['images']['image700']['url'],
  42. 'thumbnail_src': thumbnail,
  43. }
  44. )
  45. elif result_type == 'Animated':
  46. results.append(
  47. {
  48. 'template': 'videos.html',
  49. 'url': result['url'],
  50. 'title': result['title'],
  51. 'content': result['description'],
  52. 'publishedDate': datetime.utcfromtimestamp(result['creationTs']),
  53. 'thumbnail': thumbnail,
  54. 'iframe_src': result['images'].get('image460sv', {}).get('url'),
  55. }
  56. )
  57. if 'tags' in json_results:
  58. for suggestion in json_results['tags']:
  59. results.append({'suggestion': suggestion['key']})
  60. return results