1 Commits

Author SHA1 Message Date
6f3434e8db Updated build number and gitea workflow
Some checks failed
Build python package / Build (push) Failing after 19s
2026-03-28 19:25:59 +01:00
3 changed files with 53 additions and 172 deletions

View File

@@ -8,21 +8,14 @@ jobs:
container:
image: python
steps:
- name: Act Workaround # https://github.com/nektos/act/issues/973
if: ${{ env.ACT }}
run: curl -fsSL https://deb.nodesource.com/setup_22.x | bash && apt install -y nodejs
- name: Check out repository code
uses: actions/checkout@main
- name: Setting up python modules to build package
run: |
python -m pip install build twine
- name: Building the package
run: |
mkdir ${{ gitea.workspace }}/build/src/GLPIAPI/
mv ${{ gitea.workspace }}/GLPIAPI.py ${{ gitea.workspace }}/build/src/GLPIAPI/GLPIAPI.py
cd ${{ gitea.workspace }}/build
mv ${{ gitea.workspace }}\GLPIAPI.py ${{ gitea.workspace }}\build\src\GLPIAPI\
cd ${{ gitea.workspace }}\build
python -m build
- name: Publish package
run: |
python -m twine upload -u ${{ secrets.repo_user }} -p ${{ secrets.repo_pass }} --repository-url ${{ secrets.repo_url }} ${{ gitea.workspace }}/build/dist/*
python -m twine upload -u ${{ secrets.repo_user }} -p ${{ secrets.repo_pass }} --repository-url ${{ secrets.repo_url }} ${{ gitea.workspace }}\build\dist\*
if: github.ref_type == 'tag'

View File

@@ -3,7 +3,7 @@ import json
from datetime import datetime
class GLPIAPI:
def __init__(self, Server, AppToken, UserToken, UserAgent="GLPI API", Profile=None):
def __init__(self, Server, AppToken, UserToken, UserAgent="GLPI API"):
self.Server = Server
self.AppToken = AppToken
self.UserToken = UserToken
@@ -11,16 +11,7 @@ class GLPIAPI:
self.SessionToken = None
self.StatusCode = None
self.Headers = None
self.ActiveProfile = None
self.ActiveEntity = None
self.RecurseEntity = True
self.InitConnection()
if(Profile == None):
self.ActiveProfile = self.GetActiveProfile()[0]
else:
self.ActiveProfile = Profile
profileId = self.GetItems('Profile', 'Profile.name', Profile)[1]['2']
self.SetActiveProfile(profileId)
def InitConnection(self):
initURI = '/apirest.php/initSession/'
@@ -41,106 +32,8 @@ class GLPIAPI:
"Session-Token": self.SessionToken,
"App-Token": self.AppToken
}
if(self.GetActiveProfile()[0] != self.ActiveProfile and self.ActiveProfile != None):
profile = [p for p in self.GetUserProfiles() if p["name"] == self.ActiveProfile]
if(profile != []):
self.SetActiveProfile(profile[0]["id"])
else:
raise Exception(f"{self.ActiveProfile} is not in user profiles")
ActiveEntities = self.GetActiveEntity()
if((ActiveEntities[0] != self.ActiveEntity or ActiveEntities[1] != self.RecurseEntity) and self.ActiveEntity != None):
entity = [e for e in self.GetUserEntities() if e["id"] == self.ActiveEntity]
if(entity != []):
self.SetActiveEntity(entity[0]["id"], self.RecurseEntity)
else:
raise Exception(f"{self.ActiveEntity} is not in user entities")
else:
raise Exception(f"{result.status_code} - {result.json()[0]}")
def CheckConnection(self):
sessionUri = f"{self.Server}/apirest.php/getFullSession/"
result = requests.get(sessionUri, headers=self.Headers)
if(result.status_code != 200 and result.json()[0] == 'ERROR_SESSION_TOKEN_INVALID'):
self.InitConnection()
return result.status_code
def GetUserProfiles(self):
self.CheckConnection()
uri = f"{self.Server}/apirest.php/getMyProfiles"
req = requests.get(uri, headers=self.Headers)
if(req.status_code == 200):
return req.json()['myprofiles']
else:
return req.status_code
def GetActiveProfile(self):
self.CheckConnection()
uri = f"{self.Server}/apirest.php/getActiveProfile"
req = requests.get(uri, headers=self.Headers)
if(req.status_code == 200):
return (req.json()['active_profile']['name'],req.json()['active_profile']['id'])
else:
return req.status_code
def SetActiveProfile(self, profile):
self.CheckConnection()
if(type(profile) == str):
profileFound = [p for p in self.GetUserProfiles() if p["name"] == profile]
if(profileFound != []):
profileId = profileFound[0]["id"]
else:
profileId = profile
body = {
"profiles_id" : profileId
}
uri = f"{self.Server}/apirest.php/changeActiveProfile"
req = requests.post(uri, headers=self.Headers, json=body)
if(req.status_code == 200):
self.ActiveProfile = self.GetActiveProfile()[0]
return req.status_code
def GetUserEntities(self):
self.CheckConnection()
uri = f"{self.Server}/apirest.php/getMyEntities"
req = requests.get(uri, headers=self.Headers)
if(req.status_code == 200):
return req.json()["myentities"]
else:
return req.status_code
def GetActiveEntity(self):
self.CheckConnection()
uri = f"{self.Server}/apirest.php/getActiveEntities"
req = requests.get(uri, headers=self.Headers)
if(req.status_code == 200):
return (req.json()['active_entity']['id'], req.json()['active_entity']['active_entity_recursive'], req.json()['active_entity']['active_entities'])
else:
return req.status_code
def SetActiveEntity(self, entity, recurse=True):
self.CheckConnection()
if(type(entity) == str):
entityFound = [e for e in self.GetUserEntities() if e["name"] == entity]
if(entityFound != []):
entityId = entityFound[0]["id"]
else:
entityId = entity
body = {
"entities_id" : entityId,
"is_recursive" : recurse
}
uri = f"{self.Server}/apirest.php/changeActiveEntities"
req = requests.post(uri, headers=self.Headers, json=body)
if(req.status_code == 200):
ActiveEntities = self.GetActiveEntity()
self.ActiveEntity = ActiveEntities[0]
self.RecurseEntity = ActiveEntities[1]
return req.status_code
def GetComputers(self, deviceName=None, serialNumber=None, user=None, imei=None, airwatchDevice=None, fieldsToDisplay=[], trashbin=0):
def GetComputers(self, deviceName=None, serialNumber=None, user=None, imei=None, airwatchDevice=None):
'''
Search for computer items in GLPI based on one of the possibles parameters :
- deviceName : name of the item
@@ -148,58 +41,50 @@ class GLPIAPI:
- user : user of the item
- imei : custom field using field plugin (only for internal use)
- airwatchDevice : an airwatchDevice object from airwatchAPI module
If no parameters are set, it will search for all items.
fieldsToDisplay: set fields to forcefully add to the results of the search (must be a list [])
trashbin: set if the search is in the trashbin or not (0 not in the trash or 1 in the trash)
If no parameters are set, it will search for all items
Return a tuple with item id, item data and item count.
'''
self.CheckConnection()
searchAll = False
if(deviceName != None):
# Recherche en fonction du nom de l'appareil
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=1&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{deviceName}$'
search_parameter = f'is_deleted=0&criteria[0][field]=1&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{deviceName}$'
elif(user != None):
# Recherche en fonction de l'utilisateur de l'appareil
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=70&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{user}$'
search_parameter = f'is_deleted=0&criteria[0][field]=70&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{user}$'
elif(airwatchDevice != None):
if(airwatchDevice.Imei != ''):
# Recherche des appareils en fonction du numéro de série ou de l'imei
# l'imei pouvant être dans le champ numéro de série ou les champs imei custom (plugin field)
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{airwatchDevice.SerialNumber}$'\
search_parameter = f'is_deleted=0&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{airwatchDevice.SerialNumber}$'\
f'&criteria[1][link]=OR&criteria[1][field]=5&criteria[1][searchtype]=contains&criteria[1][value]=^{airwatchDevice.Imei}$'\
f'&criteria[2][link]=OR&criteria[2][field]=76667&criteria[2][searchtype]=contains&criteria[2][value]=^{airwatchDevice.Imei}$'\
f'&criteria[3][link]=OR&criteria[3][field]=76670&criteria[3][searchtype]=contains&criteria[3][value]=^{airwatchDevice.Imei}$'
else:
# Recherche des appareils en fonction du numéro de série seulement
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{airwatchDevice.SerialNumber}$'
search_parameter = f'is_deleted=0&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{airwatchDevice.SerialNumber}$'
elif(imei != None):
# Recherche des appareils en fonction du numéro de série ou de l'imei
# l'imei pouvant être dans le champ numéro de série ou les champs imei custom (plugin field)
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{serialNumber}$'\
search_parameter = f'is_deleted=0&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{serialNumber}$'\
f'&criteria[1][link]=OR&criteria[1][field]=5&criteria[1][searchtype]=contains&criteria[1][value]=^{imei}$'\
f'&criteria[2][link]=OR&criteria[2][field]=76667&criteria[2][searchtype]=contains&criteria[2][value]=^{imei}$'\
f'&criteria[3][link]=OR&criteria[3][field]=76670&criteria[3][searchtype]=contains&criteria[3][value]=^{imei}$'
elif(serialNumber != None):
# Recherche des appareils en fonction du numéro de série seulement
search_parameter = f'is_deleted={trashbin}&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{serialNumber}$'
search_parameter = f'is_deleted=0&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{serialNumber}$'
else:
# Recherche de l'ensemble des appareils si rien n'est renseigné
searchAll = True
search_parameter = f'is_deleted=0&criteria[0][link]=AND&criteria[0][field]=view&criteria[0][searchtype]=contains&criteria[0][value]='
if(searchAll):
searchUri = f"{self.Server}/apirest.php/search/Computer/?range=0-9999999&is_deleted={trashbin}"
searchUri = f"{self.Server}/apirest.php/search/Computer/?range=0-9999999&is_deleted=0"
else:
searchUri = f"{self.Server}/apirest.php/search/Computer?{search_parameter}"
if(fieldsToDisplay != []):
for i in range(len(fieldsToDisplay)):
searchUri += f"&forcedisplay[{i}]={fieldsToDisplay[i]}"
search = requests.get(searchUri, headers=self.Headers)
if(search.status_code == 200):
search = search.json()
@@ -215,12 +100,10 @@ class GLPIAPI:
else:
itemID = list(search["data"].keys())
return itemID, search["data"], search["totalcount"]
else:
return None, None, 0
return None, search, 0
return None, None, 0
def GetItems(self, itemType, fieldName=None, fieldValue=None, fieldsToDisplay=[], trashbin=0):
def GetItems(self, itemType, fieldName=None, fieldValue=None):
'''
Search for items of a specific item type in GLPI. A filter can be set using fieldName and fieldValue :
fieldName: must be the name of the field as visible in GLPI
@@ -230,27 +113,19 @@ class GLPIAPI:
Return a tuple with item id (in a list if there are more than 1), item data (in a list of dict items) and item count (int).
If the query does not succeed it will return a tuple with the http status code instead of item data (e.g. None, 400, 0).
'''
self.CheckConnection()
searchAll = False
if(fieldName != None and fieldValue != None):
fieldId = list(self.GetSearchOptions(itemType, fieldName))[0]
# Recherche en fonction de l'utilisateur de l'appareil
search_parameter = f'is_deleted={trashbin}&criteria[0][field]={fieldId}&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{fieldValue}$'
search_parameter = f'is_deleted=0&criteria[0][field]={fieldId}&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{fieldValue}$'
else:
searchAll = True
if(searchAll):
searchUri = f"{self.Server}/apirest.php/search/{itemType}/?range=0-9999999&is_deleted={trashbin}"
searchUri = f"{self.Server}/apirest.php/search/{itemType}/?range=0-9999999&is_deleted=0"
else:
searchUri = f"{self.Server}/apirest.php/search/{itemType}?{search_parameter}"
idFieldNumber = list(self.GetSearchOptions(itemType, f'{itemType}.id'))[0]
searchUri += f"&forcedisplay[0]={idFieldNumber}"
if(fieldsToDisplay != []):
for i in range(1, len(fieldsToDisplay)+1):
searchUri += f"&forcedisplay[{i}]={fieldsToDisplay[i-1]}"
search = requests.get(searchUri, headers=self.Headers)
if(search.status_code == 200):
@@ -262,16 +137,15 @@ class GLPIAPI:
return itemID, data, search["totalcount"]
elif(search["totalcount"] > 1):
if(searchAll):
idFieldNumber = list(self.GetSearchOptions(itemType, 'id'))[0]
itemID = [i[idFieldNumber] for i in search["data"]]
else:
itemID = list(search["data"].keys())
return itemID, search["data"], search["totalcount"]
else:
return None, None, 0
return None, search, 0
return None, search.status, 0
def GetUsers(self, username=None, email=None, fieldsToDisplay=[], trashbin=0):
def GetUsers(self, username=None, email=None):
'''
Search for users in GLPI based on one of the possibles parameters :
- username : username of the glpi user
@@ -280,31 +154,49 @@ class GLPIAPI:
Returns a tuple with user id, user data and user count
'''
fieldName = None
fieldValue = None
searchAll = False
if(username != None):
fieldName = 'User.name'
fieldValue = username
search_parameter = f'is_deleted=0&criteria[0][field]=1&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{username}$'
elif(email != None):
fieldName = 'User.UserEmail.email'
fieldValue = email
return self.GetItems("User", fieldName, fieldValue, fieldsToDisplay, trashbin)
search_parameter = f'is_deleted=0&criteria[0][field]=5&withindexes=true&criteria[0][searchtype]=contains&criteria[0][value]=^{email}$'
else:
searchAll = True
if(searchAll):
searchUri = f"{self.Server}/apirest.php/search/User/?range=0-9999999&is_deleted=0"
else:
searchUri = f"{self.Server}/apirest.php/search/User?{search_parameter}"
search = requests.get(searchUri, headers=self.Headers)
if(search.status_code == 200):
search = search.json()
if(search["totalcount"] == 1):
userID = list(search["data"].keys())[0]
data = search["data"][userID]
return userID, data, search["totalcount"]
elif(search["totalcount"] > 1):
if(searchAll):
# requires id to be in the display preferences of the api user
userID = [i["2"] for i in search["data"]]
else:
userID = list(search["data"].keys())
return userID, search["data"], search["totalcount"]
return None, None, 0
def GetSearchOptions(self, itemType, fieldName=None):
self.CheckConnection()
queryUri = f"{self.Server}/apirest.php/listSearchOptions/{itemType}"
searchOptions = requests.get(queryUri, headers=self.Headers)
if(searchOptions.status_code == 200):
searchOptions = searchOptions.json()
if(fieldName != None):
for k,v in searchOptions.items():
if('uid' in v.keys() and v['uid'].lower() == fieldName.lower()):
if(v['name'].lower() == fieldName.lower()):
return {k : searchOptions[k]}
return searchOptions
return searchOptions.status_code
def UploadFile(self, file, path):
self.CheckConnection()
manifest = {
"input": {
"name": file,
@@ -323,7 +215,6 @@ class GLPIAPI:
return requests.post(self.Server+"/apirest.php/Document/", headers=headers, data=data, files=files)
def SetDocumentToItem(self, itemID, itemType, documentID):
self.CheckConnection()
body = {
"input": {
"documents_id": documentID,
@@ -334,7 +225,6 @@ class GLPIAPI:
return requests.post(self.Server+"/apirest.php/Document/"+str(documentID)+"/Document_Item", headers=self.Headers, json=body)
def UpdateInventory(self, inventory):
self.CheckConnection()
headers = {
"Content-Type":"Application/x-compress",
"user-agent":self.UserAgent
@@ -350,7 +240,6 @@ class GLPIAPI:
...
}
'''
self.CheckConnection()
body = {
"input" : {
"id" : itemId,
@@ -362,7 +251,7 @@ class GLPIAPI:
return requests.put(uri, headers=self.Headers, json=body)
def UpdateSerialNumber(self, deviceid, serialnumber):
self.CheckConnection()
body = {
"input" : {
"id" : deviceid,
@@ -373,7 +262,7 @@ class GLPIAPI:
return requests.put(uri, headers=self.Headers, json=body)
def UpdateItemUser(self, itemID, itemType, username):
self.CheckConnection()
body = {
"input" : {
"id" : itemID,
@@ -388,7 +277,6 @@ class GLPIAPI:
- containerName is block label name
- containerID is block id
'''
self.CheckConnection()
uri = f"{self.Server}/apirest.php/PluginFields{itemType}{containerName}"
searchURI = f"{self.Server}/apirest.php/PluginFields{itemType}{containerName}?range=0-999999999"
result = requests.get(searchURI, headers=self.Headers)

View File

@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "GLPIAPI"
version = "1.0.6"
version = "1.0.4"
description = "A module python to make it easier to use GLPI API"
readme = "README.md"
dependencies = [