From 2a563b7b12b138e982479509360fc96258625603 Mon Sep 17 00:00:00 2001 From: Vaclav Vorisek Date: Mon, 7 Mar 2022 15:24:00 +0100 Subject: [PATCH 1/3] 4901 code cleand and reformat --- agi-bin/xuc-request.py | 52 +++++++++--------- asterisk-bin/change-pass-vm | 6 +-- bin/simultcalls.py | 44 +++++++-------- bin/tzdataexport.py | 103 ++++++++++++++++++------------------ 4 files changed, 105 insertions(+), 100 deletions(-) diff --git a/agi-bin/xuc-request.py b/agi-bin/xuc-request.py index 1d8a229..a02bdf1 100755 --- a/agi-bin/xuc-request.py +++ b/agi-bin/xuc-request.py @@ -13,22 +13,19 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import object -__version__ = '$Revision$' -__date__ = '$Date$' -__copyright__ = 'Copyright (C) 2014-2017 Avencall' -__author__ = 'AV' +__version__ = '$Revision$' +__date__ = '$Date$' +__copyright__ = 'Copyright (C) 2014-2017 Avencall' +__author__ = 'AV' -import sys -import requests +import configparser +import json import logging +import sys import traceback -import json -import configparser + +import requests from xivo.agi import AGI agi = AGI() @@ -39,9 +36,9 @@ XUC_SERVER_IP = xuc_config.get('XUC', 'XUC_SERVER_IP') XUC_SERVER_PORT = xuc_config.get('XUC', 'XUC_SERVER_PORT') XUC_SERVER = XUC_SERVER_IP + ':' + XUC_SERVER_PORT -TogglePauseURL="http://" + XUC_SERVER + "/xuc/api/1.0/togglePause/" -AgentLoginURL="http://" + XUC_SERVER + "/xuc/api/1.0/agentLogin/" -AgentLogoutURL="http://" + XUC_SERVER + "/xuc/api/1.0/agentLogout/" +TogglePauseURL = "http://" + XUC_SERVER + "/xuc/api/1.0/togglePause/" +AgentLoginURL = "http://" + XUC_SERVER + "/xuc/api/1.0/agentLogin/" +AgentLogoutURL = "http://" + XUC_SERVER + "/xuc/api/1.0/agentLogout/" # User configuration DEBUG_MODE = False @@ -50,7 +47,7 @@ LOGFILE = '/var/log/xivo-xuc-agent-webservices.log' CONNECTION_TIMEOUT = 2 # Factory configuration -URL_HEADERS = { 'User-Agent' : 'XiVO Webservice AGI' } +URL_HEADERS = {'User-Agent': 'XiVO Webservice AGI'} logger = logging.getLogger() @@ -61,6 +58,7 @@ class Syslogger(object): global logger logger.error(data) + def init_logging(debug_mode): if debug_mode: logger.setLevel(logging.DEBUG) @@ -76,18 +74,20 @@ def init_logging(debug_mode): syslogger = Syslogger() sys.stderr = syslogger -def logAgiFile(message, error = False): + +def logAgiFile(message, error=False): agi.verbose(message) if error == False: logger.info(message) else: logger.error(message) + def send_request(url, customHeaders, params): try: result = requests.post(url, - headers = customHeaders, - data = json.dumps(params), + headers=customHeaders, + data=json.dumps(params), timeout=CONNECTION_TIMEOUT) agi.verbose("Request sent to server") @@ -103,8 +103,9 @@ def send_request(url, customHeaders, params): logger.debug(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) finally: - agi.set_variable("XIVO_XUCWS_STATUS_CODE",str(result.status_code)) - agi.set_variable("XIVO_XUCWS_CONTENT",str(result.content)) + agi.set_variable("XIVO_XUCWS_STATUS_CODE", str(result.status_code)) + agi.set_variable("XIVO_XUCWS_CONTENT", str(result.content)) + def toggle_pause(phonenumber): params = {'phoneNumber': phonenumber} @@ -112,23 +113,26 @@ def toggle_pause(phonenumber): logAgiFile("Toggle Pause request for agent at phone: " + str(phonenumber)) send_request(TogglePauseURL, headers, params) + def log_agent(phonenumber, agentnumber): params = {'agentphonenumber': phonenumber, 'agentnumber': agentnumber} headers = {'content-type': 'application/json'} logAgiFile("Agent login request for agentnumber: " + str(agentnumber) + " at phone: " + str(phonenumber)) send_request(AgentLoginURL, headers, params) + def logout_agent(phonenumber): params = {'phoneNumber': phonenumber} headers = {'content-type': 'application/json'} logAgiFile("Agent logout request for agent logged on phone: " + str(phonenumber)) send_request(AgentLogoutURL, headers, params) + def main(): agi.verbose('---------------------------------------------------') init_logging(DEBUG_MODE) - if(len(XUC_SERVER) <= 0): + if (len(XUC_SERVER) <= 0): logAgiFile('XUC address is not defined, the agent login/pause can\'t be used') logAgiFile('Please configure the address in the /etc/xivo-xuc.conf file') sys.exit(2) @@ -137,7 +141,7 @@ def main(): if len(sys.argv) < 2: logAgiFile("Wrong number of arguments", error=True) sys.exit(1) - agi.verbose('Request: '+sys.argv[1]) + agi.verbose('Request: ' + sys.argv[1]) if sys.argv[1] == 'togglePause': toggle_pause(sys.argv[2]) elif sys.argv[1] == 'agentLogin': @@ -152,7 +156,7 @@ def main(): except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() logger.error(repr(traceback.format_exception(exc_type, exc_value, - exc_traceback))) + exc_traceback))) sys.exit(1) sys.exit(1) diff --git a/asterisk-bin/change-pass-vm b/asterisk-bin/change-pass-vm index fe10d98..c06f528 100755 --- a/asterisk-bin/change-pass-vm +++ b/asterisk-bin/change-pass-vm @@ -18,11 +18,11 @@ import os import sys +import xivo_dao from xivo_auth_client import Client as Auth from xivo_confd_client import Client as Confd from xivo_dao import accesswebservice_dao from xivo_dao import asterisk_conf_dao -import xivo_dao XIVO_AUTH_TOKEN_TIMEOUT = 10 @@ -55,7 +55,6 @@ def mds_get_confd_host(): def get_confd_client_config(): - is_mds = os.path.exists('/var/lib/xivo/mds_enabled') if is_mds: @@ -80,7 +79,8 @@ def get_confd_client_config(): config['password'] = passwd if is_mds: - auth = Auth(config['host'], username=config['username'], password=config['password'], verify_certificate=config['verify_certificate']) + auth = Auth(config['host'], username=config['username'], password=config['password'], + verify_certificate=config['verify_certificate']) token_data = auth.token.new('xivo_service', expiration=XIVO_AUTH_TOKEN_TIMEOUT) config['token'] = token_data['token'] diff --git a/bin/simultcalls.py b/bin/simultcalls.py index e73f905..9c96cf6 100755 --- a/bin/simultcalls.py +++ b/bin/simultcalls.py @@ -16,34 +16,34 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see -from __future__ import print_function -from __future__ import division -from future import standard_library -standard_library.install_aliases() -from builtins import range -from past.utils import old_div -__version__ = '$Revision$' -__date__ = '$Date$' -__author__ = 'Corentin Le Gall' -import cjson +__version__ = '$Revision$' +__date__ = '$Date$' +__author__ = 'Corentin Le Gall' + import csv import getopt import os import sys import time -import urllib.request, urllib.parse, urllib.error +import urllib.error +import urllib.request + +import cjson + def zero_seconds(val): global histo_seconds if val not in histo_seconds: histo_seconds[val] = 0 + def zero_minutes(val): global histo_minutes if val not in histo_minutes: histo_minutes[val] = 0 + def gettimelength(start, length, chan1, chan2, timefmt): cond = True ret = [] @@ -58,6 +58,7 @@ def gettimelength(start, length, chan1, chan2, timefmt): ret = [] return ret + sc_mode = None sc_channel = None sc_begin = None @@ -105,7 +106,7 @@ if opts[1]: infile_or_ip = opts[1][0] if not infile_or_ip or not sc_mode or sc_help: - codename = 'simultcalls.py' # sys.argv[0] + codename = 'simultcalls.py' # sys.argv[0] print() print('Usage : you should use this tool in either mode :') print(' %s [options] -m file xivo_cdr_XXX.csv (exported CSV)' % codename) @@ -145,7 +146,7 @@ if sc_mode == 'ip': sc_end = today title = '%s from %s to %s' % (remoteip, sc_begin, sc_end) w = urllib.request.urlopen('https://%s/service/ipbx/json.php/%s/call_management/cdr/?act=search&dbeg=%s&dend=%s' - % (remoteip, mode, sc_begin, sc_end)) + % (remoteip, mode, sc_begin, sc_end)) wr = w.readlines() if wr: for z in cjson.decode(''.join(wr)): @@ -172,7 +173,7 @@ elif sc_mode == 'file': f = open(infile_or_ip) title = 'file : %s' % infile_or_ip print('reading csv file from %s' % infile_or_ip) - csvreader = csv.reader(f, delimiter = ';') + csvreader = csv.reader(f, delimiter=';') for line in csvreader: nl += 1 if len(line) == 16: @@ -188,7 +189,7 @@ else: t2 = time.time() print('... (%.1f seconds spent for %d items)\n' \ - 'filling histogram' % (t2-t1, len(mystats))) + 'filling histogram' % (t2 - t1, len(mystats))) if not mystats: print('no data found matching your channel "%s" - exiting' % sc_channel) @@ -197,7 +198,7 @@ if not mystats: # mystats is filled now starttime_seconds = mystats[0][0] -starttime_minutes = old_div(mystats[0][0],60) +starttime_minutes = mystats[0][0] / 60 histo_seconds = {} histo_minutes = {} @@ -215,7 +216,7 @@ for st in mystats: t3 = time.time() print('... (%.1f seconds spent, %d bins filled)\n' \ - 'sorting and writing to files' % (t3-t2, len(histo_seconds))) + 'sorting and writing to files' % (t3 - t2, len(histo_seconds))) datfilename_s = '/tmp/stat_seconds_%s.dat' % now datfilename_m = '/tmp/stat_minutes_%s.dat' % now @@ -230,19 +231,19 @@ hsk.sort() for h in hsk: ttime = starttime_seconds + h h0 = histo_seconds[h] - time_min = old_div(ttime,60) - starttime_minutes + time_min = ttime / 60 - starttime_minutes if time_min in histo_minutes: histo_minutes[time_min] = histo_minutes[time_min] + h0 / 60.0 else: histo_minutes[time_min] = h0 / 60.0 if h0 == max_s_value: - for hbin in [h-1, h, h+1]: + for hbin in [h - 1, h, h + 1]: if hbin not in max_s_list: max_s_list.append(hbin) if h0 > max_s_value: max_s_value = h0 - max_s_list = [h-1, h, h+1] + max_s_list = [h - 1, h, h + 1] zero_minutes(time_min - 1) zero_minutes(time_min + 1) @@ -268,12 +269,13 @@ for h in hmk: datfile_m.close() t4 = time.time() -print('... (%.1f seconds spent)' % (t4-t3)) +print('... (%.1f seconds spent)' % (t4 - t3)) # make plots if requested pstmpplot = None if sc_ps or sc_x11 or sc_image: import Gnuplot + g = Gnuplot.Gnuplot() g('set timestamp') g('set title "%s"' % title) diff --git a/bin/tzdataexport.py b/bin/tzdataexport.py index 19342c3..9e53ab5 100755 --- a/bin/tzdataexport.py +++ b/bin/tzdataexport.py @@ -31,16 +31,10 @@ More info about the tz database can be found here: - http://www.twinsun.com/tz/tz-link.htm """ -from __future__ import print_function -from builtins import zip -from builtins import map -from builtins import next -from builtins import object __version__ = "$Revision$ $Date$" import datetime -import itertools import logging import re import string @@ -61,7 +55,7 @@ def is_abbrv_of(abbrv, word): False """ return word.startswith(abbrv) - + def is_unambiguous_abbrv_of(abbrv, word, context): """Return True if abbrv is the only abbreviation of word in context context. @@ -130,14 +124,14 @@ class RuleLine(object): - rules : the name of the rule that currently apply in the zone, or None if the standard time always applies """ - + _FROMFIELD_CONTEXT = ('minimum', 'maximum', 'only') _TOFIELD_CONTEXT = ('minimum', 'maximum') _INFIELD_CONTEXT = ('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december') _WEEKDAY_CONTEXT = ('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday') - + def __init__(self, name, from_, to, type, in_, on, at, save): self.name = name self.from_ = self._fromfield_to_year(from_.lower()) @@ -147,27 +141,27 @@ class RuleLine(object): self.on = self._onfield_to_day(on) self.at, self.at_time_type = self._atfield_to_seconds_and_type(at) self.save = self._savefield_to_seconds(save) - + @classmethod def _fromfield_to_year(cls, fromfield): if is_unambiguous_abbrv_of(fromfield, 'minimum', cls._FROMFIELD_CONTEXT): - return 0 # Arbitrary 'small' year value + return 0 # Arbitrary 'small' year value elif is_unambiguous_abbrv_of(fromfield, 'maximum', cls._FROMFIELD_CONTEXT): - return 20000 # Arbitrary 'large' year value + return 20000 # Arbitrary 'large' year value else: return int(fromfield) - + @classmethod def _tofield_to_year(cls, tofield, fromval): if is_unambiguous_abbrv_of(tofield, 'minimum', cls._TOFIELD_CONTEXT): - return 0 # Arbitrary 'small' year value + return 0 # Arbitrary 'small' year value elif is_unambiguous_abbrv_of(tofield, 'maximum', cls._TOFIELD_CONTEXT): - return 20000 # Arbitrary 'large' year value + return 20000 # Arbitrary 'large' year value elif is_unambiguous_abbrv_of(tofield, 'only', cls._TOFIELD_CONTEXT): return fromval else: return int(tofield) - + @classmethod def _infield_to_month(cls, infield): for i, month_name in enumerate(cls._INFIELD_CONTEXT): @@ -175,7 +169,7 @@ class RuleLine(object): return i + 1 else: raise ValueError("'%s' is not an unambiguous month name abbreviation" % infield) - + @classmethod def _atfield_to_seconds_and_type(cls, atfield): last_char = atfield[-1] @@ -189,11 +183,11 @@ class RuleLine(object): atfield = atfield[:-1] else: time_type = 'w' - + if not _is_amount_of_time(atfield): raise ValueError("'%s' is not a valid 'AT' field value" % atfield) return _amount_of_time_to_seconds(atfield), time_type - + @classmethod def _savefield_to_seconds(cls, savefield): if savefield == '-': @@ -201,20 +195,20 @@ class RuleLine(object): if not _is_amount_of_time(savefield): raise ValueError("'%s' is not a valid 'SAVE' field value" % savefield) return _amount_of_time_to_seconds(savefield) - + @classmethod def _fixed_day_to_str(cls, day): return 'D%s' % day - + @classmethod def _variable_day_to_str(cls, week, weekday): return 'W%s.%s' % (week, weekday) - + @classmethod def _onfield_to_day(cls, onfield): if onfield.isdigit(): return cls._fixed_day_to_str(onfield) - + onfield = onfield.lower() if onfield.isalpha(): if not onfield.startswith('last'): @@ -223,8 +217,8 @@ class RuleLine(object): if weekday_idx is None: raise ValueError("'%s' is not a valid 'ON' field value (ambiguous)" % onfield) return cls._variable_day_to_str(5, weekday_idx + 1) - - mobj = re.match(r'^([a-z]+)([<>]=?)(\d{1,2})$', onfield, re.I) + + mobj = re.match(r'^([a-z]+)([<>]=?)(\d{1,2})$', onfield, re.I) if mobj is None: raise ValueError("'%s' is not a valid 'ON' field value" % onfield) weekday, op, num = mobj.groups() @@ -247,34 +241,34 @@ class RuleLine(object): # of DST rule logger.info("'%s' is not a well supported 'ON' field value (use of <)" % onfield) return cls._variable_day_to_str(5, weekday_idx + 1) - + def will_occur_on_year(self, tyear=None): if tyear is None: tyear = _utcnow().year return self.from_ <= tyear <= self.to - + def is_dst_start(self): return self.save != 0 - + def is_dst_end(self): return not self.is_dst_start() - + def as_rule(self): return {'month': self.in_, 'day': self.on, 'time': self.at} class RuleSet(object): """Represent a set of rules with an identical name.""" - + def __init__(self, name): self.name = name self._rules = [] - + def add_rule(self, rule): if rule.name != self.name: raise ValueError("Rule name ('%s') is different from rule set name ('%s')" % (rule.name, self.name)) self._rules.append(rule) - + def extract_dst_rules(self, utcoffset=0): """Return a 'wall-clock time' DST rules dictionary from this rule set. @@ -291,7 +285,7 @@ class RuleSet(object): dst_end_rules.append(rule) else: logger.info('We found a rule which is neither a start nor end DST rule') - + if not dst_start_rules or not dst_end_rules: logger.debug("The '%s' rule set doesn't have currently applicable DST rules" % self.name) return None @@ -312,7 +306,7 @@ class ZoneLine(object): - rules : the name of the rule that currently apply in the zone, or None if the standard time always applies """ - + def __init__(self, name, gmtoff, rules_save): self.name = name self.gmtoff = self._gmtofffield_to_seconds(gmtoff) @@ -323,13 +317,13 @@ class ZoneLine(object): self.gmtoff += _amount_of_time_to_seconds(rules_save) else: self.rules = rules_save - + @classmethod def _gmtofffield_to_seconds(cls, gmtofffield): if not _is_amount_of_time(gmtofffield, accept_neg=True): raise ValueError("'%s' is not a valid 'GMTOFF' field value" % gmtofffield) return _amount_of_time_to_seconds(gmtofffield) - + class LinkLine(object): """Represent a link line from a tz source file. @@ -338,11 +332,11 @@ class LinkLine(object): - link_from : the name of the existing timezone - link_to : the name of the new (alias) timezone """ - + def __init__(self, link_from, link_to): self.link_from = link_from self.link_to = link_to - + def _is_blank_line(line): """Returns True is the line is considered as a blank lines, else false. @@ -382,14 +376,14 @@ def _parse_tz_source_file(lines): rulesets = {} zones = [] links = [] - + it = _strip_iter(lines) try: while True: cur_line = next(it) if _is_blank_line(cur_line): continue - + tokens = cur_line.split() if tokens[0] == 'Rule': logger.debug('Adding rule \'%s\' to rulesets', cur_line) @@ -427,12 +421,14 @@ def _create_model_from_info(rulesets, zones, links): else: ruleset = rulesets[zone.rules] try: - res[zone.name] = {'name': zone.name, 'utcoffset': zone.gmtoff, 'dst': ruleset.extract_dst_rules(zone.gmtoff)} + res[zone.name] = {'name': zone.name, 'utcoffset': zone.gmtoff, + 'dst': ruleset.extract_dst_rules(zone.gmtoff)} except ValueError: logger.exception('Probably an invalid zone - ignoring') for link in links: if link.link_from not in res: - logger.warning("Can't create link from '%s' to '%s' - original zone doesn't exit", link.link_from, link.link_to) + logger.warning("Can't create link from '%s' to '%s' - original zone doesn't exit", link.link_from, + link.link_to) else: res[link.link_to] = res[link.link_from] return res @@ -480,7 +476,7 @@ if __name__ == '__main__': import tarfile import tempfile import time - + STD_SOURCE_FILES = [ "africa", "antarctica", @@ -493,14 +489,16 @@ if __name__ == '__main__': "pacificnew", "southamerica", ] - + p = optparse.OptionParser(usage='%prog [options] FILE...') p.add_option('-o', action='store', dest='outfile', metavar='OFILE', help='write the result to OFILE') - p.add_option('-s', action='store_true', dest='std', default=False, help='use the standard tz source files name (africa, asia, ...) as FILEs') - p.add_option('-t', action='store', dest='tarfile', metavar='TFILE', help='look for FILEs into the [gz|bz2] tarfile TFILE') + p.add_option('-s', action='store_true', dest='std', default=False, + help='use the standard tz source files name (africa, asia, ...) as FILEs') + p.add_option('-t', action='store', dest='tarfile', metavar='TFILE', + help='look for FILEs into the [gz|bz2] tarfile TFILE') p.add_option('-v', action='count', dest='verbose', help='Verbose mode.') opt, args = p.parse_args() - + if opt.verbose == 1: logger.setLevel(logging.INFO) elif opt.verbose > 1: @@ -508,7 +506,7 @@ if __name__ == '__main__': if opt.std: args.extend(STD_SOURCE_FILES) - + if opt.tarfile is not None: if not tarfile.is_tarfile(opt.tarfile): logger.error('error: file "%s" is not a valid tarfile' % opt.tarfile) @@ -518,7 +516,7 @@ if __name__ == '__main__': tfile.extractall(tempdir) tfile.close() args = [os.path.join(tempdir, file) for file in args] - + if not args: logger.error('error: tool takes at least one argument') sys.exit(1) @@ -526,15 +524,16 @@ if __name__ == '__main__': if not os.path.isfile(file): logger.error('error: "%s" is not a file' % file) sys.exit(1) - + if opt.outfile is None: out = sys.stdout else: out = open(opt.outfile, 'w') - + try: model = create_model_from_files(args) - out.write('# This file was automatically generated on %s by the tzdataexport tool\n' % time.strftime('%Y-%m-%d')) + out.write( + '# This file was automatically generated on %s by the tzdataexport tool\n' % time.strftime('%Y-%m-%d')) export_model_to_text_file(out, model) finally: if out is not sys.stdout: -- GitLab From 7fdde7c0c87a4285d26c7873063778a44ab8c5ec Mon Sep 17 00:00:00 2001 From: Vaclav Vorisek Date: Mon, 7 Mar 2022 15:28:21 +0100 Subject: [PATCH 2/3] 4901 code cleand and reformat --- bin/simultcalls.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/simultcalls.py b/bin/simultcalls.py index 9c96cf6..2eee828 100755 --- a/bin/simultcalls.py +++ b/bin/simultcalls.py @@ -26,7 +26,6 @@ import getopt import os import sys import time -import urllib.error import urllib.request import cjson -- GitLab From b4d2a7a1b94e8451ceede21ad0e77402e875e742 Mon Sep 17 00:00:00 2001 From: Vaclav Vorisek Date: Fri, 11 Mar 2022 10:53:15 +0100 Subject: [PATCH 3/3] version bump --- debian/changelog | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/debian/changelog b/debian/changelog index c2a17eb..56e65d3 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +xivo-utils (2022.04.00) xivo-izar; urgency=medium + + * version bump + + -- Vaclav Vorisek Fri, 11 Mar 2022 10:52:44 +0100 + xivo-utils (2022.03.00) xivo-izar; urgency=medium * Python 3 compatibility -- GitLab