From 9518a916a6c47764117b688ab509b3cab08a6f9b Mon Sep 17 00:00:00 2001 From: filimonov Date: Tue, 23 Jan 2024 20:51:42 +0700 Subject: [PATCH] repair functions --- .gitignore | 3 +- backup.sh | 0 web/app.py | 27 +++-- web/static/main.css | 25 +---- .../{_WebCall.html => TestCall.html} | 19 +--- web/templates/WebCall.html | 10 +- worker-dev/__pycache__/config.cpython-39.pyc | Bin 0 -> 336 bytes worker-dev/__pycache__/msg.cpython-39.pyc | Bin 0 -> 2569 bytes worker-dev/app.py | 44 ++++++++ worker-dev/config.py | 16 +++ worker-dev/dockerfile | 14 +++ worker-dev/getmsg.py | 94 ++++++++++++++++++ worker-dev/msg.py | 68 +++++++++++++ worker-dev/requirements.txt | 8 ++ worker/app.py | 15 ++- 15 files changed, 282 insertions(+), 61 deletions(-) create mode 100644 backup.sh rename web/templates/{_WebCall.html => TestCall.html} (65%) create mode 100644 worker-dev/__pycache__/config.cpython-39.pyc create mode 100644 worker-dev/__pycache__/msg.cpython-39.pyc create mode 100644 worker-dev/app.py create mode 100644 worker-dev/config.py create mode 100644 worker-dev/dockerfile create mode 100644 worker-dev/getmsg.py create mode 100644 worker-dev/msg.py create mode 100644 worker-dev/requirements.txt diff --git a/.gitignore b/.gitignore index 2aac831..3ce1720 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ **/.venv -**/.vscode \ No newline at end of file +**/venv +**/.vscode diff --git a/backup.sh b/backup.sh new file mode 100644 index 0000000..e69de29 diff --git a/web/app.py b/web/app.py index 53812bb..a63f06c 100644 --- a/web/app.py +++ b/web/app.py @@ -16,7 +16,7 @@ app = Flask(__name__) internal = {} external = {} State = "" -findLimit = 1000 + @app.route("/") def root(): @@ -32,20 +32,27 @@ def WebCall(): call = coll_call.find().limit(findLimit).sort('time', -1) return render_template("WebCall.html", call=call) + +@app.route("/web/call/test/") +def GetTest(): + call = coll_call.find({'client': {'$nin': IgnoreList}}).sort('time', -1) + return render_template("TestCall.html", call=call) + + +@app.route("/web/call/test/") +def GetTestId(id): + call = coll_call.find( + {'client': {'$nin': IgnoreList}, 'status': int(id)}).sort('time', -1) + return render_template("TestCall.html", call=call) + + @app.route("/web/call/status/") def WebCallStatus(id): + call = coll_call.find({"status": int(id)}).sort('time', -1) call = coll_call.find( - {'client': {'$nin': IgnoreList}, 'status': int(id)}).limit(findLimit).sort('time', -1) + {'client': {'$nin': IgnoreList}, 'status': int(id)}).sort('time', -1) return render_template("WebCall.html", call=call) -@app.route("/web/call/find/", methods=["GET"]) -def WebCallFind(): - try: - id = str(request.args.get("client")) - call = coll_call.find({"client": {"$regex": str(id)}}).limit(findLimit).sort('time', -1) - return(render_template("WebCall.html", call=call)) - except Exception as e: - return(str(e)) if __name__ == "__main__": app.debug = True diff --git a/web/static/main.css b/web/static/main.css index 36ffc38..2e8a484 100644 --- a/web/static/main.css +++ b/web/static/main.css @@ -42,29 +42,6 @@ a { } header { - height: 80px; + height: 50px; vertical-align: middle; -} - -.search { - height: 30px; -} - -.search_label { - color: chocolate; - font-family: Verdana, Geneva, Tahoma, sans-serif; - font-weight: bold; -} - -.search_text { - color: chocolate; - font-family: Verdana, Geneva, Tahoma, sans-serif; - font-weight: bold; - width: 200px; -} - -.search_btn { - color: chocolate; - font-family: Verdana, Geneva, Tahoma, sans-serif; - font-weight: bold; } \ No newline at end of file diff --git a/web/templates/_WebCall.html b/web/templates/TestCall.html similarity index 65% rename from web/templates/_WebCall.html rename to web/templates/TestCall.html index 9210f5d..021dbf5 100644 --- a/web/templates/_WebCall.html +++ b/web/templates/TestCall.html @@ -12,34 +12,21 @@ Входящий вызов принят Входящий вызов не принят Перезвонили + - -
- - - -
- - - - + - {% for entry in call %} - {% if entry.important == True %} - - {% else %} - - {% endif %} +
Номер клиента Дата время событияДата время Ссылка на запись
{{ "%s %s %s %s"|format(entry.client[0:1], entry.client[1:4], entry.client[4:7], entry.client[7:11]) }}{{ "%s %s %s %s"|format(entry.client[0:1], entry.client[1:4], entry.client[4:7], entry.client[7:11]) }}{{ "%s %s %s %s"|format(entry.client[0:1], entry.client[1:4], entry.client[4:7], entry.client[7:11]) }} {{ entry.time }} diff --git a/web/templates/WebCall.html b/web/templates/WebCall.html index 44256a4..493117a 100644 --- a/web/templates/WebCall.html +++ b/web/templates/WebCall.html @@ -11,6 +11,7 @@
Входящий вызов принят Входящий вызов не принят +<<<<<<< HEAD Перезвонили успешно Перезвонили безуспешно

@@ -20,12 +21,16 @@

+======= + Перезвонили + +>>>>>>> parent of c52dc73 (Добавил поиск)
+ - @@ -45,6 +50,7 @@
Номер клиента Дата времяСтатус звонка Ссылка на запись
{{ entry.time }} +<<<<<<< HEAD {% if entry.status == 0 %} Вызов принят {% elif entry.status == 1 %} @@ -58,6 +64,8 @@ {% endif %} +======= +>>>>>>> parent of c52dc73 (Добавил поиск) {% if entry.recordUrl|length > 1 %} {% endif %} diff --git a/worker-dev/__pycache__/config.cpython-39.pyc b/worker-dev/__pycache__/config.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..842d1e64fa417d105fd8901e7ddeac0ea905716a GIT binary patch literal 336 zcmYk1&q~8U5XN_-h*;8tuiz<%n*E#XfQTN71T>X4r(8tbHA-zaY^%ka&*H7Gl&eSI zz>^!BVh84f-+aTz%zYRhAz$AgeY3_0eYLP#frks?$9PhaM)y8o7Oc+n@ZL v#I|0>v*~hBKiRp7SJq998))+uKiK)>b9Gw3H-~34t6yKtdHd6%m4o0H9>hp` literal 0 HcmV?d00001 diff --git a/worker-dev/__pycache__/msg.cpython-39.pyc b/worker-dev/__pycache__/msg.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cff7dd47d5ca9a1a7cc2cd0666ecf0b2bd39277 GIT binary patch literal 2569 zcmb7GUvC>l5Z~RqvoHReq%>{Pf=Y#fD{@ka7l;sQ)U*(Z8WcN1^~=e4HsO-~n|<>e1_F#T2F6>_w}5w&WWy3lWoak63RF>A%A^|9QL1E8 z1DYsRWi2_m3@a$rGu4XK0g4UT@ zllZXx#TEbLia&Hp+WaYmH@XCJ7=qO1aTEsH^1}f{x~$~b9}IC9ykYDJZAQ{RR2Jg6 zWU7YK)q|~Y9B++I;`aFGFpyiXLvf$~2q^#j0#|Pp>s8uk!3`|63 zbrc!VwigV;kry2Go~vctP%AW03=7yQUbL4TyN#MCVF8~u2-CG{F%EM3l%2B+R>P=V z@{Yq5U9`y9vtMJWf`NZ`-dL`hGxm;Yv7&f@Mi#nkW30P$5-)(p+~Ns!!Zl~ z{h8Bhl`4Qp(xr4@${P zG^Eyba)DMD(9t+yxVEEM9n#*7u9VT09x6W~NAk#S5Xq~VJEWa+hH5WiwTTM?s)*hx zOK&1AMT{~yi5`)mjI(*fQq7!^S@u%Orlp+~GL~_u;6V9{SwlsbUANX9GfbL>$XbGD`ThG=~spW-$&A6g8!p;?F7+lsU&S(Lm+u83aYAe0x zj-}Rdab5emGz^17??^ZHUi|R=es8DKbHCf`JiD=ws@Qu+<50zeASQUTh;Nc-N$LwH zI?gTn=mmq3bX{F>-BAb=pVl?k{be%nQ;lj6pj8~`6CC;}wmT#nSk@_C>TQY|kv6;_ zRu4&}+^LUg_>=~R1}cHV$0Yfz(AQ2;oe@8x4O(!!WS1HS{%A~BG?$Ze_|Jd{BUPsN fh^1O6sXil#Zn^1tZGV+I_cb+*B;{x${TcrPk~{0P literal 0 HcmV?d00001 diff --git a/worker-dev/app.py b/worker-dev/app.py new file mode 100644 index 0000000..fb6006b --- /dev/null +++ b/worker-dev/app.py @@ -0,0 +1,44 @@ +import pika +import sys +import os +import json +import datetime +import re +import config +from pymongo import MongoClient +from msg import msg +import requests +import time + +def main(): + connection = pika.BlockingConnection(pika.ConnectionParameters( + "192.168.0.20", 5672, "mkt", pika.PlainCredentials( + "rabbit", "mrl2X0jwnYuCCiKFTshG7WKyOAhfDo") + )) + channel = connection.channel() + + def callback(ch, method, properties, body: bytearray): + srcJson = json.loads(str(body.decode('utf-8')).replace("\'", "\"")) +# if srcJson['state'] == 'HANGUP' and srcJson['direction'] == 'incoming' and srcJson['from'] == '89135853246': + try: + if srcJson['callstatus'] != 'ANSWER': + print(srcJson) + except: + pass + + channel.basic_consume( + queue='copy_incoming', on_message_callback=callback, auto_ack=False) + + print(' [*] Waiting for messages. To exit press CTRL+C') + channel.start_consuming() + + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + print('Interrupted') + try: + sys.exit(0) + except SystemExit: + os._exit(0) diff --git a/worker-dev/config.py b/worker-dev/config.py new file mode 100644 index 0000000..7a257dd --- /dev/null +++ b/worker-dev/config.py @@ -0,0 +1,16 @@ + +IMPORTANT_LINE = ['83912051045'] + +IGNORE_LIST = ['83912051045', + '83912051046', + '83919865589', + '83919865589', + '84950213944', + '84951183750', + '84951252791', + '89919237009', + '89919241441', + '89919398228', + '89919500798', + '89919505445', + '89919863883'] diff --git a/worker-dev/dockerfile b/worker-dev/dockerfile new file mode 100644 index 0000000..063c2bf --- /dev/null +++ b/worker-dev/dockerfile @@ -0,0 +1,14 @@ +FROM alpine + +RUN apk update && apk upgrade && apk add python3 && apk add -U tzdata + +WORKDIR /app + +COPY requirements.txt requirements.txt +ADD *.py /app +RUN python3 -m venv .venv +RUN /app/.venv/bin/pip3 install -r /app/requirements.txt + +EXPOSE 5000 + +CMD [".venv/bin/python3", "app.py"] \ No newline at end of file diff --git a/worker-dev/getmsg.py b/worker-dev/getmsg.py new file mode 100644 index 0000000..f782416 --- /dev/null +++ b/worker-dev/getmsg.py @@ -0,0 +1,94 @@ +import pika +import sys +import os +import json +import datetime +import re +import config +from pymongo import MongoClient +from msg import msg +import requests +import time + +CONNECTION_STRING = "mongodb://mongodb:Cc03Wz5XX3iI3uY3@192.168.0.20" +db_connection = MongoClient(CONNECTION_STRING) + +db_base = db_connection["phone"] +coll_call = db_base["phone_dev"] +from_api = db_base["from_api"] + + +def main(): + connection = pika.BlockingConnection(pika.ConnectionParameters( + "192.168.0.20", 5672, "mkt", pika.PlainCredentials( + "rabbit", "mrl2X0jwnYuCCiKFTshG7WKyOAhfDo") + )) + channel = connection.channel() + + def callback(ch, method, properties, body: bytearray): + m = msg(body) + + # Разбираем входящие звонки + if m.isIncoming(): + # Если статус START + if m.getState() == "START": + insert_value = { + "uuid": m.getUUID(), + "status": -1, + "canClose": 0 + } + + coll_call.update_one( + filter={"client": m.getClient(), "status": -1}, + update={"$set": insert_value}, + upsert=True + ) + #print("НАЧАТ:", m.dict) + + # Если Статус END + if m.getState() == "END": + coll_call.update_one( + filter={"uuid": m.getUUID()}, + update={"$set": {"canClose": 1}} + ) + #print("ЗАКОНЧЕН:", m.dict) + time.sleep(5) + resp = requests.get("https://callinfo.services.mobilon.ru/api/call/info/1e86a98e026578eb5f6bf8c092c0c4a2/" + m.getUUID()) + j = json.loads(resp.content.decode('utf-8')) + d = dict(j) + from_api.insert_one(d) + + # Если статус HANGUP + if m.getState() == "HANGUP": + if m.isAnswered(): + insert_value = { + "status": 0, + "duration": m.getDuration(), + "recordUrl": m.getRecordUrl() + } + else: + insert_value = { + "status": 1 + } + coll_call.update_one( + filter={"uuid": m.getUUID(), "canClose": 1}, + update={"$set": insert_value} + ) + #print("Положена трубка:", m.dict) + + channel.basic_consume( + queue='test', on_message_callback=callback, auto_ack=True) + + print(' [*] Waiting for messages. To exit press CTRL+C') + channel.start_consuming() + + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + print('Interrupted') + try: + sys.exit(0) + except SystemExit: + os._exit(0) diff --git a/worker-dev/msg.py b/worker-dev/msg.py new file mode 100644 index 0000000..71b1b4a --- /dev/null +++ b/worker-dev/msg.py @@ -0,0 +1,68 @@ +import os +import json +import datetime +import re +import config + + +class msg: + def __init__(self, body): + self.body: bytearray = body + self.decode: str = self.body.decode('utf-8') + self.json: json = json.loads(self.decode.replace("\'", "\"")) + self.dict: dict = dict(self.json) + + def getDirection(self): + try: + return self.dict["direction"] + except: + pass + + def isIncoming(self) -> bool: + return True if self.dict["direction"] == "incoming" else False + + def isExternal(self) -> bool: + return not self.isIncoming() + + def getState(self) -> str: + try: + return self.dict["state"] + except: + pass + + def getClient(self) -> str: + return self.dict["from"] if self.isIncoming() else self.dict["to"] + + def getTime(self) -> str: + try: + return datetime.datetime.fromtimestamp(self.dict["time"]).strftime('%Y-%m-%d %H:%M:%S') + except: + return None + + def getStatus(self) -> int: + pass + + def getRecordUrl(self) -> str: + return self.dict["recordUrl"] + + def getDuration(self) -> int: + return self.dict["duration"] + + def getUUID(self) -> str: + try: + return self.dict["uuid"] + except: + pass + + def isAnswered(self) -> bool: + try: + self.dict["callstatus"] + return True + except: + return False + + def isImportant(self): + try: + return True if self.getState() == "START" and self.isIncoming() and self.dict["to"] in config.IMPORTANT_LINE else False + except: + pass diff --git a/worker-dev/requirements.txt b/worker-dev/requirements.txt new file mode 100644 index 0000000..e575685 --- /dev/null +++ b/worker-dev/requirements.txt @@ -0,0 +1,8 @@ +dnspython==2.3.0 +pika==1.3.1 +pymongo==4.3.3 +certifi==2022.12.7 +charset-normalizer==3.1.0 +idna==3.4 +requests==2.28.2 +urllib3==1.26.15 \ No newline at end of file diff --git a/worker/app.py b/worker/app.py index 40cfe6c..baf62dc 100644 --- a/worker/app.py +++ b/worker/app.py @@ -84,20 +84,17 @@ def main(): print(e) if srcJson['direction'] == 'external': - print("EXTERNAL", srcJson) +# coll_phone.update_one({'$and': [{'client': {'$regex': srcJson['to']}}, {'status': 1}}]}, {'$set': {'status': 2, 'callid': srcJson['uuid']}}) + coll_phone.update_one({'$and': [{'client': {'$regex': srcJson['to']}}, {'status': 1}]}, {'$set': {'status': 2, 'callid': srcJson['uuid']}}) if srcJson['state'] == 'HANGUP': - print("Full Log", srcJson) try: # Проверяем заполнено ли поле recordURL, если нет то меняем статус на 4 if len(srcJson['recordUrl']) > 4: - print("recordURL len > 4") - r = coll_phone.update_one({'callid':srcJson['uuid']}, {'$set': {'recordUrl': srcJson['recordUrl'], 'status': 2}}) - print(r) + print(srcJson['uuid'], srcJson['recordUrl']) + coll_phone.update_one({'callid':srcJson['uuid']}, {'$set': {'recordUrl': srcJson['recordUrl'], 'status': 2}}) else: - coll_prone - print("recordURL len < 4") - r = coll_phone.update_one({'callid':srcJson['uuid']}, {'$set': {'status': 4}}) - print(r) + print(srcJson['uuid']) + coll_phone.update_one({'callid':srcJson['uuid']}, {'$set': {'status': 4}}) except Exception as e: print(e)