Compare commits

..

No commits in common. "90bdf92fc18be6e49c151ef57859a42293ff880d" and "ba742f7d2129976f0ada1dc8c7968874ff9c407a" have entirely different histories.

2 changed files with 56 additions and 74 deletions

125
des.py
View File

@ -8,38 +8,31 @@ import time
import requests
import classes.desinfection as des
# import classes.proverka as prov
from classes.users import Users
def get_questions(id_task, session, headers):
url = "https://knd.mosreg.ru//api/v1/executions/" + str(id_task) + "/questions"
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
questions = session.get(url, headers=headers)
json_quest = questions.json()
return json_quest["selected_chains"]
return json_quest['selected_chains']
def send_image(session, headers, url, photo):
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
files = {
"image": (photo[-5:], open(photo, "rb")),
'image': (photo[-5:], open(photo, 'rb')),
}
# print(files)
img = session.post(
"https://knd.mosreg.ru//api/v1/executions/" + str(url) + "/images",
headers=headers,
files=files,
)
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url) +
'/images', headers=headers, files=files)
if img.status_code == 200:
print(f"Фото {photo} успешно отправлено")
return img.json()
else:
print(
f"Не удалось загрузить фото на сервер по заданию {url}, \
статус ошибки {img.status_code}! Повторная попытка!"
)
print(f"Не удалось загрузить фото на сервер по заданию {url}, \
статус ошибки {img.status_code}! Повторная попытка!")
second_img = send_image(session, headers, url, photo)
return second_img
@ -47,24 +40,23 @@ def send_image(session, headers, url, photo):
def get_photo(address, email):
photos = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath("."), "data", email, str(month), address)
main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month),
address)
if not os.path.exists(main_path):
return photos
else:
for images in os.listdir(main_path):
if (
images.endswith(".jpg")
or images.endswith(".jpeg")
or images.endswith(".JPG")
):
photos.append(main_path + "/" + images)
if (images.endswith(".jpg") or
images.endswith(".jpeg") or
images.endswith(".JPG")):
photos.append(main_path + '/' + images)
return photos
def get_addresses(email):
addresses = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath("."), "data")
main_path = os.path.join(os.path.abspath('.'), 'data')
path = os.walk(os.path.join(main_path, email, str(month)))
if not os.path.exists(os.path.join(main_path, email, str(month))):
return f"Не найдена папка с месяцем у пользователя {email}! Проверьте \
@ -88,19 +80,18 @@ def get_task(session, headers):
2 адрес
3 подъезд
4 id_задания"""
desinfection = "Дезинфекция подъездов (МОП)"
proverka = "Систематическая проверка подъездов МКД"
desinfection = 'Дезинфекция подъездов (МОП)'
proverka = 'Систематическая проверка подъездов МКД'
# Получаем адреса
addresses = get_addresses(headers["uid"])
addresses = get_addresses(headers['uid'])
# Если адреса получили
if isinstance(addresses, list):
session_t = session
session_t.headers.update(
{
"referer": "https://knd.mosreg.ru/executions",
"x-platform": "android",
"accept": "*/*",
}
{'referer': 'https://knd.mosreg.ru/executions',
'x-platform': 'android',
'accept': '*/*'
}
)
for address in addresses:
# change '-' for '/'
@ -109,56 +100,46 @@ def get_task(session, headers):
addr = address.replace("Маиданово", "Майданово")
search = addr.replace("_", "/")[:-4]
# print(search)
data = {"search": search}
tasks = session_t.post(
"https://knd.mosreg.ru//api/v1/actor/executions",
headers=headers,
data=data,
)
data = {'search': search}
tasks = session_t.post('https://knd.mosreg.ru//api/v1/actor/executions',
headers=headers,
data=data
)
json_tasks = tasks.json()
# get_t = False
# Если есть доступное задание с таким адресом
#
# Уже полученные задания
exec_assigned = json_tasks["executions_assigned"]
exec_assigned = json_tasks['executions_assigned']
print(exec_assigned)
# Еще не принятые задания
exec_available = json_tasks["executions_available"]
exec_available = json_tasks['executions_available']
print(exec_available)
# print(address)
if len(exec_available) > 0:
for n in exec_available:
coord = n["coord"]
enterances = n["tasks"]
coord = n['coord']
enterances = n['tasks']
for execution in enterances:
address_from_tasks = execution["dimensions"][0].get(
"entity_value_name"
)
name_from_tasks = execution["name"]
address_from_tasks = execution['dimensions'][0].get(
'entity_value_name')
name_from_tasks = execution['name']
if name_from_tasks == desinfection:
enterance = execution["dimensions"][2].get(
"entity_value_name"
)
if (
address_from_tasks
== "Клин г, " + addr.replace("_", "/")[:-4]
and enterance[-1] == address[-2]
):
print("\n")
enterance = execution['dimensions'][2].get(
'entity_value_name')
if address_from_tasks == 'Клин г, ' + addr.replace("_", "/")[:-4] and enterance[-1] == address[-2]:
print('\n')
print(name_from_tasks)
print("\n")
print('\n')
task = {
"id": execution["execution_id"],
"address": execution["dimensions"][0].get(
"entity_value_name"
),
"enterance": execution["dimensions"][2].get(
"entity_value_name"
),
"coord": coord,
'id': execution['execution_id'],
'address': execution['dimensions'][0].get('entity_value_name'),
'enterance': execution['dimensions'][2].get('entity_value_name'),
'coord': coord
}
if name_from_tasks == desinfection:
des.assign_task(session, headers, task, address)
des.assign_task(
session, headers, task, address)
elif name_from_tasks == proverka:
pass
# prov.assign_task(session, headers, task, address)
@ -166,8 +147,7 @@ def get_task(session, headers):
pass
else:
print(
f"Нет доступных заданий для пользователя {headers['uid']} по адресу: {address}"
)
f"Нет доступных заданий для пользователя {headers['uid']} по адресу: {address}")
# Если адреса не получили выводим ошибку
else:
print(addresses)
@ -177,15 +157,18 @@ def main():
users = Users()
logins = users.get_passwords()
if isinstance(logins, list):
url = "https://knd.mosreg.ru//api/v1/auth/sign_in"
url = 'https://knd.mosreg.ru//api/v1/auth/sign_in'
for user in logins:
session = requests.Session()
login = {"email": user["email"], "password": user["password"]}
login = {
'email': user['email'],
'password': user['password']
}
response = session.post(url, data=login)
headers = {
"client": response.headers.get("client"),
"Access-token": response.headers.get("Access-token"),
"uid": response.headers.get("uid"),
'client': response.headers.get('client'),
'Access-token': response.headers.get('Access-token'),
'uid': response.headers.get('uid'),
}
if response.status_code == 200:
get_task(session, headers)
@ -204,4 +187,4 @@ if __name__ == "__main__":
def random_string(stringLength):
letters = string.ascii_letters
digits = string.digits
return "".join(random.choice(letters + digits) for i in range(stringLength))
return ''.join(random.choice(letters+digits) for i in range(stringLength))

View File

@ -49,12 +49,12 @@ def complete_task(session, headers, task, address):
id_task = task["id"]
questions = get_questions(id_task, session, headers)
data = []
comp = []
for answers in questions:
answer_chain = {"id": answers["id"], "questions": []} # answers['questions']
if answer_chain["id"] == 6146: # Цепочка без ответов
continue
for components in answers["questions"]:
comp = []
q_c = {"id": components["id"], "question_components": []}
if q_c["id"] == 6560: # Вопрос без ответа
continue
@ -126,8 +126,7 @@ def complete_task(session, headers, task, address):
session_t = session
session_t.headers.update(
{
"referer": "https://knd.mosreg.ru/executions"
+ str(task["id"])
"referer": "https://knd.mosreg.ru/executions" + str(task["id"])
+ "/solve",
"x-platform": "wb",
"accept": "*/*",