141 lines
6.0 KiB
Python
141 lines
6.0 KiB
Python
import os
|
||
import datetime
|
||
import time
|
||
from natsort import natsorted
|
||
|
||
|
||
def assign_task(session, headers, task, address):
|
||
# print('assign_task')
|
||
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
|
||
task_assign = session.put(url, headers=headers)
|
||
if task_assign.status_code == 200:
|
||
print(f'Получили задание по адресу: {address}')
|
||
complete_task(session, headers, task, address)
|
||
else:
|
||
print(f"Не смогли получить задание {address} {task['id']}!")
|
||
|
||
|
||
def complete_task(session, headers, task, address):
|
||
photos = get_photo(address, headers['uid'])
|
||
if len(photos) > 0:
|
||
# photos.sort()
|
||
photos = natsorted(photos)
|
||
"""В папке лежит фото графика, которое отправляется из модуля des, поэтому убираем отсюда"""
|
||
# if len(photos) == 11 or len(photos) == 14:
|
||
if len(photos) == 3 or len(photos) == 4:
|
||
photos.pop()
|
||
id_task = task['id']
|
||
quest = get_questions(id_task, session, headers)
|
||
length_question = get_length_questions(quest)
|
||
prepared_answers = []
|
||
if len(photos) == length_question:
|
||
prepared_answers = prepare_answer(quest, photos, session, task, headers)
|
||
ans = {"question_chains": prepared_answers}
|
||
# print(ans)
|
||
session_t = session
|
||
session_t.headers.update(
|
||
{
|
||
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
|
||
'x-platform': 'android',
|
||
'accept': '*/*'
|
||
}
|
||
)
|
||
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
|
||
if complete.status_code == 200:
|
||
print(f'Задание по адресу {address} выполнено успешно!\n\n')
|
||
else:
|
||
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}\n\n')
|
||
else:
|
||
print(f"\n\n\nНесоответствие количества вопросов и фотографий по адресу {address}!!! \
|
||
Необходимо проверить!!!\n\n\n")
|
||
# print(len(quest)) 9 and 13
|
||
|
||
|
||
def get_length_questions(quest):
|
||
count = 0
|
||
for main_chain in quest:
|
||
for second_chain in main_chain['questions']:
|
||
for third_chain in second_chain['question_components']:
|
||
question_type = third_chain['type']
|
||
if question_type == "gallery":
|
||
count = count + 1
|
||
return count
|
||
|
||
|
||
def prepare_answer(quest, photos, session, task, headers):
|
||
questions = []
|
||
question_components= []
|
||
question_chains = []
|
||
for main_chain in quest:
|
||
for second_chain in main_chain['questions']:
|
||
for third_chain in second_chain['question_components']:
|
||
question_type = third_chain['type']
|
||
if question_type == 'list':
|
||
data = {"id": third_chain['id'], "answer": 77, "answer_status": None, "start_time": int(time.time())}
|
||
time.sleep(2)
|
||
data.update({"end_time": int(time.time())})
|
||
question_components.append(data)
|
||
elif question_type == "geo":
|
||
data = {"id": third_chain['id'], "answer": {"location": task['coord']}, "answer_status": None, \
|
||
"start_time": int(time.time())}
|
||
time.sleep(2)
|
||
data.update({"end_time": int(time.time())})
|
||
question_components.append(data)
|
||
elif question_type == "gallery":
|
||
img = send_image(session, headers, task['id'], photos.pop(0))#photos.pop(0))
|
||
data = {"id": third_chain['id'], "answer": [img['id']], "answer_status": None, \
|
||
"start_time": int(time.time())}
|
||
time.sleep(2)
|
||
data.update({"end_time": int(time.time())})
|
||
question_components.append(data)
|
||
if len(question_components) > 0:
|
||
main_data = {
|
||
"id": second_chain['id'],
|
||
"question_components": question_components
|
||
}
|
||
questions.append(main_data)
|
||
question_components = []
|
||
if len(questions) > 0:
|
||
q_dict = {
|
||
"id": main_chain['id'],
|
||
"questions" : questions
|
||
}
|
||
question_chains.append(q_dict)
|
||
questions = []
|
||
return question_chains
|
||
|
||
|
||
def get_photo(address, email):
|
||
photos = []
|
||
month = datetime.datetime.now().month
|
||
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)
|
||
return photos
|
||
|
||
|
||
def get_questions(id_task, session, headers):
|
||
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']
|
||
|
||
|
||
def send_image(session, headers, url, photo):
|
||
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
|
||
files = {
|
||
'image': (photo[-5:], open(photo, 'rb')),
|
||
}
|
||
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}! Повторная попытка!")
|
||
second_img = send_image(session, headers, url, photo)
|
||
return second_img
|