export4kaboom : gestion temporaire du statut d'observateur
[progfou.git] / web / export4kaboom
CommitLineData
cad0f8f5
P
1#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3"""
4export4kaboom - Outil d'export des référentiels adapté pour Kaboom
5
6Copyright : Agence universitaire de la Francophonie — www.auf.org
7Licence : GNU General Public Licence, version 3
8Auteur : Jean Christophe André
9Création : 20 octobre 2017
10
11Debian-Depends:
12
13Mise en place dans Apache :
14 ScriptAlias /export4kaboom /usr/local/lib/export4kaboom
15Usage :
16 http://references.auf.org/export4kaboom/implantations.json
17 http://references.auf.org/export4kaboom/etablissements.json
18"""
19import os
20import sys
21import json
22import urllib.request
23
24def http_reply(data, mime_type=None, charset=None, headers={}, outfile=sys.stdout):
25 if data is None:
26 data = ''
27 # préparation des champs MIME
28 if mime_type is None:
29 mime_type = 'text/plain'
30 if charset is None:
31 charset = getattr(outfile, 'encoding', None)
32 if charset:
33 charset_spec = '; charset={}'.format(charset)
34 else:
35 charset_spec = ''
36 # préparation des en-têtes de la réponse
37 _headers = {
38 'Content-Type': '{}{}'.format(mime_type, charset_spec),
39 'Content-Length': len(data) if data else 0,
40 'Status': '200 OK',
41 'Pragma': 'no-cache',
42 'Expires': '0',
43 #'Vary': 'Content-Encoding',
44 }
45 if headers:
46 _headers.update(headers)
47 # envoi de la réponse
48 _headers = ''.join(("{}: {}\r\n".format(k, v) for k,v in _headers.items()))
49 outfile.write(_headers + "\r\n")
50 outfile.write(data)
51 outfile.flush()
52
53def http_redirect(location):
54 data = """If you see this, it means the automatic redirection has \
55 failed.\r\nPlease go to {}\r\n""".format(location)
56 headers = {'Status': '302 Redirection', 'Location': location}
57 http_reply(data, headers=headers)
58
6aedbb0e
P
59def hack_observateur(data):
60 for x in data:
61 if x['nom'].startswith('[Observateur] '):
62 x.update({'nom': x['nom'][14:]})
63 x.update({'statut': 'O'})
64
cad0f8f5
P
65def country_code_to_name(data, fields=[]):
66 res = urllib.request.urlopen('http://references.auf.org/export/pays.json')
67 country = json.loads(res.read().decode('utf-8'))
68 country = {x['code']: x for x in country}
69 for x in data:
70 for f in fields:
71 x.update({f+'_nom': country[x[f]]['nom']})
72
73if __name__ == '__main__':
74 # initialisation
75 path_info = os.environ.get('PATH_INFO', '')
76 path_prefix = os.environ.get('REQUEST_URI', '')
77 if len(path_info) > 0:
78 path_prefix = path_prefix[:-len(path_info)]
79 # routage
80 if path_info == '':
81 http_redirect(path_prefix + '/')
82 elif path_info == '/':
83 l = [
84 '/export/pays.json',
85 '/export4kaboom/implantations.json',
86 '/export4kaboom/etablissements.json',
87 ]
88 l = ['<li><a href="%s">%s</a></li>' % (f, f) for f in sorted(l)]
89 title = '<p>Liste des exports disponibles&nbsp;:</p>\n'
90 data = '<html>\n' + title + '<ul>\n' + '\n'.join(l) + '\n</ul>\n</html>'
91 http_reply(data, headers={'Content-Type': 'text/html'})
92 elif path_info == '/etablissements.json':
93 res = urllib.request.urlopen('http://references.auf.org/export/etablissements.json')
94 data = json.loads(res.read().decode('utf-8'))
95 data = [x for x in data if x['membre'] is True] # juste les membres
6aedbb0e 96 hack_observateur(data)
cad0f8f5
P
97 country_code_to_name(data, ['pays'])
98 data = json.dumps(data, indent=' ')
99 http_reply(data, mime_type='application/json')
100 elif path_info == '/implantations.json':
101 res = urllib.request.urlopen('http://references.auf.org/export/implantations.json')
102 data = json.loads(res.read().decode('utf-8'))
103 data = [x for x in data if x['statut'] == 1] # juste les ouvertes
104 country_code_to_name(data, ['adresse_physique_pays', 'adresse_postale_pays'])
105 data = json.dumps(data, indent=' ')
106 http_reply(data, mime_type='application/json')
107 else: # réponse par défaut
108 http_reply("Requête '{}' non gérée.".format(path_info))
109 sys.exit(0)