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

Refactor AWS Python Client #25

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__/*

This file was deleted.

This file was deleted.

Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Written for Python 3.6.x

import json
import os
import random
import string
import subprocess
import time
from urllib import request

from winapi import WinApi

class Client:

def __init__(self, api_base, api_key):
self.api_base = api_base
self.api_key = api_key

self.client_id = self.generate_id()
self.current_path = os.path.dirname(os.path.realpath(__file__))

def generate_id(self):
client_id = ''.join(random.choices(string.ascii_letters + string.digits, k=random.randint(12, 14)))

WinApi.show_message('Client ID', client_id, WinApi.BoxType.MB_OK, WinApi.IconType.INFO)

return client_id

def get_response(self, client_id):
with request.urlopen(f'{self.api_base}{client_id}?key={self.api_key}') as response:
Copy link

Choose a reason for hiding this comment

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

Hi,

I know this is a refactoring PR and the issues exist in the original code, but should this and the request below be wrapped in a try/except URLError? or is the client just restarted if it crashes? Also below you are installing an opener on every call but it looks like that installs the opener globally so could that be moved outside the loop?

PS. I don't have write access but saw the PR while reading the code and thought I'd comment. I hope you don't mind.

Copy link
Member Author

Choose a reason for hiding this comment

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

Heyo, yes they should be. Technically, since the client will be calling this from just a command line and it's not automated they can just restart it BUT I do agree that it's better to have the try/except there.

As for the opener, probably. I've barely used urllib and have always just stuck around with the requests library.

I'll push up a commit real quick to address these few things. If you notice anything else, feel free to comment. This was written in like 10 minutes, maybe less so there's bound to be errors.

(also, I don't mind at all :P)

return json.loads(response.read())

def loop(self):
while True:
response = self.get_response(self.client_id)

for item in response:
# Check if the server echos back the client id
if item.get('clientID') == self.client_id:
action = item.get('action')

if action and item.get('data'):
data = json.loads(item['data'])

if action == 'messagebox':
WinApi.show_message(
data.get('title') or '',
data.get('message') or '',
WinApi.box_type(data.get('type') or ''),
data.get('icon') and WinApi.IconType[data['icon'].upper()] or None
Copy link

Choose a reason for hiding this comment

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

This could raise a KeyError if the icon name isn't valid.

You could move it to a try/except or maybe
, getattr(WinApi.IconType, data.get('icon', '').upper(), None),
if you want to keep everything on one line.

)

elif action == 'showimage':
opener = request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; x64; rv:60.0) Gecko/20100101 Firefox/60.0')]
request.install_opener(opener)

request.urlretrieve(data.get('url') or '', 'image.tmp')

subprocess.call(f'rundll32 "C:\Program Files\Windows Photo Viewer\PhotoViewer.dll", ImageView_Fullscreen {self.current_path}\\image.tmp')

time.sleep(20)
26 changes: 26 additions & 0 deletions Unofficial/Python/remote-control-client/aws-based-rc/client/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# A file for you to run the client with ease.
from optparse import OptionParser
import os
import sys

from client import Client

parser = OptionParser()
parser.add_option('-k', '--key', dest='api_key', help='The Api Key', metavar='api_key', default=None)
parser.add_option('-b', '--base', dest='api_base', help='Base url of the api', metavar='base_url', default=None)

(options, args) = parser.parse_args()

API_KEY = os.environ.get('AWS_CONTROL_API_KEY') or options.api_key
API_BASE = os.environ.get('AWS_CONTROL_API_BASE') or options.api_base

if not API_KEY or not API_BASE:
print('Invalid API_KEY/API_BASE set, please use `file.py -k <KEY> -b <BASE>` or set the `AWS_CONTROL_API_KEY/AWS_CONTROL_API_BASE` env vars!')
Copy link

Choose a reason for hiding this comment

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

minor nit: you could use run.py or sys.argv[0] instead of file.py

sys.exit(0)

client = Client(API_BASE, API_KEY)

# loop blocks until it's exited
client.loop()

print('Exiting program...')
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from enum import Enum
import ctypes


class WinApi:
class BoxType(Enum):
MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000

class IconType(Enum):
EXCLAIM = 0x30
INFO = 0x40
QUESTION = 0x20
STOP = 0x10

READABLE_MAP = {
'okonly': BoxType.MB_OK,
'okcancel': BoxType.MB_OKCXL,
'yesnocancel': BoxType.MB_YESNOCXL,
'yesno': BoxType.MB_YESNO
}

def box_type(string):
return WinApi.READABLE_MAP.get(string) or WinApi.BoxType.MB_OK

def show_message(title, content, box_type=BoxType.MB_OK, icon=None):
return icon and ctypes.windll.user32.MessageBoxW(0, content, box_type.value | icon.value) or ctypes.windll.user32.MessageBoxW(0, content, title, box_type.value)