commit 616f220cfc3be4132a2bd5a39b818bb7b8caa11e Author: Cassowary Rusnov Date: Mon Nov 22 09:54:37 2021 -0800 Initial checkin. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a233641 --- /dev/null +++ b/.gitignore @@ -0,0 +1,183 @@ +# -*- mode: gitignore; -*- + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# pytype +.pytype/ + +# Pyre type checker +.pyre/ + +# emacs things +*~ +\#*\# +/.emacs.desktop +/.emacs.desktop.lock +*.elc +auto-save-list +tramp +.\#* + +# Org-mode +.org-id-locations +*_archive + +# flymake-mode +*_flymake.* + +# eshell files +/eshell/history +/eshell/lastdir + +# elpa packages +/elpa/ + +# reftex files +*.rel + +# AUCTeX auto folder +/auto/ + +# cask packages +.cask/ +dist/ + +# Flycheck +flycheck_*.el + +# server auth directory +/server/ + +# projectiles files +.projectile + +# directory configuration +.dir-locals.el + +# network security +/network-security.data diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..69beda9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +Copyright © 2021 Cassowary Rusnov + +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. + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..aae77cd --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# CiviCRM APIv4 # + +**alpha state** + +This is an extremely thin layer which supports basic operations against CiviCRM's APIv4. It does little processing, +and mostly encodes some knowledge about how to interact with the API so that this code need not be repeated in projects. + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..118495b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools-build_meta" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1190bd8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +requests +beautifulsoup4 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..1a86e64 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,36 @@ +[metadata] +name = civicrmapi4 +version = 0.0.1 +description = A simple layer to interact with the CiviCRM APIv4 +author = Cassowary Rusnov +author_email = rusnovc@gmail.com +keywords = api, civicrm +long_description = file: README.md +long_description_content_type = text/markdown +license_file = LICENSE +url = +license = MIT +platform = any +classifiers = + Development Status :: 3 - Alpha + Intended Audience :: Developers + License :: OSI Approved :: MIT License + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Topic :: Internet + Topic :: Internet :: WWW/HTTP + +[options] +packages = + civicrmapi4 + +zip_safe = true +install_requires = + python_version >= "3.6" + requests + beautifulsoup4 + \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..a4f49f9 --- /dev/null +++ b/setup.py @@ -0,0 +1,2 @@ +import setuptools +setuptools.setup() diff --git a/src/civicrmapi4/__init__.py b/src/civicrmapi4/__init__.py new file mode 100644 index 0000000..925bb3e --- /dev/null +++ b/src/civicrmapi4/__init__.py @@ -0,0 +1,5 @@ +"""Top-level package for civicrmapi4.""" + +__author__ = """Cassowary Rusnov""" +__email__ = "rusnovc@gmail.com" +__version__ = "0.0.1" diff --git a/src/civicrmapi4/civicrmapi4.py b/src/civicrmapi4/civicrmapi4.py new file mode 100644 index 0000000..cd4d53b --- /dev/null +++ b/src/civicrmapi4/civicrmapi4.py @@ -0,0 +1,132 @@ +"""Main module.""" + +import json +import requests +import logging + +from typing import List, Optional, Dict, Union + +from bs4 import BeautifulSoup + + +log = logging.getLogger(__name__) + + +class APIError (BaseException): + ... + + +class CallFailed(APIError): + ... + + +class APIv4: + def __init__(self, base_url: str): + self.base_url = base_url + self.api_url = self.base_url + "/civicrm/ajax/api4" + self.session = None + + def login(self, user: str, password: str): + self.session = requests.Session() + + ### Perform login post + self.session.cookies.update({"has_js": "1"}) + postdata = { + "name": user, + "pass": password, + "form_id": "user_login_block", + } + res = self.session.post(self.base_url, data=postdata) + if (not res.ok): + log.error("Login failed. Code: {}. Result: {}".format(res.status_code, res.text)) + # we should raise an error here. + self.session = None + return + # session now has the correct session cookie to do authenticated requests + # these headers seem to be required to pass CSRF + self.session.headers.update({ + "X-Requested-With": "XMLHttpRequest", + "Content-Type": "application/json;charset=utf-8", + }) + log.info("Successfully logged into CRM.") + + def _call(self, objName: str, action: str, params: Optional[Dict] = None) -> requests.Response: + """ + Low level, minimal processing call to the API. + """ + if (self.session is None): + log.error("Need to login first.") + raise APIError("Need to login first.") + + url = self.api_url+'/'+objName+'/'+action + if params: + result = self.session.post(url, params={'params':json.dumps(params)}, data="") + else: + result = self.session.post(url, data="") + if (not result.ok): + raise CallFailed("Call returned non-2xx: {} {}".format(result.status_code, result.text)) + + return result.json() + + def call_values(self, objName: str, action: str, params: Optional[Dict] = None) -> Optional[List]: + """A quick wrapper to just return the values of an API call""" + result = self._call(objName, action, params) + if result and ("values" in result): + return result["values"] + + return None + + def get_fields(self, objName: str) -> List: + """ + Return a list of fields on the target object type. + """ + return self.call_values(objName, "getFields") + + def get_actions(self, objName: str) -> List: + """ + Return a list of possible actions for a given object type. + """ + return self.call_values(objName, "getActions") + + def get_entities(self, detailed: bool = False) -> Union[List[str], List[Dict]]: + """Return a list of possible entities.""" + ent = self.call_values("Entity", "get") + if detailed: + return ent + + return [x["name"] for x in ent] + + def get(self, objName: str, where: Optional[List]=None, limit: Optional[int]=None, select=Optional[List[str]]) -> List: + """Get objects based on a where clause, optional limit and optional field list.""" + params = {} + if limit is not None: + params["limit"] = limit + if where is not None: + params["where"] = where + if columns is not None and columns: + params["select"] = select + + return self.call_values(objName, "get", params=params) + + def create(self, objName: str, values: Dict) -> Dict: + """Create an object using the values specified, and return the newly created object.""" + result = self.call_values(objName, "create", params={"values": values}) + if result: + return result[0] + return {} + + def delete(self, objName: str, where: List) -> int: + """Delete objects with the specified where clauses and return the count..""" + result = self._call(objName, "delete", params={"where": where}) + + if "count" in result: + return result["count"] + + return 0 + + def replace(self, objName: str, records: List[Dict], where: List) -> List: + ... + + def update(self, objName: str, fields: Dict, where: List) -> List: + """Update is an upsert operation.""" + ... diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..7507b81 --- /dev/null +++ b/tox.ini @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 120 +max-complexity = 20