9gag.py 2.3 KB

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