Commit 9525b488 authored by loelkes's avatar loelkes
Browse files

Base for Devices, Setups, Packages, Assets. Extensive Documentation.

parent 4ce0df4b
Copyright 2017 Christian Lölkes
Copyright 2019 Christian Lölkes
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
......
# infobeamerhosted
1. Install with ```pip install infobeamerhostes```
## Quick usage
```
pip install infobeamerhosted
python -m infobeamerhosted
```
## API
### Infobeamer()
```
from infobeamerhosted import *
foo = Infobeamer()
```
#### Properties
* ```.devices``` access all devices
* ```.setups``` access all devices
* ```.packages``` access all devices
* ```.assets``` access all devices
* ```.group : str``` Sets .group for all devices, setups, packages and assets.
### Common Properties for Devices(), Setups(), Packages(), Assets()
* ```.group```: the current group name used to select a subset of items. Set to '' (default) to disable.
* ```.all```: all items available.
* ```.selection```: items where the group name matches ```.group```. If this is not set the output is identitcal to ```.all```.
### Common Methods for Devices(), Setups, Packages(), Assets()
* ```getItems()```fetches all items from the Info-Beamer API. This is called upon initialization.
### Common Properties for Device(), Setup(), Package(), Asset()
* *Device()*: all properties from the [Device Object](https://info-beamer.com/doc/api#deviceobject)
* *Setup()*: all properties from the [Setup Info Object](https://info-beamer.com/doc/api#setupinfoobject)
* *Package()*: all properties from the [Package Object](https://info-beamer.com/doc/api#packageobject)
* *Asset()*: all properties from the [Package Object](https://info-beamer.com/doc/api#assetinfoobject)
* ```.group```: the current group name used to select a subset of items. Set to '' (default) to disable.
### Common Methods for Device(), Setup(), Package(), Asset()
* ```.inGroup(name: str) -> bool``` return True if the Item is in the group with the name *name*.
* ```.update([option: str, payload: dict]) -> bool```. Returns True if successfull, False otherwise.
* ```.delete() -> bool``` deletes the item. Returns True if successfull, False otherwise.
## Standalone use
......@@ -11,6 +57,14 @@
* ```--api-user``` User for info-beamer.com. Default is *empty*. (optional)
* ```--api-url``` Key from info-beamer.com. Default is **https://info-beamer.com/api/v1/** (optional)
You can also set environment variables for API_KEY, API_USER (optional), API_URL (optional).
```
export API_KEY = "infobeamer api key"
export API_USER = ""
export API_URL = "https://info-beamer.com/api/v1/"
```
## Ressources
* **API Documentation** [info-beamer.com/doc/api](https://info-beamer.com/doc/api)
# Copyright 2019 Christian Lölkes
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import requests
import os
import json
......@@ -9,10 +29,9 @@ logger = logging.getLogger(__name__)
class InfobeamerAPI:
def __init__(self, key=False, user=False, url=False):
self.user = user
self.key = key
self.url = url
self.task_num = 5
self.user = user or InfobeamerAPI.USER
self.key = key or InfobeamerAPI.KEY
self.url = url or InfobeamerAPI.URL
def setupRequests(self):
self.status = False
......@@ -56,15 +75,14 @@ class InfobeamerAPI:
def query(self, endpoint='ping', method='GET', payload={}):
result = None
self.status = False
if method not in ['GET', 'POST', 'DELETE']:
raise APIError()
if method is 'GET':
result = requests.get(f'{self.url}{endpoint}',
auth=self.auth, params=payload)
result = requests.get(f'{self.url}{endpoint}', auth=self.auth, params=payload)
elif method is 'POST':
result = requests.post(f'{self.url}{endpoint}',
auth=self.auth, data=payload)
result = requests.post(f'{self.url}{endpoint}', auth=self.auth, data=payload)
elif method is 'DELETE':
result = requests.delete(f'{self.url}{endpoint}',
auth=self.auth, data=payload)
result = requests.delete(f'{self.url}{endpoint}', auth=self.auth, data=payload)
if result.status_code == requests.codes.ok:
self.status = True
self.response = result.json()
......
from API import *
# Copyright 2019 Christian Lölkes
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from threading import Thread
from queue import Queue
from API import InfobeamerAPI as API
from API import InfobeamerAPI
import logging
logger = logging.getLogger(__name__)
class Infobeamer(API):
def __init__(self, key=False):
super().__init__(key)
self.setups = Setups(key)
self.devices = []
class Infobeamer(InfobeamerAPI):
def __init__(self):
super().__init__()
self.setups = Setups()
self.devices = Devices()
self.packages = Packages()
self.assets = Assets()
self.group = ''
@property
def group(self):
def group(self) -> str:
try:
return self.__group
except: # AttributeError
return ''
@group.setter
def group(self, value):
self.__group = value
def getSetup(self, serial=0, id=0):
for setup in self.setups:
if setup.id == int(id):
return setup
else:
continue
return False
def group(self, name: str):
self.__group = name
self.devices.group = name
self.setups.group = name
self.packages.group = name
self.assets.group = name
class Setups(API):
def __init__(self, key):
super().__init__(key)
self.groups = []
self.group = ''
self.getSetups()
class GroupBase(InfobeamerAPI):
def __init__(self, target):
super().__init__()
self.target = target
self.getItems()
@property
def group(self):
def group(self) -> str:
try:
return self.__groupname
except: # AttributeError
return ''
@group.setter
def group(self, name):
def group(self, name: str):
self.__groupname = name
@property
def all(self):
return self.__setups;
def all(self) -> list:
return self.__items;
@all.setter
def all(self, value):
self.__setups = value
def all(self, items: list):
self.__items = items
@property
def selection(self):
return [setup for setup in self.all if setup.inGroup(self.group)]
def selection(self) -> list:
if self.group:
return [item for item in self.all if item.inGroup(self.group)]
else:
return self.all
def getSetups(self):
if not self.query('setup/list'):
def getItems(self):
if not self.query(f'{self.target.NAME}/list'):
raise APIError()
self.all = [Setup(setup) for setup in self.response['setups']]
logger.info(f'Found a total of {len(self.all)} Setups.')
for setup in self.all:
if setup.group and setup.group not in self.groups:
self.groups.append(setup.group)
logger.info(f'Found the following groups {self.groups}')
class Setup:
def __init__(self, config):
self.__dict__.update(config)
self.all = [self.target(item) for item in self.response[self.target.NAME + 's']]
logger.info(f'Found a total of {len(self.all)} {self.target.NAME}s.')
class Setups(GroupBase):
def __init__(self):
super().__init__(Setup)
class Devices(GroupBase):
def __init__(self):
super().__init__(Device)
class Assets(GroupBase):
def __init__(self):
super().__init__(Asset)
class Packages(GroupBase):
def __init__(self):
super().__init__(Package)
def inGroup(self, groupname):
class ItemBase(InfobeamerAPI):
def __init__(self, target):
self.target = target
self.payload = {}
def inGroup(self, groupname: str) -> bool:
if groupname == self.group:
return True
else:
return False
def update(self, option=None, payload=False) -> bool:
if self.query(f'{self.target}/{self.id}/{option}', 'POST', payload or self.payload) and self.response.ok:
logger.info(f'Updated {self.target} with id={self.id}')
return True
logger.error(f'Could not update {self.target} with id={self.id}')
return False
def delete(self) -> bool:
if self.query(f'{self.target}/{self.id}/', 'DELETE') and self.response.ok:
logger.info(f'Deleted {self.target} with id={self.id}')
return True
logger.error(f'Could not delete {self.target} with id={self.id}')
return False
@property
def group(self) -> str:
return self.userdata.get('group',False)
return self.userdata.get('group','')
@group.setter
def group(self, name: str):
self.userdata.update({'group': name})
self.update(payload=self.userdata)
class Device(ItemBase):
NAME = 'device'
def __init__(self, config):
super().__init__('device')
self.__dict__.update(config)
def assignSetup(self, id=0):
self.update({'setup_id': id})
def reboot(self):
self.query('reboot')
class Setup(ItemBase):
NAME = 'setup'
def __init__(self, config):
super().__init__('setup')
self.__dict__.update(config)
class Asset(ItemBase):
NAME = 'asset'
def __init__(self, config):
super().__init__('asset')
self.__dict__.update(config)
class Package(ItemBase):
NAME = 'package'
def __init__(self, config):
super().__init__('package')
self.__dict__.update(config)
# Copyright 2019 Christian Lölkes
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from Infobeamer import *
from API import *
if __name__ == '__main__':
import argparse
......@@ -9,12 +30,12 @@ if __name__ == '__main__':
# Parse arguments for CLI use.
parser = argparse.ArgumentParser()
parser.add_argument('--api-key', type=str, help='API Key.')
parser.add_argument('--api-user', type=str, help='API User.')
parser.add_argument('--api-url', type=str, help='API URL.')
parser.add_argument('--api-user', type=str, default='', help='API User.')
parser.add_argument('--api-url', type=str, default='', help='API URL.')
args = parser.parse_args()
API_KEY = os.environ.get('API_KEY') or args.api_key
API_URL = os.environ.get('API_URL') or args.api_url
API_USER = os.environ.get('API_USER') or args.api_user
InfobeamerAPI.KEY = os.environ.get('API_KEY') or args.api_key
InfobeamerAPI.URL = os.environ.get('API_URL') or args.api_url
InfobeamerAPI.USER = os.environ.get('API_USER') or args.api_user
ibh = Infobeamer(API_KEY)
ibh = Infobeamer()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment