cli.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import json
  2. import os
  3. import click
  4. import requests
  5. from decouple import config
  6. from rich import print
  7. from rich.console import Console
  8. from rich.table import Table
  9. console = Console()
  10. print("Welcome to the CLI Tool of [bold blue]MediaCMS![/bold blue]", ":thumbs_up:")
  11. BASE_URL = 'https://demo.mediacms.io/api/v1'
  12. AUTH_KEY = ''
  13. USERNAME = ''
  14. EMAIL = ''
  15. def set_envs():
  16. with open('.env', 'r') as file:
  17. if not file.read(1):
  18. print("Use the Login command to set your credential environment variables")
  19. else:
  20. global AUTH_KEY, USERNAME, EMAIL
  21. AUTH_KEY = config('AUTH_KEY')
  22. USERNAME = config('USERNAME')
  23. EMAIL = config('EMAIL')
  24. set_envs()
  25. @click.group()
  26. def apis():
  27. """A CLI wrapper for the MediaCMS API endpoints."""
  28. @apis.command()
  29. def login():
  30. """Login to your account."""
  31. email = input('Enter your email address: ')
  32. password = input('Enter your password: ')
  33. data = {
  34. "email": f"{email}",
  35. "password": f"{password}",
  36. }
  37. response = requests.post(url=f'{BASE_URL}/login', data=data)
  38. if response.status_code == 200:
  39. username = json.loads(response.text)["username"]
  40. with open(".env", "w") as file:
  41. file.writelines(f'AUTH_KEY={json.loads(response.text)["token"]}\n')
  42. file.writelines(f'EMAIL={json.loads(response.text)["email"]}\n')
  43. file.writelines(f'USERNAME={json.loads(response.text)["username"]}\n')
  44. print(f"Welcome to MediaCMS [bold blue]{username}[/bold blue]. Your auth creds have been suceesfully stored in the .env file", ":v:")
  45. else:
  46. print(f'Error: {"non_field_errors": ["User not found."]}')
  47. @apis.command()
  48. def upload_media():
  49. """Upload media to the server"""
  50. headers = {'authorization': f'Token {AUTH_KEY}'}
  51. path = input('Enter the location of the file or directory where multiple files are present: ')
  52. if os.path.isdir(path):
  53. for filename in os.listdir(path):
  54. files = {}
  55. abs = os.path.abspath(f"{path}/{filename}")
  56. files['media_file'] = open(f'{abs}', 'rb')
  57. response = requests.post(url=f'{BASE_URL}/media', headers=headers, files=files)
  58. if response.status_code == 201:
  59. print(f"[bold blue]{filename}[/bold blue] successfully uploaded!")
  60. else:
  61. print(f'Error: {response.text}')
  62. else:
  63. files = {}
  64. files['media_file'] = open(f'{os.path.abspath(path)}', 'rb')
  65. response = requests.post(url=f'{BASE_URL}/media', headers=headers, files=files)
  66. if response.status_code == 201:
  67. print(f"[bold blue]{filename}[/bold blue] successfully uploaded!")
  68. else:
  69. print(f'Error: {response.text}')
  70. @apis.command()
  71. def my_media():
  72. """List all my media"""
  73. headers = {'authorization': f'Token {AUTH_KEY}'}
  74. response = requests.get(url=f'{BASE_URL}/media?author={USERNAME}', headers=headers)
  75. if response.status_code == 200:
  76. data_json = json.loads(response.text)
  77. table = Table(show_header=True, header_style="bold magenta")
  78. table.add_column("Name of the media")
  79. table.add_column("Media Type")
  80. table.add_column("State")
  81. for data in data_json['results']:
  82. table.add_row(data['title'], data['media_type'], data['state'])
  83. console.print(table)
  84. else:
  85. print(f'Could not get the media: {response.text}')
  86. @apis.command()
  87. def whoami():
  88. """Shows the details of the authorized user"""
  89. headers = {'authorization': f'Token {AUTH_KEY}'}
  90. response = requests.get(url=f'{BASE_URL}/whoami', headers=headers)
  91. for data, value in json.loads(response.text).items():
  92. print(data, ' : ', value)
  93. @apis.command()
  94. def categories():
  95. """List all categories."""
  96. response = requests.get(url=f'{BASE_URL}/categories')
  97. if response.status_code == 200:
  98. data_json = json.loads(response.text)
  99. table = Table(show_header=True, header_style="bold magenta")
  100. table.add_column("Category")
  101. table.add_column("Description")
  102. for data in data_json:
  103. table.add_row(data['title'], data['description'])
  104. console.print(table)
  105. else:
  106. print(f'Could not get the categories: {response.text}')
  107. @apis.command()
  108. def encodings():
  109. """List all encoding profiles"""
  110. response = requests.get(url=f'{BASE_URL}/encode_profiles/')
  111. if response.status_code == 200:
  112. data_json = json.loads(response.text)
  113. table = Table(show_header=True, header_style="bold magenta")
  114. table.add_column("Name")
  115. table.add_column("Extension")
  116. table.add_column("Resolution")
  117. table.add_column("Codec")
  118. table.add_column("Description")
  119. for data in data_json:
  120. table.add_row(data['name'], data['extension'], str(data['resolution']), data['codec'], data['description'])
  121. console.print(table)
  122. else:
  123. print(f'Could not get the encodings: {response.text}')
  124. if __name__ == '__main__':
  125. apis()