lenny.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. import ConfigParser
  4. import audioop
  5. import contextlib
  6. import glob
  7. import io
  8. import os
  9. import re
  10. import signal
  11. import smtplib
  12. import string
  13. import subprocess
  14. import sys
  15. import syslog
  16. import tempfile
  17. import threading
  18. import urllib2
  19. import wave
  20. from datetime import datetime
  21. import linphone
  22. import yaml
  23. from enum import Enum
  24. VOLUME_THRESHOLD = 100
  25. def slugify(s):
  26. """
  27. Normalizes string, converts to lowercase, removes non-alpha characters,
  28. and converts spaces to hyphens, wich is url/filename friendly.
  29. """
  30. valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
  31. filename = ''.join(cc for cc in s if cc in valid_chars)
  32. filename = filename.replace(' ', '_') # I don't like spaces in filenames.
  33. return filename
  34. def get_ip_from_logfile(remote_sip_client_tag, log_file):
  35. # Le log file contiendra, via la mise a jour dyndns custom du routeur, une ligne du type:
  36. # 84.227.205.102 - jf [23/Jun/2017:17:06:19 +0200] "GET /itslenny/domain=[essai]/ip=[84.227.205.102] HTTP/1.1" 404 169 "-" "Fritz!Box DDNS/1.0.1"
  37. cmd = 'cat ' + log_file + ' | grep "' + remote_sip_client_tag + '" | tail -n 1'
  38. reg = "domain=\[" + remote_sip_client_tag + "\]\/ip=\[(.*)\]"
  39. s = re.findall(reg, subprocess.check_output(["bash", "-c", cmd]))
  40. if len(s) > 0:
  41. return s[0]
  42. class ConversationStatus(Enum):
  43. READY_TO_TALK = 0
  44. IMTALKING = 1
  45. WAITFORANSWER = 2
  46. class Conversation(object):
  47. def __init__(self):
  48. self._status = ConversationStatus.READY_TO_TALK
  49. @property
  50. def status(self):
  51. return self._status
  52. @status.setter
  53. def status(self, value):
  54. if value != self._status:
  55. self._status = value
  56. current_dir = os.path.dirname(os.path.realpath(__file__))
  57. replies_seq = glob.glob(current_dir + "/replies/sequence/*.wav")
  58. replies_seq.sort()
  59. replies_generic = glob.glob(current_dir + "/replies/generic/*.wav")
  60. replies_generic.sort()
  61. THREADS_MUST_QUIT = False
  62. def get_wav_duration(fname):
  63. with contextlib.closing(wave.open(fname, 'r')) as f:
  64. frames = f.getnframes()
  65. rate = f.getframerate()
  66. return frames / float(rate)
  67. def sleep(duration):
  68. dummy_event = threading.Event()
  69. dummy_event.wait(timeout=duration)
  70. class SipConnection(object):
  71. class MailType(Enum):
  72. Notify_Incoming_Call = 1
  73. Notify_Incoming_Telemarketer_Call = 2
  74. def log(self, msg):
  75. to_show = str(self) + ": " + msg
  76. print(to_show)
  77. syslog.syslog(to_show)
  78. def mail(self, mail_cfg, text):
  79. try:
  80. server = smtplib.SMTP(mail_cfg["smtp_host"])
  81. server.sendmail(mail_cfg["from"], mail_cfg["to"], text)
  82. server.quit()
  83. except smtplib.SMTPException as e:
  84. self.log("Error sending email " + e.message)
  85. def say(self, core):
  86. if self._conversation.status is not ConversationStatus.IMTALKING:
  87. self._conversation.status = ConversationStatus.IMTALKING
  88. # On joue les repliques en sequence, puis quand
  89. # on arrive au bout, on en joue une au hasard
  90. # du groupe 'generic'
  91. voice_filename = replies_seq[self._replies_pos]
  92. self._replies_pos = (self._replies_pos + 1) % len(replies_seq)
  93. if self._replies_pos == 0:
  94. # On ne rejoue jamais la première réplique "allo"
  95. self._replies_pos = 1
  96. duration = get_wav_duration(voice_filename)
  97. self.log("Saying : " + voice_filename)
  98. core.play_file = voice_filename
  99. sleep(duration)
  100. core.play_file = ""
  101. # On laisse l'autre l'occassion de reparler
  102. self._conversation.status = ConversationStatus.WAITFORANSWER
  103. def incoming_stream_worker(self, core, call):
  104. f = open(self._incoming_stream_file, "rb")
  105. f.seek(0, io.SEEK_END)
  106. p = f.tell()
  107. buf = ''
  108. previous_status = self._conversation.status
  109. while call.state is not linphone.CallState.End and not self._is_quitting:
  110. if self._conversation.status is ConversationStatus.IMTALKING:
  111. f.seek(0, io.SEEK_END)
  112. p = f.tell()
  113. else:
  114. if previous_status != self._conversation.status:
  115. f.seek(0, io.SEEK_END)
  116. p = f.tell()
  117. f.seek(p)
  118. buf += f.read(4096)
  119. p = f.tell()
  120. if len(buf) >= 20000:
  121. volume = audioop.rms(buf, 2)
  122. # print("State : " + str(conversation.status))
  123. buf = ''
  124. if volume < self._volume_threshold:
  125. if self._conversation.status is ConversationStatus.READY_TO_TALK:
  126. threading.Thread(target=self.say, args=[core]).start()
  127. else:
  128. self._conversation.status = ConversationStatus.READY_TO_TALK
  129. # We must sleep a bit to avoid cpu hog
  130. sleep(0.01)
  131. previous_status = self._conversation.status
  132. self.log("Worker is quitting")
  133. def registration_state_changed(self, core, call, state, message):
  134. # Le client se ré-enregistre a de multiple reprise, on
  135. # s'en tappe un peu d'en être informé.
  136. if message != self._registration_previous_message:
  137. self.log("Registration status: " + message)
  138. self._registration_previous_message = message
  139. def call_state_changed(self, core, call, state, message):
  140. self.log("state changed : " + message)
  141. if state == linphone.CallState.Released:
  142. # Let's convert wav to mp3
  143. if call.current_params.record_file is not None and os.path.isfile(call.current_params.record_file):
  144. self.log("Saving to mp3 : " + call.current_params.record_file)
  145. subprocess.call('lame --quiet --preset insane %s' % call.current_params.record_file, shell=True)
  146. os.remove(call.current_params.record_file)
  147. if state == linphone.CallState.IncomingReceived:
  148. self.log("Incoming call : {}".format(call.remote_address.username))
  149. self.mail_if_needed(call.remote_address.username, self.MailType.Notify_Incoming_Call)
  150. self._replies_pos = 0
  151. if self.is_in_blacklists(call.remote_address.username):
  152. self.log("telemarketer calling : " + call.remote_address.username)
  153. self.mail_if_needed(call.remote_address.username, self.MailType.Notify_Incoming_Telemarketer_Call)
  154. call_params = core.create_call_params(call)
  155. if not os.path.isdir(current_dir + "/out"):
  156. os.makedirs(current_dir + "/out")
  157. a_file = current_dir + "/out/call_from_" + slugify(call.remote_address.username) + \
  158. "_" + datetime.now().strftime(
  159. '%Y-%m-%d_%Hh%Mmn%Ss') + ".wav"
  160. self.log("Recording to : " + a_file)
  161. call_params.record_file = a_file
  162. # Let ring some time
  163. sleep(4)
  164. core.accept_call_with_params(call, call_params)
  165. call.start_recording()
  166. sleep(2)
  167. t = threading.Thread(target=self.incoming_stream_worker, args=[core, call])
  168. t.start()
  169. self.say(core)
  170. def __enter__(self):
  171. return self
  172. def __exit__(self, exc_type, exc_value, traceback):
  173. self.log(str(self) + ": cleaning on exit ...")
  174. os.unlink(self._incoming_stream_file)
  175. def get_domain_info(self):
  176. if "domain" in self._config_info:
  177. return self._config_info["domain"]
  178. if "domain_dyn_tag" in self._config_info and "domain_dyn_log" in self._config_info:
  179. return get_ip_from_logfile(self._config_info["domain_dyn_tag"], self._config_info["domain_dyn_log"])
  180. def start(self):
  181. self.log("starting ")
  182. self._core.use_files = True
  183. self._core.record_file = self._incoming_stream_file
  184. proxy_cfg = self._core.create_proxy_config()
  185. domain = self.get_domain_info()
  186. proxy_cfg.identity_address = self._core.create_address('sip:' + self._config_info["username"] + '@' + domain + ':5060')
  187. proxy_cfg.server_addr = 'sip:' + domain + ':5060'
  188. proxy_cfg.register_enabled = True
  189. self._core.add_proxy_config(proxy_cfg)
  190. auth_info = self._core.create_auth_info(self._config_info["username"], None, self._config_info["password"],
  191. None, None, domain)
  192. self._core.add_auth_info(auth_info)
  193. while not self._is_quitting:
  194. sleep(0.03)
  195. self._core.iterate()
  196. def request_quit(self):
  197. self._is_quitting = True
  198. self.__exit__(None, None, None)
  199. def __str__(self):
  200. return self._config_info["username"] + "@" + self.get_domain_info()
  201. def __init__(self, config_info):
  202. callbacks = {
  203. 'call_state_changed': self.call_state_changed,
  204. 'registration_state_changed': self.registration_state_changed,
  205. }
  206. self._config_info = config_info
  207. self._core = linphone.Core.new(callbacks, None, None)
  208. self._is_quitting = False
  209. self._registration_previous_message = ""
  210. self._conversation = Conversation()
  211. self._replies_pos = 0
  212. self._volume_threshold = VOLUME_THRESHOLD
  213. self._incoming_stream_file = tempfile.NamedTemporaryFile(delete=False).name
  214. self._core.iterate()
  215. def mail_if_needed(self, number, type):
  216. if "mailer" in self._config_info:
  217. mail_cfg = self._config_info["mailer"]
  218. if type == self.MailType.Notify_Incoming_Call:
  219. if mail_cfg["log_all_call"]:
  220. self.mail(mail_cfg, "Appel entrant : " + number)
  221. if type == self.MailType.Notify_Incoming_Telemarketer_Call:
  222. self.mail(mail_cfg, "Appel télémarketeur entrant : " + number)
  223. def is_in_blacklists(self, a_number):
  224. return self.is_in_local_blacklist(a_number) or self.is_in_directory_ch_blacklist(
  225. a_number) or self.is_in_ktipp_blacklist(a_number) \
  226. or self.is_in_shiansw_blacklist(a_number)
  227. def is_in_local_blacklist(self, a_number):
  228. black_list = current_dir + "/blacklist.txt"
  229. if os.path.isfile(black_list):
  230. res = a_number in open(current_dir + "/blacklist.txt").read()
  231. if res:
  232. self.log(a_number + " Found in localblacklist")
  233. return res
  234. def is_in_ktipp_blacklist(self, a_number):
  235. # On peut interroger le site ktipp:
  236. # https://www.ktipp.ch/service/warnlisten/detail/?warnliste_id=7&ajax=ajax-search-form&keyword=0445510503
  237. # Si argument keyword pas trouvé, ca donne ca dans la réponse :
  238. # 0 Einträge
  239. base_url = "https://www.ktipp.ch/service/warnlisten/detail/?warnliste_id=7&ajax=ajax-search-form&keyword={" \
  240. "$number$}"
  241. the_number = a_number.lstrip("0")
  242. the_number = the_number.replace("+", "")
  243. url = base_url.replace("{$number$}", the_number)
  244. response = ""
  245. try:
  246. response = urllib2.urlopen(url).read()
  247. except urllib2.HTTPError:
  248. pass
  249. res = "0 Eintr" not in response
  250. if res:
  251. self.log(a_number + " found in ktipp blacklist")
  252. return res
  253. def is_in_shiansw_blacklist(self, a_number):
  254. base_url = "https://ch.shouldianswer.net/telefonnummer/{$number$}"
  255. url = base_url.replace("{$number$}", a_number)
  256. response = ""
  257. try:
  258. response = urllib2.urlopen(url).read()
  259. except urllib2.HTTPError:
  260. pass
  261. res = '<div class="review_score negative"></div>' in response
  262. if res:
  263. self.log("Found in ch.shouldianswer.net blacklist")
  264. return res
  265. def is_in_directory_ch_blacklist(self, a_number):
  266. base_url = "https://tel.local.ch/fr/{$number$}"
  267. url = base_url.replace("{$number$}", a_number)
  268. response = ""
  269. try:
  270. response = urllib2.urlopen(url).read()
  271. except urllib2.HTTPError:
  272. pass
  273. res = 'https://tel.local.ch/fr/spamnumber/' in response
  274. if res:
  275. self.log(a_number + " found in directories.ch blacklist")
  276. return res
  277. if __name__ == "__main__":
  278. cfg = ConfigParser.SafeConfigParser()
  279. cfg_path = current_dir + "/config.yml"
  280. if len(sys.argv) == 2:
  281. cfg_path = sys.argv[1]
  282. connections = []
  283. for connection_cfg in yaml.load(file(cfg_path)):
  284. connections.append(SipConnection(connection_cfg))
  285. for sip_c in connections:
  286. threading.Thread(target=sip_c.start).start()
  287. # Ensuring clean quit and ressource releasing
  288. # when receiving ctrl-c from console or SIGTERM
  289. # from daemon manager.
  290. def signal_handler(sig, frame):
  291. print('External stop request!')
  292. for conn in connections:
  293. conn.request_quit()
  294. signal.signal(signal.SIGINT, signal_handler)
  295. signal.signal(signal.SIGTERM, signal_handler)
  296. signal.pause()