Skip to content

Commit 0d4918a

Browse files
CLI API Tool (#273)
CLI tool
1 parent 8093c4c commit 0d4918a

File tree

5 files changed

+185
-2
lines changed

5 files changed

+185
-2
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
cli-tool/.env
2+
frontend/package-lock.json
13
media_files/encoded/
24
media_files/original/
35
media_files/hls/
@@ -14,4 +16,4 @@ static/mptt/
1416
static/rest_framework/
1517
static/drf-yasg
1618
cms/local_settings.py
17-
deploy/docker/local_settings.py
19+
deploy/docker/local_settings.py

cli-tool/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
## MediaCMS CLI Tool
2+
This is the CLI tool to interact with the API of your installation/instance of MediaCMS.
3+
4+
### How to configure and use the tools
5+
- Make sure that you have all the required installations (`cli-tool/requirements.txt`)installed. To install it -
6+
- Create a new virtualenv using any python virtualenv manager.
7+
- Then activate the virtualenv and enter `pip install -r requirements.txt`.
8+
- Create an .env file in this folder (`mediacms/cli-tool/`)
9+
- Run the cli tool using the command `python cli.py login`. This will authenticate you and store necessary creds for further authentications.
10+
- To check the credentials and necessary setup, run `python cli.py whoami`. This will show your details.

cli-tool/cli.py

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

cli-tool/requirements.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
click
2+
python-decouple
3+
requests
4+
rich

requirements-dev.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ pytest-django
1313
pytest-factoryboy
1414
Faker
1515
selenium
16-
webdriver-manager
16+
webdriver-manager

0 commit comments

Comments
 (0)