Compare commits

...

78 Commits
v1 ... main

Author SHA1 Message Date
Agate 979bfb7ca9 ci: update .tar.gz URLs for gitea (like #74706)
gitea/passerelle-atreal-openads/pipeline/head There was a failure building this commit Details
2023-02-22 16:50:31 +01:00
Agate d7570c9910 Prepare Jenkinsfile for Gitea migration (#74572)
gitea/passerelle-atreal-openads/pipeline/head There was a failure building this commit Details
2023-02-20 15:12:19 +01:00
Frédéric Péters b305334c75 tox: limit psycopg2 to < 2.9 (#54925) 2021-06-17 08:50:03 +02:00
Frédéric Péters 156ff794f4 tests: give an explicit name when creating files (#53755)
Django 2.2.21 introduced the validation of FieldFile.save() name
argument, which cannot contain a path separator anymore.

ref. https://docs.djangoproject.com/en/3.2/releases/2.2.21/
2021-05-13 09:15:24 +02:00
Frédéric Péters 43c7cf6fcc tests: cast order_by to lists 2021-01-05 09:15:48 +01:00
Frédéric Péters a76678bfcf build: update to use origin/main 2020-12-26 15:21:16 +01:00
Frédéric Péters a6b22e6b40 tox: limit mock version for compatibility with python 3.5 2020-10-06 09:26:03 +02:00
Frédéric Péters 5e08716cd9 tox: get additional modules using https (via #46904#note-2) 2020-09-24 20:04:05 +02:00
Frédéric Péters 214f8e813d tox: stop testing against python 2 2020-09-09 08:04:34 +02:00
Frédéric Péters f4092a6534 build: don't install manage.py 2020-06-12 13:10:29 +02:00
Frédéric Péters 55f359c09d jenkins: build for all default distributions 2020-06-12 13:07:40 +02:00
Frédéric Péters 417768cce7 misc: remove README extraction for setup long description 2020-06-12 12:59:51 +02:00
Frédéric Péters 2dc4176591 debian: add python3 packaging 2020-06-12 12:53:54 +02:00
Frédéric Péters 14fd10268e build: sync setup.py 2020-06-12 12:53:40 +02:00
Thomas NOËL 7066d22b0a tests: run tests with postgres 2020-05-09 13:49:10 +02:00
Thomas NOËL b84bec87e9 switch to native postgresql json field 2020-05-09 13:33:14 +02:00
Benjamin Dauvergne fe1b4fa541 misc: move AddIndex to end of 0002 migration (#39544)
Automatic generation does not sort AddIndex for manual indexes correctly
with respect to Remove/AddField.
2020-05-01 01:41:40 +02:00
Benjamin Dauvergne d4d1234615 misc: add proper 0002 migration (#39544)
0001 should never be modified apart from cosmetic changes.
2020-05-01 01:41:40 +02:00
Benjamin Dauvergne f5828d45e4 tox.ini: add env to manipulate migrations (#39544)
tox -e manage makemigrations
2020-05-01 01:41:40 +02:00
Benjamin Dauvergne 97932ec03c misc: remove explicit byte string in migrations for py3 (#39544) 2020-05-01 01:41:40 +02:00
Benjamin Dauvergne 9865ae0b61 misc: fix package path in migration (#39544) 2020-05-01 01:41:40 +02:00
Benjamin Dauvergne 9656393c58 misc: restore initial 0001 migration (#39544) 2020-05-01 01:41:40 +02:00
Emmanuel Cazenave 78f65b8603 tox: add psycopg2 in deps 2020-04-26 08:41:05 +02:00
Frédéric Péters 424417c08c tox: limit enum34 to 1.1.6, for python 2 compatibility 2020-02-22 10:12:05 +01:00
Emmanuel Cazenave 4aa84aed42 run tests against python3 (#39533) 2020-02-04 18:35:08 +01:00
Emmanuel Cazenave ab07851642 cast version to string (#39533) 2020-02-04 17:29:11 +01:00
Emmanuel Cazenave 351a1a6242 adapt tests to python3 (#39533) 2020-02-04 17:28:28 +01:00
Emmanuel Cazenave 60d2884f8c use items() instead of iteritems() (#39533) 2020-02-04 17:27:47 +01:00
Emmanuel Cazenave 253fc22a15 adapt chunk read to binary data (#39533) 2020-02-04 17:27:19 +01:00
Emmanuel Cazenave 436022883a open file in binary mode (#39533) 2020-02-04 17:26:51 +01:00
Emmanuel Cazenave 5747367a56 use response.text when expecting text (#39533) 2020-02-04 17:26:18 +01:00
Emmanuel Cazenave 0ecaa0d858 grab url methods form six (#39533) 2020-02-04 17:25:01 +01:00
Emmanuel Cazenave 87c7468ab1 catch binascii.Error when decoding base64 (#39533) 2020-02-04 17:23:20 +01:00
Emmanuel Cazenave 5b788a5dff grab HTMLParser from six and adapt initialization to py3 (#39533) 2020-02-04 17:21:41 +01:00
Emmanuel Cazenave 37534c6980 use six types when calling isinstance() (#39533) 2020-02-04 17:19:16 +01:00
Emmanuel Cazenave 90bdb52e90 use python_2_unicode_compatible for objects representation (#39533) 2020-02-04 17:13:50 +01:00
Emmanuel Cazenave 090e4d2bc3 use force_text() instead of unicode() (#39533) 2020-02-04 17:09:09 +01:00
Emmanuel Cazenave 671afb17ec migration: use text instead of bytes (#39533) 2020-02-04 17:01:46 +01:00
Frédéric Péters 864bd92deb tox: limit to xmlschema < 1.1, for Python 2 compatibility 2020-01-24 09:44:34 +01:00
Michael Bideau a0ae081b74 Models: fixed url concatenation (removed '/' at the begining of the second part) 2019-12-05 21:31:40 +01:00
Michael Bideau 05a81aa993 Pylint: fixed 'keyword-arg-before-vararg' and module order issues 2019-10-29 18:26:56 +01:00
Michael Bideau 498a36bba3 Tests: fixed failing 'test_get_courrier_type' because of previous commit 2019-10-29 18:00:58 +01:00
Michael Bideau 1214526b1a Replaced courrier_type 'decision_non_opposition_DP' with 'decision_nom_opposition_sr' 2019-10-28 18:38:45 +01:00
Michael Bideau 6809c75d33 Make the connector more generic; Fixed urls and some pylint issues
Features
    * Added 'get_courrier_type' endpoint that return a 'courrier type' for a given type_dossier
    * Added url parameter 'type_dossier_detaille' to 'create_dossier' to post it in the request body
    * Replaced the way 'type fichier' is defined: now looks into 'XXX_type_raw' for file 'XXX'

Fixes
    * Url components are now encoded
    * Pylint warnings
    * Loging do not raise an error when 'files' var is empty in 'create_dossier'

Tests
    * Added 2 new errors tests to 'test_create_dossier'
    * Added 'test_get_courrier_type' to test endpoint 'get_courrier_type'
    * Fixed pylint warnings
2019-10-24 17:24:55 +02:00
Frédéric Péters 6197d8ae62 misc: fix debug log call to receive string as first parameter 2019-10-16 08:37:12 +02:00
Emmanuel Cazenave 7b5ec7f6fe jenkins: use ci@entrouvert.org for notifications 2019-10-02 14:09:52 +02:00
Michael Bideau 31ee9a8ea6 Tests: Refactoring: moving fixtures to conftest.py, added some fixture for ForwardFile and HttpRequest 2019-08-26 14:32:32 +00:00
Michael Bideau 38061d4593 Locales: added translations for 'fr' locale 2019-08-22 16:41:51 +00:00
Michael Bideau a739371cef Features: adding verbose name to all fields (mainly ForwardFile ones) 2019-08-22 16:41:28 +00:00
Michael Bideau a951f062f0 Refactoring: fix most of the (many) 'flake8' complaints 2019-08-22 16:02:06 +00:00
Michael Bideau 9df996e5ad Refactoring: fix all of the 'pylint' complaints for tests files (conftests, settings) 2019-08-22 15:13:27 +00:00
Michael Bideau 05280c153e License: prepended license text to all tests files 2019-08-22 14:51:04 +00:00
Michael Bideau afcca49f53 Refactoring: fix most of the (many many) 'pylint' complaints 2019-08-22 14:44:52 +00:00
Michael Bideau 2786bc29e7 License: prepended license text to most files 2019-08-21 15:02:33 +00:00
Michael Bideau c7e882c1e3 Resources: removed 'trac.ico' file (should not have been commited) 2019-08-21 14:51:04 +00:00
Michael Bideau 8474372bef Locales: cleaning extra 'fr' PO file (should not have been commited previously) 2019-08-21 14:39:57 +00:00
Michael Bideau 35fe3e7411 Setup.py: added locales compilation; Locales: added 'fr' PO file; Fixes: semantics and typos 2019-08-21 14:22:35 +00:00
Michael Bideau 910fc8ad57 Tests: set 'now' to a time when 'guichet' is open in 'test_openads_create_dossier' (to prevent failure when running test when 'guichet' is closed) 2019-08-21 08:54:50 +00:00
Michael Bideau 990f1fb7bc Added 'guichet' (planned availability), added CRUD views for each entity, many fixes and refactoring
Features:
    * A connector now can be associated with 'collectivites',
      and each of them can have one 'guichet'.
      A 'collectivite' have a name and an openADS technical identifier
      A 'guichet' allow to define hours and days for when its 'collectivite' is "open"
    * Each of those entities have a view to CRUD it

    * For entity ForwardFile:
       - Added association with a connector, and eventually a 'collectivite'
       - Added ForwardFiles 'size' field
       - Added updating fields 'content_type', 'file_hash' and 'size' on save()
       - Added custom validation on save()

    * For entity AtrealOpenads:
       - Added permissions on each endpoint
       - Added 'email' field support for each type of 'demandeur'
       - 'numero_dossier' is now required in the url for some endpoints (previously was a GET param)
       - Added 'upload_user_files' as an endpoint (but can still be used as a method with request=None)
       - The 'upload_user_files()' method now only handle forward file that have status='pending'

Fixes:
    * Added "*args" and "**kwargs" arguments to some connector endpoint methods
    * Added 'verbose_name' and 'ordering' on each entity META
    * Added decorator '@force_encoded_string_output' to prevent utf-8 issues with python2
    * Added __repr__, __str__ and __unicode__ functions to each entities
    * Added database indexes for each entity
    * Commented out useless JSON schema imports
    * Removed unused variable assignations

Refactoring:
    * Moved utilities functions to utils.py file
    * Added a BaseModel to provide some default functions for Models
    * Added enum/translations of hard-coded values for ForwardFile 'upload_status' field

Tests:
    * Added test for each entity
    * Added tests files specific to utilities, forms and views
    * Total code coverage is 99% with only 10 statement missed
2019-08-20 17:00:12 +00:00
Michael Bideau e8de2e66e8 JSON schemas: removed __main__ part 2019-08-20 16:23:42 +00:00
Michael Bideau 73669b0f33 JSON schemas: fixed a typo ('Un particulier' instead of 'Une personne physique') 2019-08-19 16:43:25 +00:00
Michael Bideau 4fc61d5f5e Added 'lettre_type' param to 'get_courrier()' endpoint 2019-07-29 14:35:56 +02:00
Michael Bideau d4080dae85 Added 'collectivite' param to 'create_dossier()' endpoint, removed useless '*args' and '**kwargs' 2019-07-29 14:30:50 +02:00
Michael Bideau 98cd089254 100% test coverage, dict strings are truncated when dumped, error messages homogeneized, and more
Features:
    * replaced the loging of json payload with the use of a DictDumper that lazy truncate strings too long
    * homogenize error messages

Fixes:
    * changed the signature of 'check_file_dict()' to match other functions and fix a bug
    * changed the signature of 'upload2ForwardFile()' to force input for 'type_fichier' argument

Refactoring:
    * removed dead code in 'upload_user_files()'
    * using 'basestring' instead of testing for 'str' and 'unicode'
    * renamed 'requerant' by 'demandeur'
    * removed useless and maybe problematic 'join()' (forgotten from the previous commit)
    * added more comments

Tests:
    * 100% test coverage!
    * fixed failing tests
    * added tests for every function
    * completed missing tests (mostly for exceptions)
    * added more comments
    * added the lines of missing statement in the coverage report
2019-07-25 14:29:06 +02:00
Michael Bideau 571316fcf4 JSON Schema input validation enabled (again), utf-8 decode error fixed, and more
Feature:
    * JSON Schema input validation enabled (again)

Fixes:
    * utf-8 decode error fixed: added unicode to litterals
    * removed useless and maybe problematic 'str()' forced casting
    * remove useless and maybe problematic 'join()' on list of file ids

Refactoring:
    * property 'extra_debug_enabled' removed (not used since some commits)
    * in function 'normalize()' only cast to 'unicode' if value is not already 'unicode'
2019-07-23 15:51:29 +02:00
Michael Bideau 6e709a0448 JSON Schema fixed, commented and updated with 'qualite' conditions on 'denomination' and 'raison_sociale' 2019-07-23 15:44:13 +02:00
Michael Bideau 6b4106ae25 Removed JSON schema validation, Added support for 'mandataire' and 'pouvoir_mandat', fixed bugs 2019-07-22 20:21:09 +02:00
Michael Bideau 4eddc1d502 Merge branch 'master' of ssh://git.entrouvert.org/passerelle-atreal-openads 2019-07-22 17:49:03 +02:00
Michael Bideau 719687287c Fix: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 11: ordinal not in range(128) 2019-07-22 17:41:00 +02:00
Thomas NOËL 8231e1465b debian: add settings.d default values 2019-07-22 13:16:31 +02:00
Michael Bideau 62dae769d6 Refactoring: remove 'extra_debug' field and replaced all 'self.debug' calls by 'self.logger.debug' 2019-07-18 22:54:50 +02:00
Michael Bideau 02f4a071fc Use HTTPResource, JSON schema for inputs, JSON lazy logging, added ForwardFile.attempt, and more
Features:
    * class AtrealOpenads now extends HTTPResource for HTTP Basic credentials
    * check_status is now also an endpoint (endpoint 'test_openads_connexion' deleted)
    * added JSON schema to validate POST request input (ouput schemas are defined too but unused for now)
    * added class 'LogJsonPayloadWithFileContent' to lazy log a json payload with content file filtered
    * added 'attempt' field to class 'ForwardFile' that count the attempt of uploading to openADS.API
    * added more controls over response data received

Refactoring:
    * removed the file content in function 'get_fwd_files_status()' and added content size instead
    * splitted the function 'get_fwd_files_status()' in two: one that retrieve detailed files, one only the summary
    * added function 'log_json_payload()' to help to log json payloads
    * added 2 functions to factorize the process of getting files from json payload
    * added function 'check_file_dict()' to factorize the process of checking a file dictionary

Fixes:
    * Default filename are now under 50 chars
    * Make the function 'get_fwd_files_status()' consistent in its return

Tests:
    * updated the test to reflect the use of HTTPResource and the split of 'get_fwd_files_status()'

More:
    * Added a lot of comments
    * Added endpoint anotation to validate response body, but its commented as the 'get' helper is not defined (not like the 'post' one)
2019-07-18 21:47:38 +02:00
Michael Bideau 85e815f72b Rebase from 'remote/origin' 2019-07-16 11:41:02 +02:00
Michael Bideau 8593779954 Added testing with tox, added AGPLv3 license, replaced namespace, and more
Packaging:
    * added author, description, classifiers, scripts and requirements in 'setup.py'

Tests:
    * added support for 'tox.ini'
    * moved 'tests' directory outside main python module

Fixes:
    * namespace is 'atreal_openads' instead of 'passerelle.apps.atreal_openads'
    * increased timeout removed from 'get' requests
    * fixed timeout typo on 'self.openADS_API_timeout'
2019-07-16 11:27:19 +02:00
Thomas NOËL 3a2d9eee6a .gitignore: exclude coverage and tests results 2019-07-15 18:41:01 +02:00
Thomas NOËL 5b2fa9d6d0 ensure tox.ini compatibility with Jenkinsfile 2019-07-15 18:23:40 +02:00
Thomas NOËL 2646ab4ee7 add tests system, via tox 2019-07-15 18:06:38 +02:00
Michael Bideau 18e57caf99 Features: added a 1h timeout to every requests 2019-07-15 13:14:38 +02:00
48 changed files with 7335 additions and 867 deletions

22
.coveragerc Normal file
View File

@ -0,0 +1,22 @@
; This file is part of passerelle-atreal-openads - a Publik connector to openADS
;
; Copyright (C) 2019 Atreal
;
; This program is free software: you can redistribute it and/or modify it
; under the terms of the GNU Affero General Public License as published
; by the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU Affero General Public License for more details.
;
; You should have received a copy of the GNU Affero General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
[run]
omit = */south_migrations/*
[report]
show_missing = True

2
.flake8 Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length = 100

26
.gitignore vendored
View File

@ -1,4 +1,30 @@
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
*.egg-info
*.pyc
*.swp
.coverage
/MANIFEST
/dist
/build
/.pytest_cache
/test*_results.xml
/coverage.xml
/htmlcov
/atreal_openads/locale/*/LC_MESSAGES/django.mo

408
.pylintrc Normal file
View File

@ -0,0 +1,408 @@
[MASTER]
# Specify a configuration file.
#rcfile=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Pickle collected data for later comparisons.
persistent=yes
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Use multiple processes to speed up Pylint.
jobs=1
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
# Allow optimization of some AST trees. This will activate a peephole AST
# optimizer, which will apply various small optimizations. For instance, it can
# be used to obtain the result of joining multiple strings with the addition
# operator. Joining a lot of strings can lead to a maximum recursion error in
# Pylint and this flag can prevent that. It has one side effect, the resulting
# AST will be different than the one from reality. This option is deprecated
# and it will be removed in Pylint 2.0.
optimize-ast=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
#disable=import-star-module-level,old-octal-literal,oct-method,print-statement,unpacking-in-except,parameter-unpacking,backtick,old-raise-syntax,old-ne-operator,long-suffix,dict-view-method,dict-iter-method,metaclass-assignment,next-method-called,raising-string,indexing-exception,raw_input-builtin,long-builtin,file-builtin,execfile-builtin,coerce-builtin,cmp-builtin,buffer-builtin,basestring-builtin,apply-builtin,filter-builtin-not-iterating,using-cmp-argument,useless-suppression,range-builtin-not-iterating,suppressed-message,no-absolute-import,old-division,cmp-method,reload-builtin,zip-builtin-not-iterating,intern-builtin,unichr-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,input-builtin,round-builtin,hex-method,nonzero-method,map-builtin-not-iterating
disable=import-star-module-level,old-octal-literal,oct-method,print-statement,unpacking-in-except,parameter-unpacking,backtick,old-raise-syntax,old-ne-operator,long-suffix,dict-view-method,dict-iter-method,metaclass-assignment,next-method-called,raising-string,indexing-exception,raw_input-builtin,long-builtin,file-builtin,execfile-builtin,coerce-builtin,cmp-builtin,buffer-builtin,basestring-builtin,apply-builtin,filter-builtin-not-iterating,using-cmp-argument,useless-suppression,range-builtin-not-iterating,suppressed-message,no-absolute-import,old-division,cmp-method,reload-builtin,zip-builtin-not-iterating,intern-builtin,unichr-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,input-builtin,round-builtin,hex-method,nonzero-method,map-builtin-not-iterating
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Put messages in a separate file for each module / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]". This option is deprecated
# and it will be removed in Pylint 2.0.
files-output=no
# Tells whether to display a full report or only the messages
reports=yes
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
[BASIC]
# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,ex,Run,_
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty
# Regular expression matching correct function names
function-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for function names
function-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct variable names
variable-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for variable names
variable-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct constant names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression matching correct attribute names
attr-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for attribute names
attr-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for argument names
argument-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct class attribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
# Regular expression matching correct class names
class-rgx=[A-Z_][a-zA-Z0-9]+$
# Naming hint for class names
class-name-hint=[A-Z_][a-zA-Z0-9]+$
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression matching correct method names
method-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for method names
method-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
[ELIF]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=4
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
[TYPECHECK]
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=(_+[a-zA-Z0-9]*?$)|dummy
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,future.builtins
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=100
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator
# Maximum number of lines in a module
max-module-lines=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of statements in function / method body
max-statements=50
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of boolean expressions in a if statement
max-bool-expr=5
[IMPORTS]
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=regsub,TERMIOS,Bastion,rexec
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception

53
Jenkinsfile vendored
View File

@ -1,15 +1,58 @@
@Library('eo-jenkins-lib@master') import eo.Utils
/**
* This file is part of passerelle-atreal-openads - a Publik connector to openADS
*
* Copyright (C) 2019 Atreal
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@Library('eo-jenkins-lib@main') import eo.Utils
pipeline {
agent any
stages {
stage('Unit Tests') {
steps {
sh 'tox -rv'
}
post {
always {
script {
utils = new Utils()
utils.publish_coverage('coverage.xml')
utils.publish_coverage_native('index.html')
utils.publish_pylint('pylint.out')
}
mergeJunitResults()
}
}
}
stage('Packaging') {
steps {
script {
if (env.JOB_NAME == 'passerelle-atreal-openads' && env.GIT_BRANCH == 'origin/master') {
sh 'sudo -H -u eobuilder /usr/local/bin/eobuilder passerelle-atreal-openads'
env.SHORT_JOB_NAME=sh(
returnStdout: true,
// given JOB_NAME=gitea/project/PR-46, returns project
// given JOB_NAME=project/main, returns project
script: '''
echo "${JOB_NAME}" | sed "s/gitea\\///" | awk -F/ '{print $1}'
'''
).trim()
if (env.GIT_BRANCH == 'main' || env.GIT_BRANCH == 'origin/main') {
sh "sudo -H -u eobuilder /usr/local/bin/eobuilder ${SHORT_JOB_NAME}"
} else if (env.GIT_BRANCH.startsWith('hotfix/')) {
sh "sudo -H -u eobuilder /usr/local/bin/eobuilder -d stretch --branch ${env.GIT_BRANCH} --hotfix passerelle-atreal-openads"
sh "sudo -H -u eobuilder /usr/local/bin/eobuilder --branch ${env.GIT_BRANCH} --hotfix ${SHORT_JOB_NAME}"
}
}
}
@ -19,7 +62,7 @@ pipeline {
always {
script {
utils = new Utils()
utils.mail_notify(currentBuild, env, 'admin+jenkins-passerelle-atreal-openads@entrouvert.com')
utils.mail_notify(currentBuild, env, 'ci+jenkins-passerelle-atreal-openads@entrouvert.org')
}
}
success {

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@ -1,3 +1,4 @@
include README
include MANIFEST.in
include VERSION
include LICENSE

21
README
View File

@ -4,10 +4,8 @@ Passerelle connector to openADS
Installation
------------
- create a symbolik link from this module to the passerelle 'apps' directory
- add to Passerelle installed apps settings:
INSTALLED_APPS += ('passerelle.apps.atreal_openads',)
INSTALLED_APPS += ('atreal_openads',)
Usage
@ -69,3 +67,20 @@ Usage in w.c.s.
Response type : JSON
Identifier : wscourrier
License
-------
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.

88
atreal_openads/forms.py Normal file
View File

@ -0,0 +1,88 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Forms for each of the Models."""
from django.forms import ModelForm
from .models import ForwardFile, Collectivite, Guichet
class ForwardFileForm(ModelForm):
"""Form for the ForwardFile model."""
class Meta:
# pylint: disable=too-few-public-methods,no-init,old-style-class,missing-docstring
model = ForwardFile
exclude = ['connecteur', 'size', 'file_hash']
def __init__(self, *args, **kwargs):
connecteur = kwargs.pop('connecteur', None)
collectivite = kwargs.pop('collectivite', None)
super(ForwardFileForm, self).__init__(*args, **kwargs)
if ((not hasattr(self.instance, 'connecteur') or not self.instance.connecteur)
and connecteur):
self.instance.connecteur = connecteur
if ((not hasattr(self.instance, 'collectivite') or not self.instance.collectivite)
and collectivite):
self.instance.collectivite = collectivite
# only allow to select a 'collectivite' that belongs to the connecteur
if hasattr(self.instance, 'connecteur') and self.instance.connecteur:
# pylint: disable=no-member
self.fields['collectivite'].queryset = Collectivite.objects.filter(
connecteur=self.instance.connecteur)
# TODO if the status is 'uploading' make everything read-only
class CollectiviteForm(ModelForm):
"""Form for the Collectivite model."""
class Meta:
# pylint: disable=too-few-public-methods,no-init,old-style-class,missing-docstring
model = Collectivite
exclude = ['connecteur']
def __init__(self, *args, **kwargs):
connecteur = kwargs.pop('connecteur', None)
super(CollectiviteForm, self).__init__(*args, **kwargs)
if ((not hasattr(self.instance, 'connecteur') or not self.instance.connecteur)
and connecteur):
self.instance.connecteur = connecteur
class GuichetForm(ModelForm):
"""Form for the Guichet model."""
class Meta:
# pylint: disable=too-few-public-methods,no-init,old-style-class,missing-docstring
model = Guichet
exclude = ['collectivite']
def __init__(self, *args, **kwargs):
collectivite = kwargs.pop('collectivite', None)
super(GuichetForm, self).__init__(*args, **kwargs)
if ((not hasattr(self.instance, 'collectivite') or not self.instance.collectivite)
and collectivite):
self.instance.collectivite = collectivite

View File

@ -0,0 +1,405 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""JSON schemas used by endpoints to validate input/ouput."""
# TODO add string limits (maxLength)
JSON_SCHEMA_FILE = {
"description": "A file object",
"$id": "#file",
"type": "object",
"properties": {
"content": {"type": "string"},
"content_type": {"type": ["string", "null"]},
"filename": {"type": "string"}
},
"required": ["content", "filename"]
}
JSON_SCHEMA_FILE_B64 = {
"description": "A file object encoded in base64",
"$id": "#file",
"type": "object",
"properties": {
"b64_content": {"type": "string"},
"content_type": {"type": ["string", "null"]},
"filename": {"type": "string"}
},
"required": ["b64_content", "filename"]
}
JSON_SCHEMA_DATE_FRENCH = {
"type": "string",
# pylint: disable=anomalous-backslash-in-string
"pattern": "^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}$" # noqa: W605
}
JSON_SCHEMA_CHECK_STATUS_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of an openADS 'connexion' test",
"type": "object",
"properties": {
"response": {"type": "integer"}
},
"required": ["response"]
}
JSON_SCHEMA_CREATE_DOSSIER_IN = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Incoming request to create a 'dossier' in openADS.API",
"definitions": {
"refs-cadastrales": {
"description": "The 3 items of a 'cadastrale' reference",
"$id": "#refs-cadastrales",
"type": "array",
"items": {
"type": "string"
},
"minItems": 3,
"maxItems": 3
},
"file": JSON_SCHEMA_FILE,
"file_plan_cadastral": {
"description": "A 'plan cadastral' document file",
"anyOf": [{"$ref": "#/definitions/file"}, {"type": "null"}]
}
},
"type": "object",
"properties": {
"fields": {
"type": "object",
"properties": {
"cerfa": {
"description": "A 'CERFA' PDF document file",
"type": "object",
"allOf": [{"$ref": "#/definitions/file"}]
},
"plan_cadastral_1": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_2": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_3": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_4": {"$ref": "#/definitions/file_plan_cadastral"},
"plan_cadastral_5": {"$ref": "#/definitions/file_plan_cadastral"},
"terrain_numero_voie": {"type": "string"},
"terrain_nom_voie": {"type": "string"},
"terrain_code_postal": {"type": "string"},
"terrain_localite": {"type": "string"},
"terrain_lieu_dit": {"type": ["string", "null"]},
"reference_cadastrale": {
"description": "A list of 'cadastrales' references",
"type": "array",
"items": {"$ref": "#/definitions/refs-cadastrales"}
},
"autres_parcelles": {
"type": "boolean"
},
"references_cadastrales": {
"description": "A list of 'cadastrales' references",
# conditionaly required and typed below
},
"proprietaire": {"enum": ["Oui", "Non"]},
"qualite": {"type": "string"},
"denomination": {}, # conditionaly required and typed below
"raison_sociale": {}, # conditionaly required and typed below
"nom": {"type": "string"},
"prenom": {"type": "string"},
"numero_voie": {"type": "string"},
"nom_voie": {"type": "string"},
"code_postal": {"type": "string"},
"localite": {"type": "string"},
"lieu_dit": {"type": ["string", "null"]},
"mandataire_nom": {}, # conditionaly required and typed below
"mandataire_prenom": {}, # conditionaly required and typed below
"mandataire_numero_voie": {}, # conditionaly required and typed below
"mandataire_nom_voie": {}, # conditionaly required and typed below
"mandataire_code_postal": {}, # conditionaly required and typed below
"mandataire_localite": {}, # conditionaly required and typed below
"mandataire_lieu_dit": {} # conditionaly required and typed below
},
# requirements
"required": [
"cerfa",
"terrain_numero_voie",
"terrain_nom_voie",
"terrain_code_postal",
"terrain_localite",
"reference_cadastrale",
#"proprietaire",
"qualite",
"nom",
"prenom",
"numero_voie",
"nom_voie",
"code_postal",
"localite"
],
# conditional requirements
"allOf": [
{
# qualite
"anyOf": [
# if qualite == "Un particulier"
# "denomination" and "raison_sociale" are not required
# and must be null
{
"properties": {
"qualite": {"const": "Un particulier"},
"denomination": {"type": "null"},
"raison_sociale": {"type": "null"}
}
},
# if qualite == "Une personne morale"
# "denomination" and "raison_sociale" are required
# and must be string
{
"properties": {
"qualite": {"const": "Une personne morale"},
"denomination": {"type": "string"},
"raison_sociale": {"type": "string"}
},
"required": ["denomination", "raison_sociale"]
}
]
},
{
# proprietaire
"anyOf": [
# if proprietaire == "Oui"
# all the mandataire fields are not required
# and must be null
{
"properties": {
"proprietaire": {"const": "Oui"},
"mandataire_nom": {"type": "null"},
"mandataire_prenom": {"type": "null"},
"mandataire_numero_voie": {"type": "null"},
"mandataire_nom_voie": {"type": "null"},
"mandataire_code_postal": {"type": "null"},
"mandataire_localite": {"type": "null"},
"mandataire_lieu_dit": {"type": "null"}
}
},
# if proprietaire == "Non"
# all the mandataire fields are required (except the lieu_dit)
# and must be string
# and conditions are checked against mandataire_qualite
{
"properties": {
"proprietaire": {"const": "Non"},
"mandataire_nom": {"type": "string"},
"mandataire_prenom": {"type": "string"},
"mandataire_numero_voie": {"type": "string"},
"mandataire_nom_voie": {"type": "string"},
"mandataire_code_postal": {"type": "string"},
"mandataire_localite": {"type": "string"},
"mandataire_qualite": {"type": "string"},
"mandataire_lieu_dit": {"type": ["string", "null"]}
},
"required": [
"mandataire_nom",
"mandataire_prenom",
"mandataire_numero_voie",
"mandataire_nom_voie",
"mandataire_code_postal",
"mandataire_localite",
"mandataire_qualite"
],
# mandataire_qualite
"anyOf": [
# if mandataire_qualite == "Un particulier"
# "mandataire_denomination" and "mandataire_raison_sociale"
# are not required and must be null
{
"properties": {
"mandataire_qualite": {"const": "Un particulier"},
"mandataire_denomination": {"type": "null"},
"mandataire_raison_sociale": {"type": "null"}
}
},
# if mandataire_qualite == "Une personne morale"
# "mandataire_denomination" and "mandataire_raison_sociale"
# are required and must be string
{
"properties": {
"mandataire_qualite": {"const": "Une personne morale"},
"mandataire_denomination": {"type": "string"},
"mandataire_raison_sociale": {"type": "string"}
},
"required": [
"mandataire_denomination",
"mandataire_raison_sociale"
]
}
]
}
]
},
{
# autres_parcelles
"anyOf": [
# if autres_parcelles == False
# "references_cadastrales" is not required
# and must be null
{
"properties": {
"autres_parcelles": {"const": False},
"references_cadastrales": {"type": "null"}
}
},
# if autres_parcelles == True
# "references_cadastrales" is required
# and must be of type "array" of "refs-cadastrales"
{
"properties": {
"autres_parcelles": {"const": True},
"references_cadastrales": {
"type": "array",
"items": {"$ref": "#/definitions/refs-cadastrales"}
}
},
"required": ["autres_parcelles", "references_cadastrales"]
}
]
}
]
}
},
"required": ["fields"]
}
JSON_SCHEMA_CREATE_DOSSIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of a 'dossier' creation in openADS.API",
"type": "object",
"properties": {
"numero_dossier": {"type": "string"},
"recepisse": JSON_SCHEMA_FILE_B64
},
"required": ["numero_dossier", "recepisse"]
}
JSON_SCHEMA_GET_DOSSIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of a 'dossier' creation in openADS.API",
"type": "object",
"properties": {
"etat": {"type": "string"},
"date_depot": JSON_SCHEMA_DATE_FRENCH,
"date_decision": JSON_SCHEMA_DATE_FRENCH,
"date_limite_instruction": JSON_SCHEMA_DATE_FRENCH,
"decision": {"type": "string"}
},
"required": [
"etat",
"date_depot",
"date_decision",
"date_limite_instruction",
"decision"
]
}
JSON_SCHEMA_FORWARDFILE = {
"description": "A ForwardFile object (PDF document that must be forwarded to openADS)",
"$id": "#forwardfile",
"type": "object",
"properties": {
"id": {"type": "integer"},
"numero_demande": {"type": "string"},
"numero_dossier": {"type": "string"},
"type_fichier": {"type": "string"},
"file_hash": {"type": "string"},
"orig_filename": {"type": "string"},
"content_type": {"type": "string"},
"upload_status": {"type": "string"},
"upload_attempt": {"type": "integer"},
"upload_msg": {"type": "string"},
"content_size": {"type": "integer"},
"last_update_datetime": {"type": "string", "format": "date-time"}
},
"required": [
"id",
"numero_demande",
"numero_dossier",
"type_fichier",
"file_hash",
"orig_filename",
"content_type",
"upload_status",
"upload_attempt",
"upload_msg",
"content_size",
"last_update_datetime"
]
}
JSON_SCHEMA_GET_FWD_FILES_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of a request about the forwarding (detailled) of user files to openADS",
"type": "array",
"items": {"$ref": "#/definitions/forwardfile"},
"definitions": {
"forwardfile": JSON_SCHEMA_FORWARDFILE
}
}
JSON_SCHEMA_GET_FWD_FILE_STATUS = {
"description": "The status of a ForwardFile",
"$id": "#forwardfile-status",
"type": "string",
# pylint: disable=anomalous-backslash-in-string
"pattern": "^\[\w+\] .+ => .+$" # noqa: W605
}
JSON_SCHEMA_GET_FWD_FILES_STATUS_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of a request about the forwarding (summarized) of user files to openADS",
"type": "object",
"properties": {
"all_forwarded": {"type": "boolean"},
"pending": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"uploading": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"success": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}},
"failed": {"type": "array", "items": {"$ref": "#/definitions/forwardfile-status"}}
},
"required": ["all_forwarded", "pending", "uploading", "success", "failed"],
"definitions": {
"forwardfile-status": JSON_SCHEMA_GET_FWD_FILE_STATUS
}
}
JSON_SCHEMA_GET_COURRIER_OUT = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response of a 'courrier' from an openADS 'dossier'",
"type": "object",
"properties": {
"courrier": JSON_SCHEMA_FILE_B64
},
"required": ["courrier"]
}

View File

@ -0,0 +1,460 @@
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-08-22 18:31+0200\n"
"PO-Revision-Date: 2019-08-22 16:34+0000\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: fr_FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.11\n"
"X-Poedit-Basepath: ../../../..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-SearchPath-0: .\n"
#: atreal_openads/models.py:70
msgid "Pending"
msgstr "En attente"
#: atreal_openads/models.py:71
msgid "Uploading"
msgstr "Téléchargement"
#: atreal_openads/models.py:72
msgid "Failed"
msgstr "Échoué"
#: atreal_openads/models.py:73
msgid "Success"
msgstr "Succès"
#: atreal_openads/models.py:84
msgid "Tracking code"
msgstr "Numéro de demande"
#: atreal_openads/models.py:85
msgid "Numero dossier"
msgstr "Numéro de dossier"
#: atreal_openads/models.py:86
msgid "Type"
msgstr "Type"
#: atreal_openads/models.py:87
msgid "Hash"
msgstr "Hash"
#: atreal_openads/models.py:88
msgid "Filename"
msgstr "Nom"
#: atreal_openads/models.py:89
msgid "Content type"
msgstr "Content type"
#: atreal_openads/models.py:90
msgid "Size"
msgstr "Taille"
#: atreal_openads/models.py:91
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:61
msgid "File"
msgstr "Fichier"
#: atreal_openads/models.py:92
msgid "Upload attempt"
msgstr "Tentatives de téléchargement"
#: atreal_openads/models.py:93
msgid "Upload status"
msgstr "Statut de téléchargement"
#: atreal_openads/models.py:95
msgid "Upload message"
msgstr "Message de téléchargement"
#: atreal_openads/models.py:96
msgid "Last update"
msgstr "Dernière mise à jour"
#: atreal_openads/models.py:100
msgid "Forward File"
msgstr "Fichier transféré"
#: atreal_openads/models.py:190
#, python-format
msgid "A %(object)s cannot have all the following fields empty: %(fields)s."
msgstr ""
"Un %(object)s ne peut pas avoir tous les champs suivants vides: %(fields)s."
#: atreal_openads/models.py:200
msgid "Name"
msgstr "Nom"
#: atreal_openads/models.py:205
msgid "openADS identifier"
msgstr "identifiant openADS"
#: atreal_openads/models.py:205 atreal_openads/models.py:368
msgid "ex: 3"
msgstr "ex: 3"
#: atreal_openads/models.py:212
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:54
msgid "Collectivite"
msgstr "Collectivité"
#: atreal_openads/models.py:271
msgid "Monday"
msgstr "Lundi"
#: atreal_openads/models.py:272
msgid "Tuesday"
msgstr "Mardi"
#: atreal_openads/models.py:273
msgid "Wednesday"
msgstr "Mercredi"
#: atreal_openads/models.py:274
msgid "Thursday"
msgstr "Jeudi"
#: atreal_openads/models.py:275
msgid "Friday"
msgstr "Vendredi"
#: atreal_openads/models.py:276
msgid "Saturday"
msgstr "Samedi"
#: atreal_openads/models.py:277
msgid "Sunday"
msgstr "Dimanche"
#: atreal_openads/models.py:283
msgid "Hour of opening (each day)"
msgstr "Heure d'ouverture (chaque jour)"
#: atreal_openads/models.py:283 atreal_openads/models.py:292
msgid "ex: 08:30"
msgstr "ex: 08:30"
#: atreal_openads/models.py:284
msgid "Hour of closing (each day)"
msgstr "Heure de fermeture (chaque jour)"
#: atreal_openads/models.py:284
msgid "ex: 17:00"
msgstr "ex: 17:00"
#: atreal_openads/models.py:285
msgid "Day of opening (each week)"
msgstr "Jour d'ouverture (chaque semaine)"
#: atreal_openads/models.py:286
msgid "ex: Lundi"
msgstr "ex: Lundi"
#: atreal_openads/models.py:288
msgid "Day of closing (each week)"
msgstr "Jour de fermeture (chaque semaine)"
#: atreal_openads/models.py:289
msgid "ex: Samedi"
msgstr "ex: Samedi"
#: atreal_openads/models.py:291
msgid "Hour of opening (on opening day)"
msgstr "Heure d'ouverture (le jour d'ouverture)"
#: atreal_openads/models.py:293
msgid "Hour of closing (on closing day)"
msgstr "Heure de fermeture (le jour de fermeture)"
#: atreal_openads/models.py:294
msgid "ex: 12:15"
msgstr "ex: 12:15"
#: atreal_openads/models.py:298
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:53
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:56
msgid "Guichet"
msgstr "Guichet"
#: atreal_openads/models.py:299
msgid "Guichets"
msgstr "Guichets"
#: atreal_openads/models.py:367
msgid "Default 'collectivite' (identifier in openADS)"
msgstr "Collectivité par défaut (identifiant openADS)"
#: atreal_openads/models.py:370
msgid "openADS API URL"
msgstr "URL de l'API openADS"
#: atreal_openads/models.py:371
msgid "ex: https://openads.your_domain.net/api/"
msgstr "ex: https://openads.votre_domaine.net/api/"
#: atreal_openads/models.py:377
msgid "This API provides exchanges with openADS."
msgstr "Cette API fournis une passerelle vers openADS."
#: atreal_openads/models.py:379
msgid "Business Process Connectors"
msgstr "Connecteurs Processus Métiers"
#: atreal_openads/models.py:383 atreal_openads/models.py:384
msgid "openADS"
msgstr "openADS"
#: atreal_openads/models.py:503
msgid "Test an openADS 'connexion'"
msgstr "Teste une connexion openADS"
#: atreal_openads/models.py:527 atreal_openads/models.py:853
#: atreal_openads/models.py:1012 atreal_openads/models.py:1101
msgid "Type of 'dossier'"
msgstr "Type de dossier"
#: atreal_openads/models.py:529
msgid "Use this collectivite (instead of the default one)"
msgstr "Utiliser cette collectivité (à la place de celle par défaut)"
#: atreal_openads/models.py:536
msgid "Create an openADS 'dossier'"
msgstr "Créer un dossier openADS"
#: atreal_openads/models.py:592
#, python-format
msgid "Guichet closed for collectivite '%s'"
msgstr "Le guichet est fermé pour la collectivité '%s'"
#: atreal_openads/models.py:848
msgid "Get informations about an openADS 'dossier'"
msgstr "Obtenir des informations sur un dossier openADS"
#: atreal_openads/models.py:854 atreal_openads/models.py:899
#: atreal_openads/models.py:962 atreal_openads/models.py:1013
#: atreal_openads/models.py:1102
msgid "Identifier for 'dossier'"
msgstr "Identifiant du dossier"
#: atreal_openads/models.py:895
msgid "Get informations about the forwarding of user files to openADS"
msgstr ""
"Obtenir des informations sur le transfers des fichiers utilisateur vers "
"openADS"
#: atreal_openads/models.py:901 atreal_openads/models.py:964
msgid "File identifier"
msgstr "Identifiant fichier"
#: atreal_openads/models.py:958
msgid "Get informations about the forwarding of a user file to openADS"
msgstr ""
"Obtenir des informations sur le transfers d'un fichier utilisateur vers "
"openADS"
#: atreal_openads/models.py:1008
msgid "Get a 'courrier' from an openADS 'dossier'"
msgstr "Obtenir un courrier d'un dossier openADS"
#: atreal_openads/models.py:1015
msgid "Courrier ID to get"
msgstr "ID du courrier à obtenir"
#: atreal_openads/models.py:1096
msgid "Trigger the uploading of user's files to openADS"
msgstr "Délenche le transfers des fichiers utilisateurs vers openADS"
#: atreal_openads/templates/atreal_openads/manage/collectivite_form.html:34
#: atreal_openads/templates/atreal_openads/manage/guichet_form.html:35
msgid "New"
msgstr "Nouveau"
#: atreal_openads/templates/atreal_openads/manage/collectivite_form.html:46
#: atreal_openads/templates/atreal_openads/manage/forwardfile_form.html:47
#: atreal_openads/templates/atreal_openads/manage/guichet_form.html:47
msgid "Save"
msgstr "Enregistrer"
#: atreal_openads/templates/atreal_openads/manage/collectivite_form.html:47
#: atreal_openads/templates/atreal_openads/manage/forwardfile_form.html:48
#: atreal_openads/templates/atreal_openads/manage/guichet_form.html:48
msgid "Cancel"
msgstr "Annuler"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:37
msgid "Add a Collectivite"
msgstr "Ajouter une collectivité"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:49
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:45
msgid "Actions"
msgstr "Actions"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:54
msgid "Forward Files"
msgstr "Fichiers transférés"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:66
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:40
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:47
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:57
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:41
#: atreal_openads/templates/atreal_openads/manage/guichet_view.html:41
msgid "edit"
msgstr "éditer"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:67
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:37
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:44
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:58
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:38
#: atreal_openads/templates/atreal_openads/manage/guichet_view.html:38
msgid "delete"
msgstr "supprimer"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:77
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:79
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:60
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:67
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:71
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:58
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:65
msgid "None"
msgstr "Aucun(e)"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:79
msgid "forward file(s)"
msgstr "fichier(s) transféré(s)"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:93
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:86
msgid "first"
msgstr "première"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:94
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:87
msgid "previous"
msgstr "précédente"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:98
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:91
msgid "Page"
msgstr "Page"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:102
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:95
msgid "next"
msgstr "suivante"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:103
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:96
msgid "last"
msgstr "dernière"
#: atreal_openads/templates/atreal_openads/manage/collectivite_list.html:112
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:105
msgid "No data"
msgstr "Aucune donnée"
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:43
msgid "Add a Guichet"
msgstr "Ajouter un Guichet"
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:56
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:63
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:70
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:62
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:77
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:85
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:54
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:61
#: atreal_openads/templates/atreal_openads/manage/forwardfile_view.html:68
#: atreal_openads/templates/atreal_openads/manage/guichet_view.html:55
msgid ":"
msgstr ":"
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:69
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:84
msgid "Forward files"
msgstr "Fichiers transférés"
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:73
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:88
msgid "forward file"
msgstr "fichier transféré"
#: atreal_openads/templates/atreal_openads/manage/collectivite_view.html:74
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:89
msgid "forward files"
msgstr "fichiers transférés"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:32
msgid "since:"
msgstr "depuis:"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:32
msgid "Down"
msgstr "Hors service"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:38
msgid "availability check parameters"
msgstr "paramètres pour le test de disponibilité"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:41
msgid "logging parameters"
msgstr "paramètres pour l'identification"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:50
msgid "Add a collectivite"
msgstr "Ajouter une collectivité"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:61
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:66
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:76
msgid "Collectivites"
msgstr "Collectivités"
#: atreal_openads/templates/atreal_openads/manage/connector_view.html:78
msgid "collectivites"
msgstr "collectivités"
#: atreal_openads/templates/atreal_openads/manage/forwardfile_list.html:35
msgid "list"
msgstr "lister"
#~ msgid ""
#~ "Datetime (or string formatted to: '%s') against which the 'guichet' is "
#~ "checked for opening"
#~ msgstr ""
#~ "Date-heure (ou chaîne au format: '%s') à partir de laquelle sera testée "
#~ "l'ouverture du guichet"
#~ msgid "List of ForwardFile IDs to upload (coma separated)"
#~ msgstr ""
#~ "Liste des IDs des ForwardFile à transférer (séparés par une virgule)"

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-07-11 16:20
# Generated by Django 1.11.15 on 2019-04-30 12:07
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import passerelle.apps.atreal_openads.models
import atreal_openads.models
class Migration(migrations.Migration):
@ -11,7 +12,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
('base', '0013_delete_templatevar'),
('base', '0012_job'),
]
operations = [
@ -22,12 +23,11 @@ class Migration(migrations.Migration):
('title', models.CharField(max_length=50, verbose_name='Title')),
('description', models.TextField(verbose_name='Description')),
('slug', models.SlugField(unique=True, verbose_name='Identifier')),
('collectivite', models.CharField(blank=True, default=b'', help_text='ex: Marseille, or ex: 3', max_length=255, verbose_name='Collectivity (identifier)')),
('openADS_API_login', models.CharField(default=b'', help_text='ex: user1234', max_length=255, verbose_name='openADS API login')),
('openADS_API_password', models.CharField(default=b'', help_text='ex: ah9pGbKKHv5ToF3cPQuV', max_length=255, verbose_name='openADS API password')),
('openADS_API_url', models.URLField(default=b'', help_text='ex: https://openads.your_domain.net/api/', max_length=255, verbose_name='openADS API URL')),
('extra_debug', models.BooleanField(default=0, help_text='ex: True', verbose_name='Extra debug')),
('users', models.ManyToManyField(blank=True, related_name='_atrealopenads_users_+', related_query_name='+', to='base.ApiUser')),
('myjobs', django.contrib.postgres.fields.jsonb.JSONField(default={})),
('collectivite', models.CharField(blank=True, default='', help_text='ex: Marseille, ou ex: 3', max_length=255, verbose_name='Collectivity (identifier)')),
('openADS_API_key', models.CharField(default='', help_text='ex: ah9pGbKKHv5ToF3cPQuV', max_length=255, verbose_name='openADS API key (secret)')),
('openADS_API_url', models.URLField(default='', help_text='ex: https://openads.your_domain.net/api/', max_length=255, verbose_name='openADS API URL')),
('users', models.ManyToManyField(blank=True, to='base.ApiUser')),
],
options={
'verbose_name': 'openADS',
@ -40,12 +40,12 @@ class Migration(migrations.Migration):
('numero_demande', models.CharField(max_length=20)),
('numero_dossier', models.CharField(max_length=20)),
('type_fichier', models.CharField(max_length=10)),
('file_hash', models.CharField(blank=True, default=b'', max_length=100)),
('orig_filename', models.CharField(blank=True, default=b'', max_length=100)),
('content_type', models.CharField(blank=True, default=b'', max_length=100)),
('upload_file', models.FileField(null=True, upload_to=passerelle.apps.atreal_openads.models.get_upload_path)),
('upload_status', models.CharField(blank=True, default=b'', max_length=10)),
('upload_msg', models.CharField(blank=True, default=b'', max_length=255)),
('file_hash', models.CharField(blank=True, default='', max_length=100)),
('orig_filename', models.CharField(blank=True, default='', max_length=100)),
('content_type', models.CharField(blank=True, default='', max_length=100)),
('upload_file', models.FileField(null=True, upload_to=atreal_openads.models.get_upload_path)),
('upload_status', models.CharField(blank=True, default='', max_length=10)),
('upload_msg', models.CharField(blank=True, default='', max_length=255)),
('last_update_datetime', models.DateTimeField(auto_now=True)),
],
),

View File

@ -0,0 +1,241 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-04-15 08:41
from __future__ import unicode_literals
import atreal_openads.utils
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('atreal_openads', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Collectivite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, default='', max_length=150, verbose_name='Name')),
('openADS_id', models.PositiveIntegerField(help_text='ex: 3', verbose_name='openADS identifier')),
],
options={
'verbose_name': 'Collectivite',
'ordering': ['name'],
},
bases=(models.Model, atreal_openads.utils.BaseModel),
),
migrations.CreateModel(
name='Guichet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ouverture_jour_h', models.TimeField(help_text='ex: 08:30', verbose_name='Hour of opening (each day)')),
('fermeture_jour_h', models.TimeField(help_text='ex: 17:00', verbose_name='Hour of closing (each day)')),
('ouverture_sem_d', models.PositiveIntegerField(choices=[(1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday')], default=1, help_text='ex: Lundi', verbose_name='Day of opening (each week)')),
('fermeture_sem_d', models.PositiveIntegerField(choices=[(1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday')], default=6, help_text='ex: Samedi', verbose_name='Day of closing (each week)')),
('ouverture_sem_h', models.TimeField(help_text='ex: 08:30', verbose_name='Hour of opening (on opening day)')),
('fermeture_sem_h', models.TimeField(help_text='ex: 12:15', verbose_name='Hour of closing (on closing day)')),
],
options={
'verbose_name': 'Guichet',
'verbose_name_plural': 'Guichets',
'ordering': ['collectivite'],
},
bases=(models.Model, atreal_openads.utils.BaseModel),
),
migrations.AlterModelOptions(
name='atrealopenads',
options={'ordering': ['openADS_API_url'], 'verbose_name': 'openADS', 'verbose_name_plural': 'openADS'},
),
migrations.AlterModelOptions(
name='forwardfile',
options={'ordering': ['-last_update_datetime'], 'verbose_name': 'Forward File'},
),
migrations.RemoveField(
model_name='atrealopenads',
name='collectivite',
),
migrations.RemoveField(
model_name='atrealopenads',
name='myjobs',
),
migrations.RemoveField(
model_name='atrealopenads',
name='openADS_API_key',
),
migrations.AddField(
model_name='atrealopenads',
name='basic_auth_password',
field=models.CharField(blank=True, max_length=128, verbose_name='Basic authentication password'),
),
migrations.AddField(
model_name='atrealopenads',
name='basic_auth_username',
field=models.CharField(blank=True, max_length=128, verbose_name='Basic authentication username'),
),
migrations.AddField(
model_name='atrealopenads',
name='client_certificate',
field=models.FileField(blank=True, null=True, upload_to='', verbose_name='TLS client certificate'),
),
migrations.AddField(
model_name='atrealopenads',
name='default_collectivite_openADS_id',
field=models.PositiveIntegerField(blank=True, default=0, help_text='ex: 3', verbose_name="Default 'collectivite' (identifier in openADS)"),
),
migrations.AddField(
model_name='atrealopenads',
name='http_proxy',
field=models.CharField(blank=True, max_length=128, verbose_name='HTTP and HTTPS proxy'),
),
migrations.AddField(
model_name='atrealopenads',
name='trusted_certificate_authorities',
field=models.FileField(blank=True, null=True, upload_to='', verbose_name='TLS trusted CAs'),
),
migrations.AddField(
model_name='atrealopenads',
name='verify_cert',
field=models.BooleanField(default=True, verbose_name='TLS verify certificates'),
),
migrations.AddField(
model_name='forwardfile',
name='connecteur',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='forward_files', related_query_name='forward_file', to='atreal_openads.AtrealOpenads'),
preserve_default=False,
),
migrations.AddField(
model_name='forwardfile',
name='size',
field=models.PositiveIntegerField(default=0, verbose_name='Size'),
),
migrations.AddField(
model_name='forwardfile',
name='upload_attempt',
field=models.PositiveIntegerField(blank=True, default=0, verbose_name='Upload attempt'),
),
migrations.AlterField(
model_name='atrealopenads',
name='users',
field=models.ManyToManyField(blank=True, related_name='_atrealopenads_users_+', related_query_name='+', to='base.ApiUser'),
),
migrations.AlterField(
model_name='forwardfile',
name='content_type',
field=models.CharField(blank=True, default='', max_length=100, verbose_name='Content type'),
),
migrations.AlterField(
model_name='forwardfile',
name='file_hash',
field=models.CharField(blank=True, default='', max_length=100, verbose_name='Hash'),
),
migrations.AlterField(
model_name='forwardfile',
name='last_update_datetime',
field=models.DateTimeField(auto_now=True, verbose_name='Last update'),
),
migrations.AlterField(
model_name='forwardfile',
name='numero_demande',
field=models.CharField(max_length=20, verbose_name='Tracking code'),
),
migrations.AlterField(
model_name='forwardfile',
name='numero_dossier',
field=models.CharField(max_length=20, verbose_name='Numero dossier'),
),
migrations.AlterField(
model_name='forwardfile',
name='orig_filename',
field=models.CharField(blank=True, default='', max_length=100, verbose_name='Filename'),
),
migrations.AlterField(
model_name='forwardfile',
name='type_fichier',
field=models.CharField(max_length=10, verbose_name='Type'),
),
migrations.AlterField(
model_name='forwardfile',
name='upload_file',
field=models.FileField(blank=True, null=True, upload_to=atreal_openads.utils.get_upload_path, verbose_name='File'),
),
migrations.AlterField(
model_name='forwardfile',
name='upload_msg',
field=models.CharField(blank=True, default='', max_length=255, verbose_name='Upload message'),
),
migrations.AlterField(
model_name='forwardfile',
name='upload_status',
field=models.CharField(choices=[('pending', 'Pending'), ('uploading', 'Uploading'), ('failed', 'Failed'), ('success', 'Success')], default='pending', max_length=10, verbose_name='Upload status'),
),
migrations.AddField(
model_name='guichet',
name='collectivite',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='guichet', to='atreal_openads.Collectivite'),
),
migrations.AddField(
model_name='collectivite',
name='connecteur',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='collectivites', related_query_name='collectivite', to='atreal_openads.AtrealOpenads'),
),
migrations.AddField(
model_name='forwardfile',
name='collectivite',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='forward_files', related_query_name='forward_file', to='atreal_openads.Collectivite'),
),
migrations.AddIndex(
model_name='guichet',
index=models.Index(fields=['collectivite'], name='su_collectivite_idx'),
),
migrations.AddIndex(
model_name='collectivite',
index=models.Index(fields=['connecteur', 'openADS_id'], name='col_conn_openADSid_idx'),
),
migrations.AddIndex(
model_name='collectivite',
index=models.Index(fields=['connecteur'], name='col_connecteur_idx'),
),
migrations.AddIndex(
model_name='collectivite',
index=models.Index(fields=['openADS_id'], name='col_openADS_id_idx'),
),
migrations.AlterUniqueTogether(
name='collectivite',
unique_together=set([('connecteur', 'openADS_id')]),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['connecteur'], name='ff_connecteur_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['collectivite'], name='ff_collectivite_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['numero_demande', 'numero_dossier'], name='ff_deman_doss_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['numero_demande'], name='ff_demande_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['numero_dossier'], name='ff_dossier_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['orig_filename'], name='ff_filename_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['upload_status'], name='ff_status_idx'),
),
migrations.AddIndex(
model_name='forwardfile',
index=models.Index(fields=['last_update_datetime'], name='ff_last_up_dt_idx'),
),
]

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,28 @@
/**
* This file is part of passerelle-atreal-openads - a Publik connector to openADS
*
* Copyright (C) 2019 Atreal
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* overrides for atreal_openads */
div#header h1.breadcrumbs a:last-child {
display: inline-block;
}
.connecteur-collectivites .collectivite .service-urbanisme {
margin-left: 0.1em;
}

View File

@ -0,0 +1,52 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} - {% if object.id %}{{ object.connecteur }} - {{ object.name }}{% else %}{% trans 'New' %}{% endif %}</h2>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
<div id="form-content">
{% csrf_token %}
{{ form|with_template }}
</div>
{% block buttons %}
<div class="buttons">
<button class="submit-button">{% trans "Save" %}</button>
<button class="cancel">{% trans "Cancel" %}</button>
</div>
{% endblock %}
</form>
{% endblock %}

View File

@ -0,0 +1,118 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name_plural }}</h2>
<span class="actions">
{% if collectivite_add_url %}
<a rel="popup" href="{{ collectivite_add_url }}?back-to=list-collectivites">{% trans "Add a Collectivite" %}</a>
{% endif %}
</span>
{% endblock %}
{% block content %}
<table id="list-collectivite">
{% block list %}
{% if object_list %}
<thead>
<tr>
<th class="actions">{% trans "Actions" %}</th>
{% for field in view.model.get_fields %}
{% if field.name != "connecteur" %}
<th class="{{field.name}}">
{% if field.name == "guichet" %}{% trans "Guichet" %}
{% elif field.name == "forward_file" %}{% trans "Forward Files" %}
{% else %}{% trans field.verbose_name %}
{% endif %}
</th>
{% endif %}
{% endfor %}
</tr>
</thead>
<tbody>
{% for col in object_list %}
<tr>
<td class="actions">
<span class="edit-link" ><a rel="popup" href="{{col.get_edit_url}}?back-to=list-collectivites" >{% trans "edit" %}</a></span>
<span class="delete-link"><a rel="popup" href="{{col.get_delete_url}}?back-to=list-collectivites">{% trans "delete" %}</a></span>
</td>
{% for field, value in col.get_fields_kv %}
{% if field.name != "connecteur" %}
<td class="{{field.name}}">
{% if field.name != "guichet" and field.name != "name" and field.name != "forward_file" %}
{{value}}
{% elif field.name == "name" %}
<a href="{{col.get_absolute_url}}">{{value}}</a>
{% elif field.name == "guichet" %}
{% if value %}<a href="{{value.get_absolute_url}}">{{value}}</a>{% else %}{% trans "None" %}{% endif %}
{% elif field.name == "forward_file" %}
{% if value %}<a href="{{ col.get_absolute_url }}/list-forward-files">{{ value.count }} {% trans "forward file(s)" %}</a>{% else %}{% trans "None" %}{% endif %}
{% endif %}
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
{% if is_paginated %}
<tfoot>
<tr>
<td class="pagination" colspan="{{ view.model.get_fields|length }}">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">&laquo; {% trans "first" %}</a>
<a href="?page={{ contacts.previous_page_number }}">{% trans "previous" %}</a>
{% endif %}
<span class="current">
{% trans "Page" %} {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">{% trans "next" %}</a>
<a href="?page={{ page_obj.paginator.num_pages }}">{% trans "last" %} &raquo;</a>
{% endif %}
</span>
<td>
</tr>
</tfoot>
{% endif %}
{% else %}
<tr class="nodata">
<td>{% trans "No data" %}</td>
</tr>
{% endif %}
{% endblock %}
</table>
{% endblock %}

View File

@ -0,0 +1,82 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }}{% if object.name %} - {{ object.name }}{% endif %}</h2>
<span class="actions">
{% if object|can_delete:request.user %}
<a rel="popup" href="{{ object.get_delete_url }}">{% trans "delete" %}</a>
{% endif %}
{% if object|can_edit:request.user %}
<a rel="popup" href="{{ object.get_edit_url }}">{% trans "edit" %}</a>
{% endif %}
{% if not object.guichet and object|can_edit:request.user and guichet_add_url %}
<a rel="popup" href="{{ guichet_add_url }}">{% trans "Add a Guichet" %}</a>
{% endif %}
</span>
{% endblock %}
{% block content %}
<div id="description">
{% block description %}
{% for field, value in object.get_fields_kv %}
<p class="{{field.name}}">
{% if field.name == "guichet" %}
{% trans "Guichet" %} {% trans ":" %}
{% if value %}
<a href="{{value.get_absolute_url}}">{{value}}</a>
{% else %}
{% trans "None" %}
{% endif %}
{% elif field.name != "connecteur" and field.name != "forward_file" and field.name != "id" and field.name != "name" %}
{% trans field.verbose_name %} {% trans ":" %} {{value}}
{% endif %}
</p>
{% endfor %}
{% if object.forward_files.count %}
<p class="title">
{% trans "Forward files" %}
{% trans ":" %}
<a href="{% if forward_files_list_url %}{{forward_files_list_url}}{% else %}{{ object.forward_files.first.get_list_url }}{% endif %}">
{{ object.forward_files.count }}
{% if object.forward_files.count == 1 %}{% trans "forward file" %}
{% else %}{% trans "forward files" %}
{% endif %}
</a>
</p>
{% endif %}
{% endblock %}
</div>
{% endblock %}

View File

@ -0,0 +1,96 @@
{% extends "passerelle/manage/service_view.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} - {{ object.title }}
{% with status=object.get_availability_status %}
{% if status %}
{% if status.down %}<span class="down" title="{{status.message}} {% trans 'since:' %} {{status.start_timestamp|date:"SHORT_DATETIME_FORMAT"}} ">{% trans 'Down' %}</span>{% endif %}
{% endif %}
{% endwith %}
</h2>
<span class="actions">
{% if object|can_edit:request.user and has_check_status %}
<a rel="popup" href="{% url 'manage-availability' resource_type=object|resource_type resource_pk=object.id %}">{% trans 'availability check parameters' %}</a>
{% endif %}
{% if object|can_edit:request.user %}
<a rel="popup" href="{% url 'logging-parameters' resource_type=object|resource_type resource_pk=object.id %}">{% trans 'logging parameters' %}</a>
{% endif %}
{% if object|can_delete:request.user %}
<a rel="popup" href="{{ object.get_delete_url }}">{% trans 'delete' %}</a>
{% endif %}
{% if object|can_edit:request.user %}
<a rel="popup" href="{{ object.get_edit_url }}">{% trans 'edit' %}</a>
{% endif %}
{% if object|can_edit:request.user and collectivite_add_url%}
<a rel="popup" href="{{ collectivite_add_url }}">{% trans "Add a collectivite" %}</a>
{% endif %}
</span>
{% endblock %}
{% block description %}
{{ block.super }}
{% if object.id %}
{% if object.collectivites.count %}
{% if object.collectivites.count == 1 %}
<p class="title">
{% trans 'Collectivites' %}
{% trans ":" %}
<a href="{{ object.collectivites.first.get_absolute_url }}">{{ object.collectivites.first }}</a>
</p>
{% elif object.collectivites.count < 10 %}
<p class="title">{% trans 'Collectivites' %}</p>
<ul class="connecteur-collectivites">
{% for col in object.collectivites.all %}
<li class="collectivite"><a href="{{ col.get_absolute_url }}">{{ col.name }}</a>
{% if col.guichet %}<span class="guichet"> ( {{ col.guichet }} ) </span>{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p class="title">
{% trans 'Collectivites' %}
{% trans ":" %}
<a href="{{ object.collectivites.first.get_list_url }}">{{ object.collectivites.count }} {% trans 'collectivites' %}</a>
</p>
{% endif %}
{% endif %}
{% if object.forward_files.count %}
<p class="title">
{% trans "Forward files" %}
{% trans ":" %}
<a href="{{ object.forward_files.first.get_list_url }}">
{{ object.forward_files.count }}
{% if object.forward_files.count == 1 %}{% trans "forward file" %}
{% else %}{% trans "forward files" %}
{% endif %}
</a>
</p>
{% endif %}
{% endif %}
{% endblock %}

View File

@ -0,0 +1,53 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% if collectivite %}<a href="{{collectivite.get_absolute_url}}">{{ collectivite.name }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} - {% if object.id %}{{ object.numero_dossier }} - {{ object.type_fichier }}{% endif %}</h2>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
<div id="form-content">
{% csrf_token %}
{{ form|with_template }}
</div>
{% block buttons %}
<div class="buttons">
<button class="submit-button">{% trans "Save" %}</button>
<button class="cancel">{% trans "Cancel" %}</button>
</div>
{% endblock %}
</form>
{% endblock %}

View File

@ -0,0 +1,111 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% if collectivite %}<a href="{{collectivite.get_absolute_url}}">{{ collectivite.name }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} - {% trans 'list' %}</h2>
{% endblock %}
{% block content %}
<table id="list-forward-files">
{% block list %}
{% if object_list %}
<thead>
<tr>
<th class="actions">{% trans "Actions" %}</th>
{% for field in view.model.get_fields %}
{% if field.name != "connecteur" and field.name != "file_hash" and field.name != "orig_filename" %}
<th class="{{field.name}}">{% trans field.verbose_name %}</th>
{% endif %}
{% endfor %}
</tr>
</thead>
<tbody>
{% for ff in object_list %}
<tr>
<td class="actions">
<span class="edit-link"><a rel="popup" href="{{ff.get_edit_url}}?back-to={% if collectivite %}col-{% endif %}list-forward-files" >{% trans "edit" %}</a></span>
<span class="delete-link"><a rel="popup" href="{{ff.get_delete_url}}?back-to={% if collectivite %}col-{% endif %}list-forward-files">{% trans "delete" %}</a></span>
</td>
{% for field, value in ff.get_fields_kv %}
{% if field.name != "connecteur" and field.name != "file_hash" and field.name != "orig_filename" %}
<td class="{{field.name}}">
{% if field.name != "collectivite" and field.name != "upload_file" %}
{{value}}
{% elif field.name == "collectivite" %}
{% if value %}<a href="{{value.get_absolute_url}}">{{value}}</a>
{% else %}{% trans "None" %}
{% endif %}
{% elif field.name == "upload_file" %}
{% if value %}<a href="{{value.url}}">{{value}}</a>
{% else %}{% trans "None" %}
{% endif %}
{% endif %}
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
{% if is_paginated %}
<tfoot>
<tr>
<td class="pagination" colspan="{{ view.model.get_fields|length }}">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">&laquo; {% trans "first" %}</a>
<a href="?page={{ contacts.previous_page_number }}">{% trans "previous" %}</a>
{% endif %}
<span class="current">
{% trans "Page" %} {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">{% trans "next" %}</a>
<a href="?page={{ page_obj.paginator.num_pages }}">{% trans "last" %} &raquo;</a>
{% endif %}
</span>
<td>
</tr>
</tfoot>
{% endif %}
{% else %}
<tr class="nodata">
<td>{% trans "No data" %}</td>
</tr>
{% endif %}
{% endblock %}
</table>
{% endblock %}

View File

@ -0,0 +1,75 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% if collectivite %}<a href="{{collectivite.get_absolute_url}}">{{ collectivite.name }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} - {% if object.id %}{{ object.numero_dossier }} - {{ object.type_fichier }}{% endif %}</h2>
<span class="actions">
{% if object|can_delete:request.user %}
<a rel="popup" href="{{ object.get_delete_url }}">{% trans "delete" %}</a>
{% endif %}
{% if object|can_edit:request.user %}
<a rel="popup" href="{{ object.get_edit_url }}">{% trans "edit" %}</a>
{% endif %}
</span>
{% endblock %}
{% block content %}
<div id="description">
{% block description %}
{% for field, value in object.get_fields_kv %}
<p class="{{field.name}}">
{% if field.name == "collectivite" %}
{% trans "Collectivite" %} {% trans ":" %}
{% if value %}
<a href="{{value.get_absolute_url}}">{{value}}</a>
{% else %}
{% trans "None" %}
{% endif %}
{% elif field.name == "upload_file" %}
{% trans "File" %} {% trans ":" %}
{% if value %}
<a href="{{value.url}}">{{value}}</a>
{% else %}
{% trans "None" %}
{% endif %}
{% elif field.name != "connecteur" and field.name != "id" %}
{% trans field.verbose_name %} {% trans ":" %} {{value}}
{% endif %}
</p>
{% endfor %}
{% endblock %}
</div>
{% endblock %}

View File

@ -0,0 +1,53 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% if collectivite %}<a href="{{collectivite.get_absolute_url}}">{{ collectivite.name }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }} {% if object.id and object.collectivite %} - {{ object.collectivite }}{% else %}{% trans 'New' %}{% endif %}</h2>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
<div id="form-content">
{% csrf_token %}
{{ form|with_template }}
</div>
{% block buttons %}
<div class="buttons">
<button class="submit-button">{% trans "Save" %}</button>
<button class="cancel">{% trans "Cancel" %}</button>
</div>
{% endblock %}
</form>
{% endblock %}

View File

@ -0,0 +1,63 @@
{% extends "passerelle/manage.html" %}
{% load i18n passerelle gadjo staticfiles %}
{% comment %}
This file is part of passerelle-atreal-openads - a Publik connector to openADS
Copyright (C) 2019 Atreal
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% block extrascripts %}
{{ block.super }}
<link rel="stylesheet" type="text/css" media="all" href="{% static "css/atreal_openads.css" %}?{% start_timestamp %}"/>
{% endblock %}
{% block breadcrumb %}
{{ block.super }}
{% if connecteur %}<a href="{{connecteur.get_absolute_url}}">{{ connecteur.slug }}</a>{% endif %}
{% if collectivite %}<a href="{{collectivite.get_absolute_url}}">{{ collectivite.name }}</a>{% endif %}
{% endblock %}
{% block appbar %}
<h2>{{ view.model.get_verbose_name }}</h2>
<span class="actions">
{% if object|can_delete:request.user %}
<a rel="popup" href="{{ object.get_delete_url }}">{% trans "delete" %}</a>
{% endif %}
{% if object|can_edit:request.user %}
<a rel="popup" href="{{ object.get_edit_url }}">{% trans "edit" %}</a>
{% endif %}
</span>
{% endblock %}
{% block content %}
<div id="description">
{% block description %}
{% for field, value in object.get_fields_kv %}
{% if field.name != "id" %}
<p class="{{field.name}}">
{% if field.name != "collectivite" %}
{% trans field.verbose_name %} {% trans ":" %} {{value}}
{% endif %}
</p>
{% endif %}
{% endfor %}
{% endblock %}
</div>
{% endblock %}

View File

@ -1,67 +0,0 @@
import pytest
from httmock import urlmatch, HTTMock, response
import django_webtest
from django.core.cache import cache
@pytest.fixture(autouse=True)
def media(settings, tmpdir):
settings.MEDIA_ROOT = str(tmpdir.mkdir('media'))
@pytest.fixture
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
request.addfinalizer(wtm._unpatch_settings)
cache.clear()
return django_webtest.DjangoTestApp()
@pytest.fixture
def endpoint_dummy_cache(monkeypatch):
from django.core.cache import caches
import passerelle.views
monkeypatch.setattr(
passerelle.views, 'cache', caches['dummy'])
@urlmatch()
def internal_server_error(url, request):
return response(500, 'Internal server error')
@pytest.fixture
def mock_500():
with HTTMock(internal_server_error):
yield None
@pytest.fixture
def relax_openssl(tmpdir):
'''OpenSSL default configuration has been really strict for some years,
this fixture set a temporary really permisive ciphers list.'''
import os
openssl_cnf_path = tmpdir / 'openssl.cnf'
with openssl_cnf_path.open('w') as fd:
fd.write(u'''
[default_conf]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
CipherString = ALL''')
old_value = os.environ.get('OPENSSL_CONF', None)
try:
os.environ['OPENSSL_CONF'] = str(openssl_cnf_path)
yield
finally:
if old_value is None:
del os.environ['OPENSSL_CONF']
else:
os.environ['OPENSSL_CONF'] = old_value

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

View File

@ -1,359 +0,0 @@
# -*- coding: utf-8 -*-
# to run it use the following command in the 'tests' directory:
# ~> DJANGO_SETTINGS_MODULE=passerelle.settings pytest -W ignore::django.utils.deprecation.RemovedInDjango20Warning test_atreal_openads.py -vv
#
# and with 'coverage':
# ~> DJANGO_SETTINGS_MODULE=passerelle.settings pytest -W ignore::django.utils.deprecation.RemovedInDjango20Warning test_atreal_openads.py -vv --cov=~/src/passerelle/passerelle/apps/atreal_openads
import pytest
import mock
import json
import os
import base64
import re
from requests import Response
from django.http import Http404
from django.http.request import HttpRequest, QueryDict
from django.http.response import JsonResponse
from django.core.files import File
from passerelle.apps.atreal_openads.models import AtrealOpenads, ForwardFile
from passerelle.utils.jsonresponse import APIError
from passerelle.base.models import Job
CONNECTOR_NAME = 'atreal-openads'
CONNECTOR_SLUG = 'atreal'
COLLECTIVITE = 3
OPENADS_API_LOGIN = 'publik-passerelle'
OPENADS_API_PASSWORD = base64.urlsafe_b64encode(os.urandom(20))
OPENADS_API_URL = 'http://openads.api/'
FAKE_COOKIE_CRSF = base64.urlsafe_b64encode(os.urandom(20))
FAKE_NUMERO_DOSSIER = base64.urlsafe_b64encode(os.urandom(10))
TESTS_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(TESTS_DIR, 'resources')
TEST_FILE_CERFA_DIA = os.path.join(RESOURCES_DIR, 'cerfa_10072-02.pdf')
TEST_FILE_PLAN_CADASTRAL = os.path.join(RESOURCES_DIR, 'plancadastral.pdf')
def get_file_data(path, b64=True):
"""Return the content of a file as a string, in base64 if specified."""
with open(path, 'r') as f:
if b64:
return base64.b64encode(f.read())
return f.read()
@pytest.fixture
def atreal_openads(db):
return AtrealOpenads.objects.create(
slug = CONNECTOR_SLUG,
collectivite = COLLECTIVITE,
openADS_API_login = OPENADS_API_LOGIN,
openADS_API_password = OPENADS_API_PASSWORD,
openADS_API_url = OPENADS_API_URL
)
def test_openads_check_status(app, atreal_openads):
fake_resp_json = {
'message': 'Service online'
}
fake_resp = JsonResponse(fake_resp_json)
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = mock.Mock(content=fake_resp, status_code=200)
jresp = atreal_openads.check_status()
assert jresp['response'] == 200
def test_openads_create_dossier(app, atreal_openads):
fake_req_json = {
"fields": {
"autres_parcelles": True,
"cerfa": {
"content": get_file_data(TEST_FILE_CERFA_DIA),
"content_type": "application/pdf",
"field_id": "50",
"filename": os.path.basename(TEST_FILE_CERFA_DIA)
},
"code_postal": "13004",
"localite": "Marseille",
"nom": "Loulou",
"nom_voie": "Avenue de la Blaque",
"numero_voie": "52",
"plan_cadastral_1": {
"content": get_file_data(TEST_FILE_PLAN_CADASTRAL),
"content_type": "application/pdf",
"field_id": "113",
"filename": os.path.basename(TEST_FILE_PLAN_CADASTRAL)
},
"prenom": "Toto",
"proprietaire": "Oui",
"proprietaire_qualite": "Un particulier",
"proprietaire_qualite_raw": "Un particulier",
"proprietaire_raw": "Oui",
"reference_cadastrale": [
[
"999",
"Z",
"0010"
]
],
"references_cadastrales": [
[
"123",
"D",
"9874"
]
],
"terrain_code_postal": "13002",
"terrain_localite": "Marseille",
"terrain_nom_voie": "Boulevard de la Linule",
"terrain_numero_voie": "23"
}
}
req = HttpRequest()
req._body = json.dumps(fake_req_json)
req.path = '/test'
req.method = 'POST'
req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_type = 'application/json'
req.content_params = None
req.COOKIES = {}
req.META = {}
req._read_started = False
fake_resp_json = {
'numero_dossier' : FAKE_NUMERO_DOSSIER,
'files': [{
'b64_content' : get_file_data(TEST_FILE_CERFA_DIA),
'content_type' : 'text/plain',
'filename' : 'recepisse_depot_%s.pdf' % FAKE_NUMERO_DOSSIER,
}]
}
fake_resp = Response()
fake_resp.status_code = 200
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp
jresp = atreal_openads.create_dossier(req, 'DIA')
assert jresp['numero_dossier'] == fake_resp_json['numero_dossier']
assert jresp['recepisse']['b64_content'] == fake_resp_json['files'][0]['b64_content']
assert jresp['recepisse']['content_type'] == 'application/pdf'
assert jresp['recepisse']['filename'] == fake_resp_json['files'][0]['filename']
job = Job.objects.filter(natural_id=FAKE_NUMERO_DOSSIER).last()
assert job
job_id = job.id
assert job.status == 'registered'
assert job.method_name == 'upload_user_files'
assert job.natural_id == FAKE_NUMERO_DOSSIER
assert job.parameters is not None
assert len(job.parameters) == 3
assert 'file_ids' in job.parameters
assert len(job.parameters['file_ids']) == 2
file_ids = job.parameters['file_ids']
FFs = ForwardFile.objects.filter(id__in=file_ids)
for FF in FFs:
assert len(FF.numero_demande) > 0
assert FF.numero_dossier == FAKE_NUMERO_DOSSIER
assert len(FF.file_hash) > 0
assert FF.upload_status == 'pending'
fake_resp_json = "You want add some files on %s " % FAKE_NUMERO_DOSSIER
fake_resp = Response()
fake_resp.status_code = 200
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp
atreal_openads.jobs()
job = Job.objects.get(id=job_id)
assert job.status == 'completed'
FFs = ForwardFile.objects.filter(id__in=file_ids)
for FF in FFs:
assert FF.upload_status == 'success'
def test_openads_get_dossier(app, atreal_openads):
fake_resp_json = {
'etat' : u"Non préemption en cours",
'date_depot' : "24/04/2019",
'date_decision' : "",
'decision' : "",
'date_limite_instruction': "24/06/2019"
}
fake_resp = Response()
fake_resp.status_code = 200
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_dossier(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp['etat'] == fake_resp_json['etat']
assert jresp['date_depot'] == fake_resp_json['date_depot']
assert jresp['date_decision'] == fake_resp_json['date_decision']
assert jresp['decision'] == fake_resp_json['decision']
assert jresp['date_limite_instruction'] == fake_resp_json['date_limite_instruction']
fake_resp_json = {
'errors' : [{
'location' : 'path',
'name' : 'Invalid Type',
'description' : '"invalid_type" is not one of DIA, PC, DP, AT, PD'
}]
}
fake_resp = Response()
fake_resp.status_code = 404
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'Resource not found'
fake_resp._content = json.dumps(fake_resp_json)
with pytest.raises(APIError) as e:
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_dossier(None, 'invalid_type', FAKE_NUMERO_DOSSIER)
assert re.search(r'^HTTP error: 404, \[path\] \(Invalid Type\) "invalid_type" is not one of DIA, PC, DP, AT, PD$', str(e.value))
def test_openads_upload2ForwardFile(app, atreal_openads):
FF = atreal_openads.upload2ForwardFile(None, None)
assert FF is None
FF = atreal_openads.upload2ForwardFile(TEST_FILE_CERFA_DIA, FAKE_NUMERO_DOSSIER)
assert isinstance(FF, ForwardFile)
assert len(FF.numero_demande) > 0
assert FF.numero_dossier == FAKE_NUMERO_DOSSIER
assert FF.type_fichier == 'CERFA'
assert FF.orig_filename == os.path.basename(TEST_FILE_CERFA_DIA)
assert FF.content_type == 'application/pdf'
assert len(FF.file_hash) > 0
assert isinstance(FF.upload_file, File)
assert FF.upload_status == 'pending'
FF = atreal_openads.upload2ForwardFile(TEST_FILE_PLAN_CADASTRAL, FAKE_NUMERO_DOSSIER, 'plan')
assert isinstance(FF, ForwardFile)
assert len(FF.numero_demande) > 0
assert FF.numero_dossier == FAKE_NUMERO_DOSSIER
assert FF.type_fichier == 'plan'
assert FF.orig_filename == os.path.basename(TEST_FILE_PLAN_CADASTRAL)
assert FF.content_type == 'application/pdf'
assert len(FF.file_hash) > 0
assert isinstance(FF.upload_file, File)
assert FF.upload_status == 'pending'
def test_openads_get_fwd_files_status(app, atreal_openads):
with pytest.raises(Http404) as e:
resp404 = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=18, summary=None)
assert re.search(r"^No file matches 'numero_dossier=[^']+' and 'id=[^']+'.$", str(e.value))
resp404 = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary=None)
assert resp404 is not None
assert len(resp404) == 0
FF = atreal_openads.upload2ForwardFile(TEST_FILE_CERFA_DIA, FAKE_NUMERO_DOSSIER)
FF.save()
assert isinstance(FF, ForwardFile)
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary=None)
assert jresp is not None
assert len(jresp) == 1
assert jresp[0]['id'] == FF.id
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', 'upload_status', 'upload_msg']:
assert jresp[0][k] == getattr(FF, k)
assert jresp[0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp[0]['last_update_datetime'] == FF.last_update_datetime
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=FF.id, summary=None)
assert jresp is not None
assert len(jresp) == 1
assert jresp[0]['id'] == FF.id
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type', 'upload_status', 'upload_msg']:
assert jresp[0][k] == getattr(FF, k)
assert jresp[0]['b64_content'] == get_file_data(FF.upload_file.path)
assert jresp[0]['last_update_datetime'] == FF.last_update_datetime
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=None, summary='1')
assert jresp is not None
assert jresp['all_forwarded'] == False
status_msg = '[%s] %s => %s' % (FF.id, FF.orig_filename, FF.upload_msg)
assert len(jresp['pending']) == 1
assert jresp['pending'][0] == status_msg
assert len(jresp['uploading']) == 0
assert len(jresp['success']) == 0
assert len(jresp['failed']) == 0
jresp = atreal_openads.get_fwd_files_status(None, FAKE_NUMERO_DOSSIER, fichier_id=FF.id, summary='1')
assert jresp is not None
assert jresp['all_forwarded'] == False
status_msg = '[%s] %s => %s' % (FF.id, FF.orig_filename, FF.upload_msg)
assert len(jresp['pending']) == 1
assert jresp['pending'][0] == status_msg
assert len(jresp['uploading']) == 0
assert len(jresp['success']) == 0
assert len(jresp['failed']) == 0
def test_openads_get_courrier(app, atreal_openads):
fake_resp_json = {
'files': [{
'filename' : "instruction_4.pdf",
'content_type' : "text/plain",
'b64_content' : get_file_data(TEST_FILE_CERFA_DIA)
}]
}
fake_resp = Response()
fake_resp.status_code = 200
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.get') as requests_get:
requests_get.return_value = fake_resp
jresp = atreal_openads.get_courrier(None, 'DIA', FAKE_NUMERO_DOSSIER)
assert jresp['courrier']['filename'] == fake_resp_json['files'][0]['filename']
assert jresp['courrier']['content_type'] == fake_resp_json['files'][0]['content_type']
assert jresp['courrier']['b64_content'] == fake_resp_json['files'][0]['b64_content']
def test_openads_upload_user_files(app, atreal_openads):
FF = atreal_openads.upload2ForwardFile(TEST_FILE_CERFA_DIA, FAKE_NUMERO_DOSSIER)
FF.save()
assert isinstance(FF, ForwardFile)
assert FF.upload_status == 'pending'
file_id = FF.id
assert file_id
fake_resp_json = "You want add some files on %s " % FAKE_NUMERO_DOSSIER
fake_resp = Response()
fake_resp.status_code = 200
fake_resp.headers = {'Content-Type': 'application/json'}
fake_resp.encoding = 'utf-8'
fake_resp.reason = 'OK'
fake_resp._content = json.dumps(fake_resp_json)
with mock.patch('passerelle.utils.Request.post') as requests_post:
requests_post.return_value = fake_resp
atreal_openads.upload_user_files('DIA', FAKE_NUMERO_DOSSIER, file_ids=[file_id])
FFup = ForwardFile.objects.get(id=file_id)
assert isinstance(FFup, ForwardFile)
for k in ['numero_dossier', 'type_fichier', 'file_hash', 'orig_filename', 'content_type']:
assert getattr(FFup, k) == getattr(FF, k)
assert FFup.upload_status == 'success'

112
atreal_openads/urls.py Normal file
View File

@ -0,0 +1,112 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""The urls for this connector module and its entities views."""
import re
from django.conf.urls import url
from .views import (
AtrealOpenadsView,
ForwardFileView,
ForwardFileListView,
ForwardFileUpdateView,
ForwardFileDeleteView,
CollectiviteView,
CollectiviteListView,
CollectiviteCreateView,
CollectiviteUpdateView,
CollectiviteDeleteView,
GuichetView,
GuichetCreateView,
GuichetUpdateView,
GuichetDeleteView
)
# pylint: disable=invalid-name
urlpatterns = [
url(r'^(?P<slug>[\w,-]+)/$', AtrealOpenadsView.as_view(), name='view-connector')
]
# pylint: disable=invalid-name
management_urlpatterns = []
for view in [
ForwardFileView,
ForwardFileListView,
ForwardFileUpdateView,
ForwardFileDeleteView,
CollectiviteView,
CollectiviteListView,
CollectiviteCreateView,
CollectiviteUpdateView,
CollectiviteDeleteView,
GuichetView,
GuichetCreateView,
GuichetUpdateView,
GuichetDeleteView]:
view_class_name = str(view.__name__)
m = re.search(r'^.*(Create|Update|Delete|List)View$', view_class_name)
if m:
view_action = m.group(1).lower()
else:
view_action = 'view'
# no prefix for action 'view'
url_prefix = view_action.replace('update', 'edit') + '-'
regex_base = r'^(?P<connecteur>[\w,-]+)/'
# pylint: disable=anomalous-backslash-in-string
regex_pkey = '/(?P<pk>[\w,-]+)' # noqa: W605
url_name = url_prefix + view.model.get_class_name_dash_case()
regex_url = '%s%s' % (url_prefix if view_action != 'view' else '',
view.model.get_class_name_dash_case())
# no primary key for action 'create' and 'list'
if view_action in ['create', 'list']:
regex_pkey = ''
# plural form of the url for action 'list' and no prefix
if view_action == 'list':
url_name = url_prefix + view.model.get_class_name_plural_dash_case()
regex_url = view.model.get_class_name_plural_dash_case()
# for 'guichet' prefix the regex by the collectivite
if view.model.get_class_name() == 'Guichet':
regex_base += 'collectivite/(?P<collectivite>[\w,-]+)/' # noqa: W605
# build the regex
regex = regex_base + regex_url + regex_pkey + '$'
# add the url pattern to the management list
management_urlpatterns += [url(regex, view.as_view(), name=url_name)]
# add the ForwardFile 'list' url patterns for Collectivite
ff_list_regex_url = ForwardFileListView.model.get_class_name_plural_dash_case()
management_urlpatterns += [
url(
r'^(?P<connecteur>[\w,-]+)/collectivite/(?P<collectivite>[\w,-]+)/%s$' % ff_list_regex_url,
ForwardFileListView.as_view(),
name='col-list-' + ff_list_regex_url
)
]

286
atreal_openads/utils.py Normal file
View File

@ -0,0 +1,286 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Utilities functions."""
import json
import base64
import datetime
import re
import hashlib
import copy
import mimetypes
import sys
from django.urls import reverse_lazy
from django.utils import six
from django.utils.encoding import force_text
from django.utils.six.moves.html_parser import HTMLParser
def to_dash_case(camel_str):
"""Convert a string formatted from camel case to dash case (like snake case with dash)."""
converted = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', camel_str)
return re.sub('([a-z0-9])([A-Z])', r'\1-\2', converted).lower()
# from: https://stackoverflow.com/a/13848698
def force_encoded_string_output(func, default_enc='utf-8'):
"""Decorator function that return the result converted to str type."""
if sys.version_info.major < 3:
def _func(*args, **kwargs):
return func(*args, **kwargs).encode(sys.stdout.encoding or default_enc)
return _func
return func
class MLStripper(HTMLParser, object):
"""HTML parser that removes html tags."""
def __init__(self):
super(MLStripper, self).__init__()
self.fed = []
def handle_data(self, data):
self.fed.append(data)
def get_data(self):
"""Get the stripped data as a string."""
return ''.join(self.fed)
def strip_tags(html):
"""Remove html tags from a string."""
stripper = MLStripper()
stripper.feed(html)
return stripper.get_data()
def clean_spaces(text):
"""Remove extra spaces an line breaks from a string."""
text = text.replace('\n', ' ')
text = text.replace('\r', ' ')
text = text.replace('\t', ' ')
text = text.replace('\\n', ' ')
text = text.replace('\\r', ' ')
text = text.replace('\\t', ' ')
return re.sub(r' +', ' ', text).strip()
def normalize(value):
"""Normalize a value to be send to openADS.API."""
if value is None:
return ''
if not isinstance(value, six.text_type):
value = force_text(value)
return clean_spaces(value)
def get_file_data(path, b64=True):
"""Return the content of a file as a string, in base64 if specified."""
with open(path, 'rb') as file_pt:
if b64:
return base64.b64encode(file_pt.read())
return file_pt.read()
# copy-pasted from 'wcs/qommon/misc.py'
def get_file_digest(content, chunk_size=100000):
"""Return a hash for the content specified."""
digest = hashlib.sha256()
content.seek(0)
def read_chunk():
"""Read 'chunk_size' amount of data from the content."""
return content.read(chunk_size)
for chunk in iter(read_chunk, b''):
digest.update(chunk)
return digest.hexdigest()
def get_upload_path(instance, filename=None):
"""Return a relative upload path for a file."""
fn_ref = instance.orig_filename if instance.orig_filename else filename
# file_hash and content_type attribute are updated on file save()
# so if the file was not yet saved, it may have those attributes undefined
# this is why we update them here, if they are empty
instance.update_file_hash(only_if_empty=True)
instance.update_content_type(only_if_empty=True)
# be careful:
# * openADS accept only filename less than 50 chars
# * name should be unique, even if the content is the same
return 'to_openADS__%s__%s%s' % (
datetime.datetime.now().strftime('%Y-%m-%d_%Hh%Mm%Ss%f'),
instance.file_hash[:4],
get_file_extension(fn_ref, instance.content_type)[:5]
)
def get_file_extension(filename, mimetype=None):
"""Return the extension of the file, according to its filename or specified mimetype."""
file_extension = None
if filename and '.' in filename:
file_extension = re.sub(r'^.*\.', '.', filename)
elif mimetype:
file_extension = mimetypes.guess_extension(mimetype)
return file_extension if file_extension else ''
# pylint: disable=invalid-encoded-data
def trunc_str_values(value, limit, visited=None, truncate_text=u''):
"""Truncate a string value (not dict keys) and append a truncate text."""
if visited is None:
visited = []
if value not in visited:
if isinstance(value, six.string_types) and len(value) > limit:
value = value[:limit] + truncate_text
elif isinstance(value, (dict, list, tuple)):
visited.append(value)
iterator = value.items() if isinstance(value, dict) else enumerate(value)
for _key, _value in iterator:
value[_key] = trunc_str_values(_value, limit, visited, truncate_text)
return value
@six.python_2_unicode_compatible
class DictDumper(object):
"""Helper to dump a dictionary to a string representation with lazy processing.
Only applied when dict is converted to string (lazy processing):
- long strings truncated (after the dict has been 'deep' copied)
- (optionaly) dict converted with json.dumps instead of unicode().
"""
def __init__(self, dic, max_str_len=255, use_json_dumps=True):
""" arguments:
- dic string the dict to dump
- max_str_len integer the maximul length of string values
- use_json_dumps boolean True to use json.dumps() else it uses unicode()
"""
self.dic = dic
self.max_str_len = max_str_len
self.use_json_dumps = use_json_dumps
@force_encoded_string_output
def __repr__(self):
return u'DictDumper(dic=%r,max_str_len=%r,use_json_dumps=%r)' % (
self.dic, self.max_str_len, self.use_json_dumps)
def __str__(self):
dict_trunc = trunc_str_values(copy.deepcopy(self.dic), self.max_str_len)
dict_ref = json.dumps(dict_trunc) if self.use_json_dumps else dict_trunc
return force_text(dict_ref)
class BaseModel(object):
"""A class that provide basic usefull functions.
Intended for all models to extends it.
"""
@classmethod
def get_verbose_name(cls):
"""Return the verbose name of the class (helper for META option)."""
# pylint: disable=no-member
return cls._meta.verbose_name
@classmethod
def get_verbose_name_plural(cls):
"""Return the plural form of the verbose name of the class (helper for META option)."""
# pylint: disable=no-member
return cls._meta.verbose_name_plural
@classmethod
def get_class_name(cls):
"""Return the object class name."""
return cls.__name__
@classmethod
def get_class_name_plural(cls):
"""Return the plural form of the object class name."""
return cls.get_class_name() + 's'
@classmethod
def get_class_name_dash_case(cls):
"""Return the object class name formatted to dash case."""
return to_dash_case(cls.get_class_name())
@classmethod
def get_class_name_plural_dash_case(cls):
"""Return the plural form of the object class name
formatted to dash case.
"""
return to_dash_case(cls.get_class_name_plural())
@classmethod
def get_class_name_title(cls):
"""Return the object class name formatted to 'title' case."""
return cls.get_class_name_dash_case().replace('-', ' ').title()
@classmethod
def get_class_name_plural_title(cls):
"""Return the plural form of the object class name
formatted to 'title' case.
"""
return cls.get_class_name_plural_dash_case().replace('-', ' ').title()
@classmethod
def get_fields(cls):
"""Return the fields of the class (helper for META option)."""
# pylint: disable=no-member
return cls._meta.get_fields(include_parents=True, include_hidden=False)
@force_encoded_string_output
def __str__(self):
return force_text(self)
# mainly for the view
def get_fields_kv(self):
"""Return the model's list of field's key value."""
# pylint: disable=no-member
return [(field, getattr(self, field.name, None)) for field in self._meta.get_fields()]
def get_url_name(self, prefix='', plural=False):
"""Return a base name for url for this object."""
class_name_dash_case = self.__class__.get_class_name_dash_case()
if plural:
class_name_dash_case = self.__class__.get_class_name_plural_dash_case()
return '%s%s' % (prefix + '-' if prefix else '', class_name_dash_case)
def get_url_params(self, primary_key=True):
"""Return the parameters for 'reverse()' to build url for this object."""
# pylint: disable=no-member
return {'pk': self.id} if primary_key else {}
def get_absolute_url(self):
"""Return the 'absolute' url for this object."""
return reverse_lazy(self.get_url_name('view'), kwargs=self.get_url_params())
def get_edit_url(self):
"""Return the 'edit' url for this object."""
return reverse_lazy(self.get_url_name('edit'), kwargs=self.get_url_params())
def get_delete_url(self):
"""Return the 'delete' url for this object."""
return reverse_lazy(self.get_url_name('delete'), kwargs=self.get_url_params())
def get_list_url(self):
"""Return the 'list' url for this object."""
return reverse_lazy(self.get_url_name('list', True), kwargs=self.get_url_params(False))

380
atreal_openads/views.py Normal file
View File

@ -0,0 +1,380 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Views for the models."""
from django.urls import reverse_lazy
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from passerelle.views import GenericConnectorView
from .models import ForwardFile, Collectivite, Guichet, AtrealOpenads
from .forms import ForwardFileForm, CollectiviteForm, GuichetForm
def get_connecteur_from_request(view, key='connecteur'):
"""Return the 'connecteur' object from the view object."""
if not hasattr(view, 'connecteur') or not view.connecteur and view.request:
connecteur_slug = view.request.resolver_match.kwargs.get(key, None)
if connecteur_slug:
view.connecteur = AtrealOpenads.objects.get(slug=connecteur_slug)
return view.connecteur if hasattr(view, 'connecteur') else None
def get_collectivite_from_request(view, key='collectivite'):
"""Return the 'collectivite' object from the view object."""
if not hasattr(view, 'collectivite') or not view.collectivite and view.request:
collectivite_id = view.request.resolver_match.kwargs.get(key, None)
if collectivite_id:
# pylint: disable=no-member
view.collectivite = Collectivite.objects.get(id=collectivite_id)
return view.collectivite if hasattr(view, 'collectivite') else None
# pylint: disable=too-many-ancestors
class ForwardFileView(DetailView):
"""View to display a ForwardFile."""
model = ForwardFile
template_name = 'atreal_openads/manage/forwardfile_view.html'
def get_context_data(self, **kwargs):
context = super(ForwardFileView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
return context
# pylint: disable=too-many-ancestors
class ForwardFileListView(ListView):
"""View to display a list of ForwardFiles."""
model = ForwardFile
template_name = 'atreal_openads/manage/forwardfile_list.html'
paginate_by = 50
ordering = 'id'
def get_queryset(self):
qset = None
collectivite = get_collectivite_from_request(self)
if collectivite:
qset = super(ForwardFileListView, self).get_queryset().filter(
connecteur=get_connecteur_from_request(self),
collectivite=collectivite)
else:
qset = super(ForwardFileListView, self).get_queryset().filter(
connecteur=get_connecteur_from_request(self))
order_by = None
order_by_param = self.request.GET.get('order-by', None)
if order_by_param:
fields_names = [f.name for f in self.model.get_fields()]
order_by_field = order_by_param[1:] if order_by_param[0] == '-' else order_by_param
if order_by_field in fields_names:
order_by = order_by_param
return qset.order_by(order_by) if order_by else qset # qset.order_by()
def get_context_data(self, **kwargs):
context = super(ForwardFileListView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
# pylint: disable=too-many-ancestors
class ForwardFileUpdateView(UpdateView):
"""View to edit a ForwardFile."""
model = ForwardFile
form_class = ForwardFileForm
template_name = 'atreal_openads/manage/forwardfile_form.html'
def get_context_data(self, **kwargs):
context = super(ForwardFileUpdateView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
def get_success_url(self):
back_to = self.request.GET.get('back-to')
if back_to == 'list-forward-files':
return reverse_lazy('list-forward-files', kwargs={
'connecteur': get_connecteur_from_request(self).slug
})
elif back_to == 'col-list-forward-files':
obj = self.get_object()
if obj.collectivite:
return reverse_lazy('col-list-forward-files', kwargs={
'connecteur': get_connecteur_from_request(self).slug,
'collectivite': obj.collectivite.id
})
return self.get_object().get_absolute_url()
# pylint: disable=too-many-ancestors
class ForwardFileDeleteView(DeleteView):
"""View to delete a ForwardFile."""
model = ForwardFile
form_class = ForwardFileForm
template_name = 'atreal_openads/manage/forwardfile_form.html'
def get_context_data(self, **kwargs):
context = super(ForwardFileDeleteView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
def get_success_url(self):
back_to = self.request.GET.get('back-to')
if back_to == 'list-forward-files':
return reverse_lazy('list-forward-files', kwargs={
'connecteur': get_connecteur_from_request(self).slug
})
elif back_to == 'col-list-forward-files':
obj = self.get_object()
if obj.collectivite:
return reverse_lazy('col-list-forward-files', kwargs={
'connecteur': get_connecteur_from_request(self).slug,
'collectivite': obj.collectivite.id
})
return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads',
'slug': get_connecteur_from_request(self).slug
})
# pylint: disable=too-many-ancestors
class CollectiviteView(DetailView):
"""View to display a Collectivite."""
model = Collectivite
template_name = 'atreal_openads/manage/collectivite_view.html'
def get_context_data(self, **kwargs):
context = super(CollectiviteView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['guichet_add_url'] = reverse_lazy('create-guichet', kwargs={
'connecteur': context['connecteur'].slug,
'collectivite': self.get_object().id})
context['forward_files_list_url'] = reverse_lazy('col-list-forward-files', kwargs={
'connecteur': context['connecteur'].slug,
'collectivite': self.get_object().id})
return context
# pylint: disable=too-many-ancestors
class CollectiviteListView(ListView):
"""View to display a list of Collectivites."""
model = Collectivite
template_name = 'atreal_openads/manage/collectivite_list.html'
paginate_by = 50
ordering = 'id'
def get_queryset(self):
qset = super(CollectiviteListView, self).get_queryset().filter(
connecteur=get_connecteur_from_request(self))
order_by = None
order_by_param = self.request.GET.get('order-by', None)
if order_by_param:
fields_names = [f.name for f in self.model.get_fields()]
order_by_field = order_by_param[1:] if order_by_param[0] == '-' else order_by_param
if order_by_field in fields_names:
order_by = order_by_param
return qset.order_by(order_by) if order_by else qset # qset.order_by()
def get_context_data(self, **kwargs):
context = super(CollectiviteListView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite_add_url'] = reverse_lazy('create-collectivite', kwargs={
'connecteur': context['connecteur'].slug})
return context
# pylint: disable=too-many-ancestors
class CollectiviteCreateView(CreateView):
"""View to create a Collectivite."""
model = Collectivite
form_class = CollectiviteForm
template_name = 'atreal_openads/manage/collectivite_form.html'
def get_context_data(self, **kwargs):
context = super(CollectiviteCreateView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
return context
def get_form_kwargs(self):
kwargs = super(CollectiviteCreateView, self).get_form_kwargs()
kwargs['connecteur'] = get_connecteur_from_request(self)
return kwargs
def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={
'connecteur': get_connecteur_from_request(self).slug
})
return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads',
'slug': get_connecteur_from_request(self).slug
})
# pylint: disable=too-many-ancestors
class CollectiviteUpdateView(UpdateView):
"""View to edit a Collectivite."""
model = Collectivite
form_class = CollectiviteForm
template_name = 'atreal_openads/manage/collectivite_form.html'
def get_context_data(self, **kwargs):
context = super(CollectiviteUpdateView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
return context
def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={
'connecteur': get_connecteur_from_request(self).slug
})
return self.get_object().get_absolute_url()
# pylint: disable=too-many-ancestors
class CollectiviteDeleteView(DeleteView):
"""View to delete a Collectivite."""
model = Collectivite
form_class = CollectiviteForm
template_name = 'atreal_openads/manage/collectivite_form.html'
def get_context_data(self, **kwargs):
context = super(CollectiviteDeleteView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
return context
def get_success_url(self):
if self.request.GET.get('back-to') == 'list-collectivites':
return reverse_lazy('list-collectivites', kwargs={
'connecteur': get_connecteur_from_request(self).slug
})
return reverse_lazy('view-connector', kwargs={
'connector': 'atreal-openads',
'slug': get_connecteur_from_request(self).slug
})
# pylint: disable=too-many-ancestors
class GuichetView(DetailView):
"""View to display a Guichet."""
model = Guichet
template_name = 'atreal_openads/manage/guichet_view.html'
def get_context_data(self, **kwargs):
context = super(GuichetView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
# pylint: disable=too-many-ancestors
class GuichetCreateView(CreateView):
"""View to create a Guichet."""
model = Guichet
form_class = GuichetForm
template_name = 'atreal_openads/manage/guichet_form.html'
def get_form_kwargs(self):
kwargs = super(GuichetCreateView, self).get_form_kwargs()
kwargs['collectivite'] = get_collectivite_from_request(self)
return kwargs
def get_context_data(self, **kwargs):
context = super(GuichetCreateView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
def get_success_url(self):
return reverse_lazy('view-collectivite', kwargs={
'connecteur': get_connecteur_from_request(self).slug,
'pk': get_collectivite_from_request(self).id
})
# pylint: disable=too-many-ancestors
class GuichetUpdateView(UpdateView):
"""View to edit a Guichet."""
model = Guichet
form_class = GuichetForm
template_name = 'atreal_openads/manage/guichet_form.html'
def get_context_data(self, **kwargs):
context = super(GuichetUpdateView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
# pylint: disable=too-many-ancestors
class GuichetDeleteView(DeleteView):
"""View to delete a Guichet."""
model = Guichet
form_class = GuichetForm
template_name = 'atreal_openads/manage/guichet_form.html'
def get_context_data(self, **kwargs):
context = super(GuichetDeleteView, self).get_context_data(**kwargs)
context['connecteur'] = get_connecteur_from_request(self)
context['collectivite'] = get_collectivite_from_request(self)
return context
def get_success_url(self):
return reverse_lazy('view-collectivite', kwargs={
'connecteur': get_connecteur_from_request(self).slug,
'pk': get_collectivite_from_request(self).id
})
# pylint: disable=too-many-ancestors
class AtrealOpenadsView(GenericConnectorView):
"""View to display a connector AtrealOpenads."""
model = AtrealOpenads
template_name = 'atreal_openads/manage/connector_view.html'
def get_context_data(self, slug=None, **kwargs):
context = super(AtrealOpenadsView, self).get_context_data(slug=slug, **kwargs)
context['collectivite_fields'] = Collectivite.get_fields()
context['collectivite_add_url'] = reverse_lazy('create-collectivite', kwargs={
'connecteur': self.get_object().slug})
return context

25
debian/50atreal_openads.py vendored Normal file
View File

@ -0,0 +1,25 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
if not 'atreal_openads' in INSTALLED_APPS:
INSTALLED_APPS += ('atreal_openads',)
TENANT_APPS += ('atreal_openads',)
PASSERELLE_APP_ATREAL_OPENADS_ENABLED = False

2
debian/compat vendored
View File

@ -1 +1 @@
9
10

14
debian/control vendored
View File

@ -1,12 +1,20 @@
Source: passerelle-atreal-openads
Maintainer: Frederic Peters <fpeters@entrouvert.com>
Maintainer: Michael Bideau <mbideau+publik@atreal.fr>
Section: python
Priority: optional
Build-Depends: python-setuptools (>= 0.6b3), python-all (>= 2.6.6-3), debhelper (>= 9), python-django
Build-Depends: python-setuptools, python-all, debhelper (>= 10), python-django, python3-setuptools, python3-all, python3-django
Standards-Version: 3.9.1
Package: python-passerelle-atreal-openads
Architecture: all
Depends: ${misc:Depends}, ${python:Depends}
Depends: ${misc:Depends}, ${python:Depends},
python-magic
Description: Passerelle connector to openADS.API
.
Package: python3-passerelle-atreal-openads
Architecture: all
Depends: ${misc:Depends}, ${python3:Depends},
python3-magic
Description: Passerelle connector to openADS.API (Python 3)
.

View File

@ -0,0 +1 @@
debian/50atreal_openads.py /etc/passerelle/settings.d/

5
debian/rules vendored
View File

@ -1,4 +1,7 @@
#!/usr/bin/make -f
export PYBUILD_NAME=passerelle-atreal-openads
export PYBUILD_DISABLE=test
%:
dh $@ --with python2
dh $@ --with python2,python3 --buildsystem=pybuild

34
manage.py Executable file
View File

@ -0,0 +1,34 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "passerelle.settings")
from django.conf import settings
if 'atreal_openads' not in settings.INSTALLED_APPS:
settings.INSTALLED_APPS += ('atreal_openads',)
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)

33
pylint.sh Executable file
View File

@ -0,0 +1,33 @@
#!/bin/sh
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
set -e -x
env
if [ -f /var/lib/jenkins/pylint.django.rc ]; then
PYLINT_RC=/var/lib/jenkins/pylint.django.rc
elif [ -f pylint.django.rc ]; then
PYLINT_RC=pylint.django.rc
else
echo No pylint RC found
exit 0
fi
test -f pylint.out && cp pylint.out pylint.out.prev
pylint -f parseable --rcfile ${PYLINT_RC} "$@" | tee pylint.out || /bin/true
test -f pylint.out.prev && (diff pylint.out.prev pylint.out | grep '^[><]' | grep .py) || /bin/true

112
setup.py
View File

@ -1,10 +1,33 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import subprocess
import sys
from setuptools.command.install_lib import install_lib as _install_lib
from setuptools.command.sdist import sdist
from distutils.command.build import build as _build
from distutils.cmd import Command
from setuptools import setup, find_packages
from distutils.command.sdist import sdist
class eo_sdist(sdist):
def run(self):
@ -18,28 +41,93 @@ class eo_sdist(sdist):
if os.path.exists('VERSION'):
os.remove('VERSION')
def get_version():
'''Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0- and add the length of the commit log.
'''
if os.path.exists('VERSION'):
version_file = open('VERSION', 'r')
version = version_file.read()
version_file.close()
return version
with open('VERSION', 'r') as v:
return v.read()
if os.path.exists('.git'):
p = subprocess.Popen(['git', 'describe', '--dirty', '--match=v*'], stdout=subprocess.PIPE)
p = subprocess.Popen(
['git', 'describe', '--dirty=.dirty', '--match=v*'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
result = p.communicate()[0]
if p.returncode == 0:
version = result.split()[0][1:]
version = version.replace('-', '.')
result = result.decode('ascii').strip()[1:] # strip spaces/newlines and initial v
if '-' in result: # not a tagged version
real_number, commit_count, commit_hash = result.split('-', 2)
version = '%s.post%s+%s' % (real_number, commit_count, commit_hash)
else:
version = result
return version
return '0'
else:
return '0.0.post%s' % len(subprocess.check_output(['git', 'rev-list', 'HEAD']).splitlines())
return '0.0'
class compile_translations(Command):
description = 'compile message catalogs to MO files via django compilemessages'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
curdir = os.getcwd()
try:
from django.core.management import call_command
for path, dirs, files in os.walk('atreal_openads'):
if 'locale' not in dirs:
continue
os.chdir(os.path.realpath(path))
call_command('compilemessages')
except ImportError:
sys.stderr.write('!!! Please install Django >= 1.4 to build translations\n')
finally:
os.chdir(curdir)
class build(_build):
sub_commands = [('compile_translations', None)] + _build.sub_commands
class install_lib(_install_lib):
def run(self):
self.run_command('compile_translations')
_install_lib.run(self)
setup(
name='passerelle-atreal-openads',
version=get_version(),
author='atReal',
author_email="support@atreal.fr",
description="A Publik connector for Passerelle to openADS",
classifiers=[
"Programming Language :: Python :: 2.7",
"Development Status :: Testing",
"License :: AGPLv3",
"Natural Language :: French",
"Operating System :: OS Independent",
"Topic :: Business"
],
include_package_data=True,
packages=find_packages(),
cmdclass={
'sdist': eo_sdist,
}
'build': build,
'compile_translations': compile_translations,
'install_lib': install_lib,
'sdist': eo_sdist
},
scripts=[],
install_requires=[
'python-magic'
]
)

0
tests/__init__.py Normal file
View File

225
tests/conftest.py Normal file
View File

@ -0,0 +1,225 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Configuration and fixtures for tests files."""
import os
import base64
import datetime
import pytest
from httmock import urlmatch, HTTMock, response
import django_webtest
from django.core.cache import cache
from django.core.files import File
from django.http.request import HttpRequest, QueryDict
from django.utils.encoding import force_text
from atreal_openads.models import (
ForwardFile,
Guichet,
Collectivite,
AtrealOpenads
)
@pytest.fixture(autouse=True)
def media(settings, tmpdir):
"""Set the media root to a temp dir created."""
settings.MEDIA_ROOT = str(tmpdir.mkdir('media'))
@pytest.fixture
def app(request):
"""Return a Django WebTest application."""
wtm = django_webtest.WebTestMixin()
wtm._patch_settings() # pylint: disable=protected-access
request.addfinalizer(wtm._unpatch_settings) # pylint: disable=protected-access
cache.clear()
return django_webtest.DjangoTestApp()
@pytest.fixture
def endpoint_dummy_cache(monkeypatch):
"""Monkey patch the Django cache to a 'dummy' one for all passerelle views."""
from django.core.cache import caches
import passerelle.views
monkeypatch.setattr(
passerelle.views, 'cache', caches['dummy'])
@urlmatch()
def internal_server_error(url, request): # pylint: disable=unused-argument
"""Return an HTTP 500 error."""
return response(500, 'Internal server error')
@pytest.fixture
def mock_500():
"""Mock an Internal Server Error."""
with HTTMock(internal_server_error):
yield None
@pytest.fixture
def relax_openssl(tmpdir):
'''OpenSSL default configuration has been really strict for some years,
this fixture set a temporary really permisive ciphers list.'''
openssl_cnf_path = tmpdir / 'openssl.cnf'
with openssl_cnf_path.open('w') as file_pt:
file_pt.write(u'''
[default_conf]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
CipherString = ALL''')
old_value = os.environ.get('OPENSSL_CONF', None)
try:
os.environ['OPENSSL_CONF'] = str(openssl_cnf_path)
yield
finally:
if old_value is None:
del os.environ['OPENSSL_CONF']
else:
os.environ['OPENSSL_CONF'] = old_value
@pytest.fixture
def fake_conf():
"""Return a dictionnary containing configuration items."""
conf = {
'CONNECTOR_NAME': 'atreal-openads',
'CONNECTOR_SLUG': 'atreal',
'COLLECTIVITE': 79,
'OPENADS_API_LOGIN': 'publik-passerelle',
'OPENADS_API_PASSWORD': force_text(base64.urlsafe_b64encode(os.urandom(20))),
'OPENADS_API_URL': 'http://openads.api/',
'FAKE_COOKIE_CRSF': force_text(base64.urlsafe_b64encode(os.urandom(20))),
'FAKE_NUMERO_DOSSIER': force_text(base64.urlsafe_b64encode(os.urandom(10))),
'TESTS_DIR': os.path.dirname(__file__)
}
conf['RESOURCES_DIR'] = os.path.join(conf['TESTS_DIR'], 'resources')
conf['TEST_FILE_CERFA_DIA'] = os.path.join(conf['RESOURCES_DIR'], 'cerfa_10072-02.pdf')
conf['TEST_FILE_PLAN_CADASTRAL'] = os.path.join(conf['RESOURCES_DIR'], 'plancadastral.pdf')
return conf
@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def atreal_openads(fake_conf, db):
"""Return an instance of a connector AtrealOpenads."""
return AtrealOpenads.objects.create( # pylint: disable=no-member
slug=fake_conf['CONNECTOR_SLUG'],
default_collectivite_openADS_id=fake_conf['COLLECTIVITE'],
openADS_API_url=fake_conf['OPENADS_API_URL'],
basic_auth_username=fake_conf['OPENADS_API_LOGIN'],
basic_auth_password=fake_conf['OPENADS_API_PASSWORD']
)
@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads):
"""Return an instance of a 'Collectivite'."""
return Collectivite.objects.create( # pylint: disable=no-member
name=u'Macollectivité',
connecteur=atreal_openads,
openADS_id='3'
)
@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1):
"""Return an instance of a 'Guichet'."""
return Guichet.objects.create( # pylint: disable=no-member
collectivite=collectivite_1,
ouverture_jour_h=datetime.time(9, 0),
fermeture_jour_h=datetime.time(17, 0),
ouverture_sem_d=1, # Lundi
fermeture_sem_d=5, # Vendredi
ouverture_sem_h=datetime.time(8, 30),
fermeture_sem_h=datetime.time(12, 15)
)
@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def forwardfile_1(fake_conf, db, atreal_openads, collectivite_1):
"""Return an instance of a 'ForwardFile'."""
return ForwardFile.objects.create( # pylint: disable=no-member
connecteur=atreal_openads,
collectivite=collectivite_1,
numero_demande='45641531',
numero_dossier=fake_conf['FAKE_NUMERO_DOSSIER'],
type_fichier='CERFA',
orig_filename=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA']),
content_type='application/pdf',
file_hash='ffdf456fdsvgb4bgfb6g4f5b',
upload_file=File(open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb'),
name=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA'])),
upload_status='pending'
)
@pytest.fixture
# pylint: disable=redefined-outer-name,invalid-name
def forwardfile_2(fake_conf, connecteur=None, collectivite=None):
"""Return a forward file object with some values but not saved in db."""
return ForwardFile(
connecteur=connecteur,
collectivite=collectivite,
numero_demande='45641531',
numero_dossier=fake_conf['FAKE_NUMERO_DOSSIER'],
type_fichier='CERFA',
orig_filename=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA']),
content_type='application/pdf',
file_hash='ffdf456fdsvgb4bgfb6g4f5b',
upload_file=File(open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb'),
name=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA'])),
upload_status='pending'
)
@pytest.fixture
def request_1():
"""Return an HttpRequest object with some default values."""
req = HttpRequest()
req._body = '' # pylint: disable=protected-access
req.path = '/'
req.method = 'GET'
req.encoding = 'utf-8'
req.GET = QueryDict(mutable=True) # required because of encoding setter
req.POST = QueryDict(mutable=True) # required because of encoding setter
req.content_type = 'application/json'
req.content_params = None
req.COOKIES = {}
req.META = {}
req._read_started = False # pylint: disable=protected-access
return req

49
tests/settings.py Normal file
View File

@ -0,0 +1,49 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Settings for testing."""
import os
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
# include app
INSTALLED_APPS += ( # noqa: F821, pylint: disable=undefined-variable
'atreal_openads',
)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'dummy': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache'
}
}
DATABASES = {
'default': {
'ENGINE': os.environ.get('DB_ENGINE', 'django.db.backends.sqlite3'),
'TEST': {
'NAME': 'passerelle-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],
},
}
}

1081
tests/test_atreal_openads.py Normal file

File diff suppressed because it is too large Load Diff

92
tests/test_forms.py Normal file
View File

@ -0,0 +1,92 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Testing forms."""
import datetime
from atreal_openads.forms import (
ForwardFileForm,
CollectiviteForm,
GuichetForm
)
from atreal_openads.models import (
Guichet,
Collectivite,
)
# pylint: disable=unused-argument,redefined-outer-name
def test_forwardfile_form(forwardfile_2, atreal_openads, collectivite_1):
"""Test for ForwardFileForm."""
form = ForwardFileForm()
assert form.instance is not None
form_with_instance = ForwardFileForm(instance=forwardfile_2, collectivite=collectivite_1)
assert form_with_instance.instance is forwardfile_2
assert form_with_instance.instance.collectivite is collectivite_1
form_with_instance = ForwardFileForm(instance=forwardfile_2, connecteur=atreal_openads)
assert form_with_instance.instance is forwardfile_2
assert form_with_instance.instance.connecteur is atreal_openads
# TODO check the queryset of the collectivite
# pylint: disable=unused-argument,redefined-outer-name
def test_collectivite_form(atreal_openads):
"""Test for CollectiviteForm."""
form = CollectiviteForm()
assert form.instance is not None
col = Collectivite(
connecteur=None,
name=u'Ma collectivité',
openADS_id=3
)
form_with_instance = CollectiviteForm(instance=col, connecteur=atreal_openads)
assert form_with_instance.instance is col
assert form_with_instance.instance.connecteur is atreal_openads
# pylint: disable=unused-argument,redefined-outer-name
def test_guichet_form(atreal_openads, collectivite_1):
"""Test for GuichetForm."""
form = GuichetForm()
assert form.instance is not None
gui = Guichet(
collectivite=None,
ouverture_jour_h=datetime.time(9, 0, 0),
fermeture_jour_h=datetime.time(18, 0, 0),
ouverture_sem_d=1,
fermeture_sem_d=5,
ouverture_sem_h=datetime.time(10, 30, 0),
fermeture_sem_h=datetime.time(12, 15, 0)
)
form_with_instance = GuichetForm(instance=gui, collectivite=collectivite_1)
assert form_with_instance.instance is gui
assert form_with_instance.instance.collectivite is collectivite_1

256
tests/test_utils.py Normal file
View File

@ -0,0 +1,256 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Testing utilities functions."""
import base64
import re
from django.utils.encoding import force_text
import pytest
from atreal_openads.utils import (
to_dash_case,
force_encoded_string_output,
strip_tags,
clean_spaces,
normalize,
get_file_data,
get_file_digest,
get_upload_path,
get_file_extension,
trunc_str_values,
DictDumper
)
def test_to_dash_case():
"""Test for function 'to_dash_case()'."""
astring = 'ACamelCaseName'
assert to_dash_case(astring) == 'a-camel-case-name'
assert to_dash_case('') == ''
def test_force_encoded_string_output(): # pylint: disable=invalid-name
"""Test for function 'force_encoded_string_output()'."""
def a_str_function():
"""Return a hardcoded string 'toto'."""
return str('toto')
ret = force_encoded_string_output(a_str_function)()
assert isinstance(ret, str)
ret = force_encoded_string_output(a_str_function, 'latin1')()
assert isinstance(ret, str)
def an_unicode_function():
"""Return a hardcoded string 'toto' in unicode."""
return u'toto'
ret = force_encoded_string_output(an_unicode_function)()
assert isinstance(ret, str)
ret = force_encoded_string_output(an_unicode_function, 'latin1')()
assert isinstance(ret, str)
def test_strip_tags():
"""Test for function 'strip_tags()'."""
base_string = 'aaa b cc '
assert strip_tags(base_string) == base_string
astring = base_string + '<em>dd'
assert strip_tags(astring) == base_string + 'dd'
astring = base_string + '<em>dd</em>'
assert strip_tags(astring) == base_string + 'dd'
astring = base_string + '<em>dd</em>'
assert strip_tags(astring) == base_string + 'dd'
astring = base_string + ' 1 < 3'
assert strip_tags(astring) == base_string + ' 1 < 3'
def test_clean_spaces():
"""Test for function 'clean_spaces()'."""
astring = 'aaa b cc '
assert clean_spaces(astring) == 'aaa b cc'
astring = 'a\ta b\nb c\rc d\\n\\r\\td'
assert clean_spaces(astring) == 'a a b b c c d d'
def test_normalize():
"""Test for function 'normalize()'."""
assert normalize(None) == ''
astring = 'aaa b cc '
assert normalize(astring) == 'aaa b cc'
astring = 'a\ta b\nb c\rc d\\n\\r\\td'
assert normalize(astring) == 'a a b b c c d d'
def test_get_file_data(fake_conf):
"""Test for function 'get_file_data()'."""
assert get_file_data(fake_conf['TEST_FILE_CERFA_DIA']) == base64.b64encode(
open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb').read())
assert get_file_data(fake_conf['TEST_FILE_CERFA_DIA'], b64=False) == open(
fake_conf['TEST_FILE_CERFA_DIA'], 'rb').read()
def test_get_file_digest(fake_conf):
"""Test for function 'get_file_digest()'."""
with open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb') as file_pt:
assert get_file_digest(file_pt) == ('cc90a620982760fdee16a5b4fe1b5ac3'
'b4fe868fd02d2f70b27f1e46d283ea51')
def test_get_upload_path(forwardfile_2):
"""Test for function 'get_upload_path()'."""
regex = r"^to_openADS__%s__%s\.pdf$" % (
'[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}h[0-9]{2}m[0-9]{2}s[0-9]+', 'ffdf')
assert re.search(regex, get_upload_path(forwardfile_2))
def test_get_file_extension():
"""Test for function 'get_file_extension()'."""
assert get_file_extension('afile.pdf') == '.pdf'
assert get_file_extension('afile', 'application/pdf') == '.pdf'
assert get_file_extension('') == ''
assert get_file_extension('afile') == ''
def test_trunc_str_values():
"""Test for function 'trunc_str_values()'."""
dic = {}
assert trunc_str_values(dic, 10) == dic
dic = {'a': '123456789'}
assert trunc_str_values(dic, 0) == {'a': u''}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 1) == {'a': u'1…'}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 2) == {'a': u'12…'}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 5) == {'a': u'12345…'}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 8) == {'a': u'12345678…'}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 9) == {'a': u'123456789'}
dic = {'a': '123456789'}
assert trunc_str_values(dic, 10) == dic
dic = {'a': '123456789', 'b123456789': '987654321'}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…'}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'}}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'}}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'},
'd': ['123456789']}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'}, 'd': [u'12345…']}
dic = {'a': '123456789', 'b123456789': '987654321', 'c': {'c1': 'ABCDEFGHIJK'},
'd': ['123456789', {'eeeeeeeeee': '132456789'}]}
assert trunc_str_values(dic, 5) == {'a': u'12345…', 'b123456789': u'98765…',
'c': {'c1': u'ABCDE…'},
'd': [u'12345…', {'eeeeeeeeee': u'13245…'}]}
def test_dict_dumper():
"""Test for methods of class 'DictDumper'."""
dic = {}
dumped = DictDumper(dic, use_json_dumps=False)
assert repr(dumped) == (u'DictDumper(dic=%r,max_str_len=%r,use_json_dumps=%r)' % (
dic, dumped.max_str_len, dumped.use_json_dumps))
assert str(dumped) == '{}'
assert force_text(dumped) == u'{}'
assert dic == dumped.dic
assert force_text(dic) == force_text(dumped)
dumped = DictDumper(dic, 0, use_json_dumps=False)
assert dic == dumped.dic
assert force_text(dic) == force_text(dumped)
dic = {'a': '123456789'}
dumped = DictDumper(dic, 10, use_json_dumps=False)
assert dic == dumped.dic
assert force_text(dic) == force_text(dumped)
dumped = DictDumper(dic, 5, use_json_dumps=False)
assert dic == dumped.dic
assert force_text(dumped) == force_text({'a': u'12345…'})
dumped = DictDumper(dic, 5, use_json_dumps=True)
assert dic == dumped.dic
assert force_text(dumped) == u'{"a": "12345\\u2026"}'
# pylint: disable=unused-argument,redefined-outer-name
def test_base_model(fake_conf, atreal_openads, collectivite_1, collectivite_1_guichet,
forwardfile_1):
"""Test for methods of class 'BaseModel' through instance of a ForwardFile."""
assert forwardfile_1.get_verbose_name() == 'Forward File'
assert forwardfile_1.get_verbose_name_plural() == 'Forward Files'
assert forwardfile_1.get_class_name() == 'ForwardFile'
assert forwardfile_1.get_class_name_plural() == 'ForwardFiles'
assert forwardfile_1.get_class_name_dash_case() == 'forward-file'
assert forwardfile_1.get_class_name_plural_dash_case() == 'forward-files'
assert forwardfile_1.get_class_name_title() == 'Forward File'
assert forwardfile_1.get_class_name_plural_title() == 'Forward Files'
assert forwardfile_1.get_url_name('list', plural=True) == 'list-forward-files'
assert forwardfile_1.get_absolute_url() == '/manage/atreal-openads/atreal/forward-file/%s' % forwardfile_1.id
assert forwardfile_1.get_edit_url() == '/manage/atreal-openads/atreal/edit-forward-file/%s' % forwardfile_1.id
assert forwardfile_1.get_delete_url() == '/manage/atreal-openads/atreal/delete-forward-file/%s' % forwardfile_1.id
assert forwardfile_1.get_list_url() == '/manage/atreal-openads/atreal/forward-files'
assert atreal_openads.get_class_name_plural() == 'AtrealOpenads'
assert atreal_openads.get_url_name('view') == 'view-connector'
params = atreal_openads.get_url_params(True)
assert params['connector'] == 'atreal-openads'
assert params['slug'] == atreal_openads.slug
with pytest.raises(Exception) as exception:
atreal_openads.get_list_url()
assert force_text(exception.value) == u"AtrealOpenads:get_list_url() method should not be called"
# TODO add more collectivite test cases
with pytest.raises(Exception) as exception:
collectivite_1_guichet.get_list_url()
assert force_text(exception.value) == u"Guichet:get_list_url() method should not be called"

324
tests/test_views.py Normal file
View File

@ -0,0 +1,324 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Testing views."""
from django.urls.base import resolve
from atreal_openads.views import (
get_connecteur_from_request,
get_collectivite_from_request,
AtrealOpenadsView,
ForwardFileView,
ForwardFileListView,
ForwardFileUpdateView,
ForwardFileDeleteView,
CollectiviteView,
CollectiviteListView,
CollectiviteCreateView,
CollectiviteUpdateView,
CollectiviteDeleteView,
GuichetView,
GuichetCreateView,
GuichetUpdateView,
GuichetDeleteView
)
from atreal_openads.models import Collectivite
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def test_get_connecteur_from_request(atreal_openads, forwardfile_1, request_1):
"""Test for function 'get_connecteur_from_request()'."""
request_1.path = '/manage/atreal-openads/%s/forward-file/%s' % (
atreal_openads.slug, forwardfile_1.id)
request_1.resolver_match = resolve(request_1.path)
view = ForwardFileView()
view.request = request_1
connecteur = get_connecteur_from_request(view)
assert connecteur is not None
assert connecteur.slug == atreal_openads.slug
# pylint: disable=unused-argument,redefined-outer-name
def test_get_collectivite_from_request(atreal_openads, collectivite_1, request_1): # noqa: E501, pylint: disable=invalid-name
"""Test for function 'get_collectivite_from_request()'."""
request_1.path = '/manage/atreal-openads/%s/collectivite/%s/forward-files' % (
atreal_openads.slug, collectivite_1.id)
request_1.resolver_match = resolve(request_1.path)
view = ForwardFileListView()
view.request = request_1
collectivite = get_collectivite_from_request(view)
assert collectivite is not None
assert collectivite.id == collectivite_1.id
# pylint: disable=too-many-statements
def test_forwardfile_view(atreal_openads, collectivite_1, forwardfile_1, request_1):
"""Test for views 'ForwardFile*View'."""
request_1.path = '/manage/atreal-openads/%s/forward-file/%s' % (
atreal_openads.slug, forwardfile_1.id)
request_1.resolver_match = resolve(request_1.path)
view = ForwardFileView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
view = ForwardFileUpdateView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/forward-file/%s' % (
atreal_openads.slug, forwardfile_1.id)
request_1.GET['back-to'] = 'list-forward-files'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/forward-files' % atreal_openads.slug
request_1.GET['back-to'] = 'col-list-forward-files'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivite/%s/forward-files' % (
atreal_openads.slug, collectivite_1.id)
view = ForwardFileDeleteView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
del request_1.GET['back-to']
url = view.get_success_url()
assert url == u'/atreal-openads/%s/' % atreal_openads.slug
request_1.GET['back-to'] = 'list-forward-files'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/forward-files' % atreal_openads.slug
request_1.GET['back-to'] = 'col-list-forward-files'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivite/%s/forward-files' % (
atreal_openads.slug, collectivite_1.id)
request_1.path = '/manage/atreal-openads/%s/collectivite/%s/forward-files' % (
atreal_openads.slug, collectivite_1.id)
request_1.resolver_match = resolve(request_1.path)
view = ForwardFileListView()
view.request = request_1
view.object_list = []
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite'].id == collectivite_1.id
queryset = view.get_queryset()
assert queryset.query is not None
assert list(queryset.query.order_by) == ['id']
assert queryset.query.default_ordering
assert queryset.query.get_meta().ordering == ['-last_update_datetime']
assert queryset.ordered
request_1.GET['order-by'] = '-id'
queryset = view.get_queryset()
assert queryset.query is not None
assert list(queryset.query.order_by) == ['-id']
assert queryset.query.default_ordering
request_1.path = '/manage/atreal-openads/%s/forward-files' % atreal_openads.slug
request_1.resolver_match = resolve(request_1.path)
del request_1.GET['back-to']
del request_1.GET['order-by']
view = ForwardFileListView()
view.request = request_1
view.object_list = []
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
queryset = view.get_queryset()
assert queryset.query is not None
assert list(queryset.query.order_by) == ['id']
assert queryset.query.default_ordering
assert queryset.query.get_meta().ordering == ['-last_update_datetime']
assert queryset.ordered
# pylint: disable=too-many-statements
def test_collectivite_view(atreal_openads, collectivite_1, forwardfile_1, request_1):
"""Test for views 'Collectivite*View'."""
request_1.path = '/manage/atreal-openads/%s/collectivite/%s' % (
atreal_openads.slug, collectivite_1.id)
request_1.resolver_match = resolve(request_1.path)
view = CollectiviteView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['guichet_add_url'] == (
u'/manage/atreal-openads/%s/collectivite/%s/create-guichet' % (
atreal_openads.slug, collectivite_1.id))
assert context['forward_files_list_url'] == (
u'/manage/atreal-openads/%s/collectivite/%s/forward-files' % (
atreal_openads.slug, collectivite_1.id))
view = CollectiviteUpdateView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivite/%s' % (
atreal_openads.slug, collectivite_1.id)
request_1.GET['back-to'] = 'list-collectivites'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivites' % atreal_openads.slug
view = CollectiviteDeleteView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
del request_1.GET['back-to']
url = view.get_success_url()
assert url == u'/atreal-openads/%s/' % atreal_openads.slug
request_1.GET['back-to'] = 'list-collectivites'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivites' % atreal_openads.slug
view = CollectiviteCreateView()
request_1.path = '/manage/atreal-openads/%s/create-collectivite' % atreal_openads.slug
request_1.resolver_match = resolve(request_1.path)
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
kwargs = view.get_form_kwargs()
assert kwargs['connecteur'].slug == atreal_openads.slug
del request_1.GET['back-to']
url = view.get_success_url()
assert url == u'/atreal-openads/%s/' % atreal_openads.slug
request_1.GET['back-to'] = 'list-collectivites'
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivites' % atreal_openads.slug
request_1.path = '/manage/atreal-openads/%s/collectivites' % atreal_openads.slug
request_1.resolver_match = resolve(request_1.path)
view = CollectiviteListView()
view.request = request_1
view.object_list = []
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite_add_url'] == (
u'/manage/atreal-openads/%s/create-collectivite' % atreal_openads.slug)
queryset = view.get_queryset()
assert queryset.query is not None
assert list(queryset.query.order_by) == ['id']
assert queryset.query.default_ordering
assert queryset.query.get_meta().ordering == ['name']
assert queryset.ordered
request_1.GET['order-by'] = '-id'
queryset = view.get_queryset()
assert queryset.query is not None
assert list(queryset.query.order_by) == ['-id']
assert queryset.query.default_ordering
def test_guichet_view(atreal_openads, collectivite_1, collectivite_1_guichet, request_1):
"""Test for views 'Guichet*View'."""
request_1.path = '/manage/atreal-openads/%s/collectivite/%s/guichet/%s' % (
atreal_openads.slug, collectivite_1.id, collectivite_1_guichet.id)
request_1.resolver_match = resolve(request_1.path)
view = GuichetView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite'].id == collectivite_1.id
view = GuichetUpdateView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite'].id == collectivite_1.id
view = GuichetDeleteView()
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite'].id == collectivite_1.id
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivite/%s' % (
atreal_openads.slug, collectivite_1.id)
view = GuichetCreateView()
request_1.path = '/manage/atreal-openads/%s/collectivite/%s/create-guichet' % (
atreal_openads.slug, collectivite_1.id)
request_1.resolver_match = resolve(request_1.path)
view.request = request_1
view.object = None
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['connecteur'].slug == atreal_openads.slug
assert context['collectivite'].id == collectivite_1.id
kwargs = view.get_form_kwargs()
assert kwargs['collectivite'].id == collectivite_1.id
url = view.get_success_url()
assert url == u'/manage/atreal-openads/%s/collectivite/%s' % (
atreal_openads.slug, collectivite_1.id)
def test_connecteur_view(atreal_openads, request_1):
"""Test for views 'AtrealOpenadsView'."""
request_1.path = '/atreal-openads/%s/' % atreal_openads.slug
request_1.resolver_match = resolve(request_1.path)
view = AtrealOpenadsView()
view.request = request_1
view.object = atreal_openads
view.kwargs = request_1.resolver_match.kwargs
context = view.get_context_data()
assert context['collectivite_fields'] == Collectivite.get_fields()
assert context['collectivite_add_url'] == (
u'/manage/atreal-openads/%s/create-collectivite' % atreal_openads.slug)

56
tox.ini Normal file
View File

@ -0,0 +1,56 @@
; This file is part of passerelle-atreal-openads - a Publik connector to openADS
;
; Copyright (C) 2019 Atreal
;
; This program is free software: you can redistribute it and/or modify it
; under the terms of the GNU Affero General Public License as published
; by the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU Affero General Public License for more details.
;
; You should have received a copy of the GNU Affero General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
[tox]
envlist = py3-junit-coverage
toxworkdir = {env:TMPDIR:/tmp}/tox-{env:USER}/passerelle-atreal-openads/{env:BRANCH_NAME:}
[testenv]
usedevelop =
coverage: True
nocoverage: False
setenv =
DB_ENGINE=django.db.backends.postgresql_psycopg2
DJANGO_SETTINGS_MODULE=passerelle.settings
PASSERELLE_SETTINGS_FILE=tests/settings.py
coverage: COVERAGE=--cov-report xml --cov-report html --cov=atreal_openads/
junit: JUNIT=--junitxml=junit-{envname}.xml
deps =
https://git.entrouvert.org/entrouvert/passerelle/archive/main.tar.gz
pytest-cov
pytest-django
pytest>=3.3.0
WebTest
mock<4
httmock
psycopg2-binary<2.9
pylint<1.8
pylint-django<0.8.1
django-webtest<1.9.3
xmlschema<1.1
commands =
py.test {posargs: {env:COVERAGE:} {env:JUNIT:} tests/}
coverage: ./pylint.sh atreal_openads/
[testenv:manage]
usedevelop = True
setenv =
DJANGO_SETTINGS_MODULE=passerelle.settings
deps =
https://git.entrouvert.org/entrouvert/passerelle/archive/main.tar.gz
commands =
python3 ./manage.py {posargs:--help}