chube_youtube.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import asyncio
  2. import os
  3. import aiohttp
  4. from chube_enums import Message
  5. from chube_ws import Resolver, make_message, make_message_from_json_string
  6. API_KEY = os.environ.get('GOOGLE_SEARCH_API_KEY')
  7. SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
  8. SEARCH_PARAM = [('part', 'snippet'), ('type', 'video,playlist'), ('safeSearch', 'none'),
  9. ('key', API_KEY)]
  10. ID_SEARCH_URL = "https://www.googleapis.com/youtube/v3/videos"
  11. ID_SEARCH_PARAM = [('part', 'snippet'), ('key', API_KEY)]
  12. GET_PLAYLIST_URL = "https://www.googleapis.com/youtube/v3/playlists"
  13. GET_PLAYLIST_COUNT_PARAM = [('part', 'contentDetails'), ('key', API_KEY)]
  14. GET_PLAYLIST_ITEMS_URL = "https://www.googleapis.com/youtube/v3/playlistItems"
  15. GET_PLAYLIST_ITEMS_PARAM = [('part', 'snippet'),('maxResults', '1'), ('key', API_KEY)]
  16. async def search_processor(ws, data, path):
  17. async with aiohttp.ClientSession() as session:
  18. async with session.get(SEARCH_URL, params=SEARCH_PARAM + [('q', data['q'])]) as response:
  19. data = await response.content.read(-1)
  20. await ws.send(make_message_from_json_string(Message.SEARCH, data.decode(response.get_encoding())))
  21. async def search_id_processor(ws, data, path):
  22. ids = data["id"]
  23. if not isinstance(ids, list):
  24. ids = {ids}
  25. else:
  26. ids = set(ids)
  27. async with aiohttp.ClientSession() as session:
  28. async with session.get(ID_SEARCH_URL, params=ID_SEARCH_PARAM + [('id', ",".join(ids))]) as response:
  29. data = await response.content.read(-1)
  30. await ws.send(make_message_from_json_string(Message.SEARCH_ID, data.decode(response.get_encoding())))
  31. async def get_all_playlist_items(playlistId):
  32. async with aiohttp.ClientSession() as session:
  33. async with session.get(GET_PLAYLIST_URL, params=GET_PLAYLIST_COUNT_PARAM + [('id', playlistId)]) as count_response:
  34. json_data = await count_response.json()
  35. item_count = json_data['items'][0]['contentDetails']['itemCount']
  36. items_params = GET_PLAYLIST_ITEMS_PARAM + [('playlistId', playlistId), ('maxResults', item_count)]
  37. async with session.get(GET_PLAYLIST_ITEMS_URL, params=items_params) as items_response:
  38. return await items_response.json()
  39. def make_resolver():
  40. resolver = Resolver()
  41. resolver.register(Message.SEARCH, search_processor)
  42. resolver.register(Message.SEARCH_ID, search_id_processor)
  43. return resolver
  44. if __name__ == "__main__":
  45. async def foo():
  46. async with aiohttp.ClientSession() as session:
  47. async with session.get(SEARCH_URL, params=SEARCH_PARAM + [('q', "She")]) as response:
  48. json_data = await response.json()
  49. print(json_data)
  50. loop = asyncio.get_event_loop()
  51. loop.run_until_complete(foo())