Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLI API Tool #273

Merged
merged 14 commits into from
Jan 31, 2022
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
cli-tool/.env
frontend/package-lock.json
media_files/encoded/
media_files/original/
media_files/hls/
Expand All @@ -14,4 +16,4 @@ static/mptt/
static/rest_framework/
static/drf-yasg
cms/local_settings.py
deploy/docker/local_settings.py
deploy/docker/local_settings.py
10 changes: 10 additions & 0 deletions cli-tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## MediaCMS CLI Tool
This is the CLI tool to interact with the API of your installation/instance of MediaCMS.

### How to configure and use the tools
- Make sure that you have all the required installations (`requirements.txt`)installed. To install it -
shubhank-saxena marked this conversation as resolved.
Show resolved Hide resolved
- Create a new virtualenv using any python virtualenv manager.
- Then activate the virtualenv and enter `pip -r requirements.txt`.
shubhank-saxena marked this conversation as resolved.
Show resolved Hide resolved
- Create an .env file in this folder (`mediacms/cli-tool/`)
- Run the cli tool using the command `python cli.py login`. This will authenticate you and store necessary creds for further authentications.
- To check the credentials and necessary setup, run `python cli.py whoami`. This will show your details.
168 changes: 168 additions & 0 deletions cli-tool/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import json
import os

import click
import requests
from decouple import config
from rich import print
from rich.console import Console
from rich.table import Table

console = Console()

print("Welcome to the CLI Tool of [bold blue]MediaCMS![/bold blue]", ":thumbs_up:")


BASE_URL = 'https://demo.mediacms.io/api/v1'
AUTH_KEY = ''
USERNAME = ''
EMAIL = ''


def set_envs():
with open('.env', 'r') as file:
if not file.read(1):
print("Use the Login command to set your credential environment variables")
else:
global AUTH_KEY, USERNAME, EMAIL
AUTH_KEY = config('AUTH_KEY')
USERNAME = config('USERNAME')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've logged in, and see that .env creates the entry USERNAME
However here when I print USERNAME it is set to 'user' - AUTH_KEY and EMAIl are correct from .env

So my-media gives error results (queries https://demo.mediacms.io/api/v1/media?author=user instead of https://demo.mediacms.io/api/v1/media?author=markos in my case)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not able to replicate this error. I am getting correct media and username :(

EMAIL = config('EMAIL')


set_envs()


@click.group()
def apis():
"""A CLI wrapper for the MediaCMS API endpoints."""


@apis.command()
def login():
"""Login to your account."""

email = input('Enter your email address: ')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

email or username is valid, so this could ask for any of the two enter email or username type

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But if we want to keep both username or email, we will have to pass two different params in the request. And then two different variables/inputs would be needed from user

password = input('Enter your password: ')

data = {
"email": f"{email}",
"password": f"{password}",
}

response = requests.post(url=f'{BASE_URL}/login', data=data)
if response.status_code == 200:
username = json.loads(response.text)["username"]
with open(".env", "w") as file:
file.writelines(f'AUTH_KEY={json.loads(response.text)["token"]}\n')
file.writelines(f'EMAIL={json.loads(response.text)["email"]}\n')
file.writelines(f'USERNAME={json.loads(response.text)["username"]}\n')
file.close()
shubhank-saxena marked this conversation as resolved.
Show resolved Hide resolved
print(f"Welcome to MediaCMS [bold blue]{username}[/bold blue]. Your auth creds have been suceesfully stored in the .env file", ":v:")
else:
print(f'Error: {response.text}')
shubhank-saxena marked this conversation as resolved.
Show resolved Hide resolved


@apis.command()
def upload_media():
"""Upload media to the server"""

headers = {'authorization': f'Token {AUTH_KEY}'}

path = input('Enter the location of the file or directory where multiple files are present: ')

if os.path.isdir(path):
for filename in os.listdir(path):
files = {}
abs = os.path.abspath("{path}/{filename}")
files['media_file'] = open(f'{abs}', 'rb')
response = requests.post(url=f'{BASE_URL}/media', headers=headers, files=files)
if response.status_code == 201:
print("[bold blue]{filename}[/bold blue] successfully uploaded!")
else:
print(f'Error: {response.text}')

else:
files = {}
files['media_file'] = open(f'{os.path.abspath(path)}', 'rb')
response = requests.post(url=f'{BASE_URL}/media', headers=headers, files=files)
if response.status_code == 201:
print("[bold blue]{filename}[/bold blue] successfully uploaded!")
else:
print(f'Error: {response.text}')


@apis.command()
def my_media():
"""List all my media"""

headers = {'authorization': f'Token {AUTH_KEY}'}
response = requests.get(url=f'{BASE_URL}/media?author={USERNAME}', headers=headers)

if response.status_code == 200:
data_json = json.loads(response.text)

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name of the media")
table.add_column("Media Type")
table.add_column("State")

for data in data_json['results']:
table.add_row(data['title'], data['media_type'], data['state'])
console.print(table)

else:
print(f'Could not get the media: {response.text}')


@apis.command()
def whoami():
"""Shows the details of the authorized user"""
headers = {'authorization': f'Token {AUTH_KEY}'}
response = requests.get(url=f'{BASE_URL}/whoami', headers=headers)
for data, value in json.loads(response.text).items():
print(data, ' : ', value)


@apis.command()
def categories():
"""List all categories."""
response = requests.get(url=f'{BASE_URL}/categories')
if response.status_code == 200:
data_json = json.loads(response.text)

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Category")
table.add_column("Description")

for data in data_json:
table.add_row(data['title'], data['description'])

console.print(table)
else:
print(f'Could not get the categories: {response.text}')


@apis.command()
def encodings():
"""List all encoding profiles"""
response = requests.get(url=f'{BASE_URL}/encode_profiles/')
if response.status_code == 200:
data_json = json.loads(response.text)

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name")
table.add_column("Extension")
table.add_column("Resolution")
table.add_column("Codec")
table.add_column("Description")

for data in data_json:
table.add_row(data['name'], data['extension'], str(data['resolution']), data['codec'], data['description'])
console.print(table)
else:
print(f'Could not get the encodings: {response.text}')


if __name__ == '__main__':
apis()
4 changes: 4 additions & 0 deletions cli-tool/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
click
python-decouple
requests
rich
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ pytest-django
pytest-factoryboy
Faker
selenium
webdriver-manager
webdriver-manager
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ m3u8
django-ckeditor
django-debug-toolbar

django-login-required-middleware==0.6.1
django-login-required-middleware==0.6.1