Compare commits

..

4 Commits
master ... cli

Author SHA1 Message Date
e120815378 splits main function and parser 2022-01-16 22:22:19 +01:00
3a47ee56bf updates setup.py for cli 2022-01-16 22:18:12 +01:00
aeca052cbc adds cli to __init__ 2022-01-16 19:57:19 +01:00
2294650daa adds minimal cli for qr code and pushing
- cli generated using typer package,
  which is added to the setup.py
- if optional argument to bump is not
  passed, the current secret is visualized
- if there is an argument, it is pushed
  as a message to the current sender
2022-01-16 19:52:12 +01:00
3 changed files with 50 additions and 126 deletions

119
bump/bump.py Executable file → Normal file
View File

@ -52,57 +52,21 @@ def password_decrypt(token: bytes, password: str) -> bytes:
return Fernet(key).decrypt(token) return Fernet(key).decrypt(token)
class Bump: class Bump:
def __init__(self, secret: str = None) -> None: def __init__(self, secret=None, secrets_file=None):
self._initialize_parameters() if None == secrets_file:
self._save_or_load_secrets(secret) secrets_file = os.path.join(os.path.expanduser('~'), '.config/bump/secrets_file')
self.secrets = self._load_secrets(secret, secrets_file)
def _save_or_load_secrets(self, secret: str = None) -> None:
self._check_and_save_secret(secret)
self.secrets = self._load_secrets(secret)
if self.secrets == []: if self.secrets == []:
print("you seem to not have a secret in your secrets file! Creating one now...") print("you seem to not have a secret in your secrets file! Creating one now...")
self.generate_secret() self.generate_secret(secrets_file)
def _check_secret_valid(self, secret: str) -> bool:
pattern = re.compile('^[a-zA-Z-]+$')
words = secret.split('-')
if (pattern.match(secret) and
len(words) >= SENDER_LENGTH + PASSWORD_LENGTH and
sum([len(word) for word in words[SENDER_LENGTH:]]) > 32):
return True
else:
return False
def _initialize_parameters(self) -> None:
self.secrets_file = os.path.join(os.path.expanduser('~'), '.config/bump/secrets_file')
self.URL = "https://bump.maenle.net/api/" self.URL = "https://bump.maenle.net/api/"
self.secrets = []
def _check_and_save_secret(self, secret:str = None) -> None:
if secret is not None:
if self._check_secret_valid(secret):
self._save_secret(secret)
else:
print("--------------")
print("invalid secret")
print("--------------")
def _load_secrets(self, secret, secrets_file):
def _save_secret(self, secret: str) -> None:
self.secrets.append(secret)
if not os.path.exists(os.path.dirname(self.secrets_file)):
os.makedirs(os.path.dirname(self.secrets_file))
with open(self.secrets_file, 'a+') as f:
f.write(secret + '\n')
def _load_secrets(self, secret: str) -> list:
try: try:
with open(self.secrets_file, 'r') as f: with open(secrets_file, 'r') as f:
secrets = f.read().splitlines() secrets = f.read().splitlines()
except FileNotFoundError: except FileNotFoundError:
secrets = [] secrets = []
@ -111,24 +75,30 @@ class Bump:
return secrets return secrets
def generate_secret(self): def generate_secret(self, secrets_file):
keywords = self._generate_keywords()
self._check_and_save_secret(keywords)
def _generate_keywords(self) -> str:
pattern = re.compile('^[a-zA-Z]+$') pattern = re.compile('^[a-zA-Z]+$')
WORDS = r.get_random_words()
secret = "" secret = ""
word_count = 0 word_count = 0
while word_count < SENDER_LENGTH + PASSWORD_LENGTH: while word_count < SENDER_LENGTH + PASSWORD_LENGTH or len(secret[SENDER_LENGTH:]) < 32:
word = r.get_random_word() word = random.choice(WORDS)
if pattern.match(word) and len(word) < 10 and len(word) >= 4: print(pattern.match(word))
if pattern.match(word) and len(word) < 10:
secret += word + "-" secret += word + "-"
word_count += 1 word_count += 1
secret = secret[:-1] secret = secret[:-1]
return secret
def show_secret(self) -> None: self.secrets.append(secret)
if not os.path.exists(os.path.dirname(secrets_file)):
os.makedirs(os.path.dirname(secrets_file))
with open(secrets_file, 'a+') as f:
f.write(secret + '\n')
def show_secret(self):
print("Scan this QR Code with the Bump app to connect") print("Scan this QR Code with the Bump app to connect")
for secret in self.secrets: for secret in self.secrets:
qr = qrcode.QRCode( qr = qrcode.QRCode(
@ -142,24 +112,24 @@ class Bump:
print("") print("")
print(secret) print(secret)
def _get_password(self, index: int = 0) -> str: def _get_password(self, index=0):
secret = self.secrets[index].split('-') secret = self.secrets[index].split('-')
return "-".join(secret[SENDER_LENGTH:]) return "-".join(secret[SENDER_LENGTH:])
def _get_sender(self, index: int = 0) -> str: def _get_sender(self, index=0):
words = self.secrets[index].split('-') words = self.secrets[index].split('-')
return "-".join(words[0:SENDER_LENGTH]) return "-".join(words[0:SENDER_LENGTH])
def _encrypt(self, data:str) -> str: def _encrypt(self, data):
password = self._get_password() password = self._get_password()
return password_encrypt(data.encode(), password) return password_encrypt(data.encode(), password)
def _decrypt(self, data: str) -> str: def _decrypt(self, data):
password = self._get_password() password = self._get_password()
return password_decrypt(data, password).decode() return password_decrypt(data, password).decode()
def push(self, title='', data='') -> None: def push(self, title='', data=''):
params = { params = {
'sender': self._get_sender(), 'sender': self._get_sender(),
'title': title, 'title': title,
@ -167,31 +137,22 @@ class Bump:
} }
return self._set_post("push", params) return self._set_post("push", params)
def peek(self) -> dict: def peek(self):
return self._get_post("peek") return self._get_post("peek")
def pop(self) -> dict: def pop(self):
return self._get_post("pop") return self._get_post("pop")
def list(self) -> list: def list(self):
params = { params = {
'minutes': 2 'minutes': 2
} }
return self._get_post("list", params) return self._get_post("list", params)
def clear(self) -> None: def clear(self):
return self._get_post("clear") return self._get_post("clear")
def delete_senders(self):
self.secrets = []
if not os.path.exists(os.path.dirname(self.secrets_file)):
os.makedirs(os.path.dirname(self.secrets_file))
with open(self.secrets_file, 'w+') as f:
f.write("")
def delete_sender(self): def delete_sender(self):
return self._set_post("delete_sender") return self._set_post("delete_sender")
@ -207,7 +168,7 @@ class Bump:
messages = requests.post(url, params).json() messages = requests.post(url, params).json()
print(messages) print(messages)
def _get_post(self, mechanism: str, add_params: dict = None) -> dict: def _get_post(self, mechanism, add_params = None):
url = self.URL + mechanism url = self.URL + mechanism
params = { params = {
@ -232,25 +193,25 @@ class Bump:
return [messages] return [messages]
def _load_log(self) -> list: def _load_log(self):
with open('.bump_log', "r+") as f: with open('.bump_log', "r+") as f:
return f.readlines() return f.readlines()
def _save_log(self, message: str) -> None: def _save_log(self, message):
with open('.bump_log', "a") as f: with open('.bump_log', "a") as f:
f.write(self._to_log_line(message)) f.write(self._to_log_line(message))
def _to_log_line(self, message: str) -> str: def _to_log_line(self, message):
return json.dumps(message) + "\n" return json.dumps(message) + "\n"
def alert(self, sleep_time: int = 1) -> None: def alert(self, sleep_time=1):
log = self._load_log() log = self._load_log()
while True: while True:
time.sleep(sleep_time) time.sleep(sleep_time)
messages = self.list() messages = self.list()
for message in messages['messages']: for message in messages:
if self._to_log_line(message) not in log and message != {}: if self._to_log_line(message) not in log and message != {}:
print({'title': message['title'], 'data': message['data']}) print(message['data'])
self._save_log(message) self._save_log(message)
log = self._load_log() log = self.load_log()

View File

@ -1,57 +1,20 @@
from typing import Optional
import bump import bump
import typer import typer
import sys
import select
cli = typer.Typer()
def default( @cli.command()
message_arg:Optional[str] = typer.Argument(None, help="The message to be bumped"), def default(message = typer.Argument(None, help="The message to be bumped")):
message:Optional[str] = typer.Option(None, help="The message to be bumped"),
reset:Optional[bool] = typer.Option(False, help="remove all senders"),
alert:Optional[bool] = typer.Option(False, help="check continuously for new messages"),
secret:Optional[str] = typer.Option(None, help="change the sender and e2e keys")):
bp = bump.Bump() bp = bump.Bump()
if message is None:
pipe = None bp.show_secret()
if select.select([sys.stdin,],[],[],0.0)[0]:
pipe = sys.stdin.readline()
if message_arg is not None:
push(message_arg)
elif pipe is not None:
push(pipe)
elif message is not None:
push(message)
elif secret is not None:
secrets(secret)
elif reset:
delete_senders()
elif alert:
alert_process()
else: else:
info() bp.push(message)
def delete_senders(): @cli.command()
def push():
bp = bump.Bump() bp = bump.Bump()
bp.delete_senders() bp.version()
def alert_process():
bp = bump.Bump()
bp.alert()
def secrets(secret:str):
if secret is not None:
bp = bump.Bump(secret)
info()
def push(message:str):
bp = bump.Bump()
bp.push(message)
def info():
bp = bump.Bump()
bp.show_secret()
def main(): def main():
typer.run(default) typer.run(default)

View File

@ -9,7 +9,7 @@ setup(
name='bump_python', name='bump_python',
packages=['bump'], packages=['bump'],
description='Notify your Phone from Python', description='Notify your Phone from Python',
version='0.1.5', version='0.1.2',
url='https://git.maenle.tech/raphael/bump_python', url='https://git.maenle.tech/raphael/bump_python',
author='Raphael Maenle', author='Raphael Maenle',
author_email='raphael@maenle.net', author_email='raphael@maenle.net',