comparison twisted/plugins/pubsub.py @ 414:ccb2a22ea0fc

Python 3 port: /!\ Python 3.6+ is now needed to use SàT Pubsub /!\ instability may occur and features may not be working anymore, this will improve with time The same procedure as in backend has been applied (check backend commit ab2696e34d29 logs for details). Python minimal version has been updated in setup.py
author Goffi <goffi@goffi.org>
date Fri, 16 Aug 2019 12:53:33 +0200
parents a58610ab2983
children 412d26a9b2c2
comparison
equal deleted inserted replaced
413:a5edf5e1dd74 414:ccb2a22ea0fc
1 #!/usr/bin/python 1 #!/usr/bin/env python3
2 #-*- coding: utf-8 -*- 2 #-*- coding: utf-8 -*-
3 3
4 # Copyright (c) 2012-2019 Jérôme Poisson 4 # Copyright (c) 2012-2019 Jérôme Poisson
5 # Copyright (c) 2003-2011 Ralph Meijer 5 # Copyright (c) 2003-2011 Ralph Meijer
6 6
65 from wokkel.iwokkel import IPubSubResource 65 from wokkel.iwokkel import IPubSubResource
66 from wokkel import data_form 66 from wokkel import data_form
67 from wokkel import pubsub 67 from wokkel import pubsub
68 from wokkel import rsm 68 from wokkel import rsm
69 from wokkel import mam 69 from wokkel import mam
70 from zope.interface import implements 70 from zope.interface import implementer
71 71
72 from sat_pubsub import const 72 from sat_pubsub import const
73 from sat_pubsub import mam as pubsub_mam 73 from sat_pubsub import mam as pubsub_mam
74 from sat_pubsub import pubsub_admin 74 from sat_pubsub import pubsub_admin
75 from sat_pubsub.backend import BackendService, ExtraDiscoHandler 75 from sat_pubsub.backend import BackendService, ExtraDiscoHandler
76 from sat_pubsub.schema import SchemaHandler 76 from sat_pubsub.schema import SchemaHandler
77 from sat_pubsub.privilege import PrivilegesHandler 77 from sat_pubsub.privilege import PrivilegesHandler
78 from sat_pubsub.delegation import DelegationsHandler 78 from sat_pubsub.delegation import DelegationsHandler
79 from os.path import expanduser, realpath 79 from os.path import expanduser, realpath
80 import ConfigParser 80 import configparser
81 81
82 82
83 def coerceListType(value): 83 def coerceListType(value):
84 return csv.reader( 84 return next(csv.reader(
85 [value], delimiter=",", quotechar='"', skipinitialspace=True 85 [value], delimiter=",", quotechar='"', skipinitialspace=True
86 ).next() 86 ))
87 87
88 88
89 def coerceJidListType(value): 89 def coerceJidListType(value):
90 values = [JID(v) for v in coerceListType(value)] 90 values = [JID(v) for v in coerceListType(value)]
91 if any((j.resource for j in values)): 91 if any((j.resource for j in values)):
92 raise ValueError(u"you must use bare jids") 92 raise ValueError("you must use bare jids")
93 return values 93 return values
94 94
95 95
96 96
97 OPT_PARAMETERS_BOTH = [ 97 OPT_PARAMETERS_BOTH = [
110 OPT_PARAMETERS_CFG = [ 110 OPT_PARAMETERS_CFG = [
111 ["admins_jids_list", None, [], "List of administrators' bare jids", 111 ["admins_jids_list", None, [], "List of administrators' bare jids",
112 coerceJidListType] 112 coerceJidListType]
113 ] 113 ]
114 114
115 CONFIG_FILENAME = u'sat' 115 CONFIG_FILENAME = 'sat'
116 # List of the configuration filenames sorted by ascending priority 116 # List of the configuration filenames sorted by ascending priority
117 CONFIG_FILES = [realpath(expanduser(path) + CONFIG_FILENAME + '.conf') for path in ( 117 CONFIG_FILES = [realpath(expanduser(path) + CONFIG_FILENAME + '.conf') for path in (
118 '/etc/', '/etc/{}/'.format(CONFIG_FILENAME), 118 '/etc/', '/etc/{}/'.format(CONFIG_FILENAME),
119 '~/', '~/.', 119 '~/', '~/.',
120 '.config/', '.config/.', 120 '.config/', '.config/.',
140 """ 140 """
141 # If we do it the reading later: after the command line options have been parsed, there's no good way to know 141 # If we do it the reading later: after the command line options have been parsed, there's no good way to know
142 # if the options values are the hard-coded ones or if they have been passed on the command line. 142 # if the options values are the hard-coded ones or if they have been passed on the command line.
143 143
144 # FIXME: must be refactored + code can be factorised with backend 144 # FIXME: must be refactored + code can be factorised with backend
145 config_parser = ConfigParser.SafeConfigParser() 145 config_parser = configparser.ConfigParser()
146 config_parser.read(CONFIG_FILES) 146 config_parser.read(CONFIG_FILES)
147 for param in self.optParameters + OPT_PARAMETERS_CFG: 147 for param in self.optParameters + OPT_PARAMETERS_CFG:
148 name = param[0] 148 name = param[0]
149 try: 149 try:
150 value = config_parser.get(CONFIG_SECTION, name) 150 value = config_parser.get(CONFIG_SECTION, name)
151 if isinstance(value, unicode):
152 value = value.encode('utf-8')
153 try: 151 try:
154 param[2] = param[4](value) 152 param[2] = param[4](value)
155 except IndexError: # the coerce method is optional 153 except IndexError: # the coerce method is optional
156 param[2] = value 154 param[2] = value
157 except Exception as e: 155 except Exception as e:
158 log.err(u'Invalid value for setting "{name}": {msg}'.format( 156 log.err('Invalid value for setting "{name}": {msg}'.format(
159 name=name, msg=e)) 157 name=name, msg=e))
160 sys.exit(1) 158 sys.exit(1)
161 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): 159 except (configparser.NoSectionError, configparser.NoOptionError):
162 pass 160 pass
163 usage.Options.__init__(self) 161 usage.Options.__init__(self)
164 for opt_data in OPT_PARAMETERS_CFG: 162 for opt_data in OPT_PARAMETERS_CFG:
165 self[opt_data[0]] = opt_data[2] 163 self[opt_data[0]] = opt_data[2]
166 164
171 raise NotImplementedError('memory backend is not available at the moment') 169 raise NotImplementedError('memory backend is not available at the moment')
172 170
173 self['jid'] = JID(self['jid']) if self['jid'] else None 171 self['jid'] = JID(self['jid']) if self['jid'] else None
174 172
175 173
174 @implementer(IServiceMaker, IPlugin)
176 class SatPubsubMaker(object): 175 class SatPubsubMaker(object):
177 implements(IServiceMaker, IPlugin)
178 tapname = "sat-pubsub" 176 tapname = "sat-pubsub"
179 description = u"Salut à Toi Publish-Subscribe Service Component".encode('utf-8') 177 description = "Salut à Toi Publish-Subscribe Service Component"
180 options = Options 178 options = Options
181 179
182 def makeService(self, config): 180 def makeService(self, config):
183 if not config['jid'] or not config['xmpp_pwd']: 181 if not config['jid'] or not config['xmpp_pwd']:
184 raise usage.UsageError("You must specify jid and xmpp_pwd") 182 raise usage.UsageError("You must specify jid and xmpp_pwd")
196 'db_name': 'database', 194 'db_name': 'database',
197 'db_host': 'host', 195 'db_host': 'host',
198 'db_port': 'port', 196 'db_port': 'port',
199 } 197 }
200 kwargs = {} 198 kwargs = {}
201 for config_k, k in keys_map.iteritems(): 199 for config_k, k in keys_map.items():
202 v = config.get(config_k) 200 v = config.get(config_k)
203 if v is None: 201 if v is None:
204 continue 202 continue
205 kwargs[k] = v 203 kwargs[k] = v
206 dbpool = adbapi.ConnectionPool('psycopg2', 204 dbpool = adbapi.ConnectionPool('psycopg2',
228 226
229 if config["verbose"]: 227 if config["verbose"]:
230 cs.logTraffic = True 228 cs.logTraffic = True
231 229
232 FallbackHandler().setHandlerParent(cs) 230 FallbackHandler().setHandlerParent(cs)
233 VersionHandler(u'SàT Pubsub', sat_pubsub.__version__).setHandlerParent(cs) 231 VersionHandler('SàT Pubsub', sat_pubsub.__version__).setHandlerParent(cs)
234 DiscoHandler().setHandlerParent(cs) 232 DiscoHandler().setHandlerParent(cs)
235 233
236 ph = PrivilegesHandler(config['jid']) 234 ph = PrivilegesHandler(config['jid'])
237 ph.setHandlerParent(cs) 235 ph.setHandlerParent(cs)
238 bs.privilege = ph 236 bs.privilege = ph