Files
platform/migrations/scripts/extract_full.py
T
Арсентьев Александр a2ac226028 ервый импорт проекта
2026-08-06 00:01:51 +03:00

363 lines
13 KiB
Python

"""Full extraction from ManageEngine API with conversations and attachments."""
import requests
import json
import os
import sys
import time
from typing import Dict, List, Optional
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
API_KEY = 'B3526FC8-82CB-4798-92C8-22AF05F9A49F'
BASE_URL = 'https://support.atl-group.ru/api/v3'
ATTACHMENTS_DIR = os.path.join(os.path.dirname(__file__), 'attachments')
import urllib3
urllib3.disable_warnings()
def get_requests_page(start_index: int, row_count: int = 100) -> Dict:
"""Get a page of requests."""
url = BASE_URL + '/requests'
params = {
'TECHNICIAN_KEY': API_KEY,
'input_data': json.dumps({
'list_info': {
'row_count': row_count,
'start_index': start_index,
'sort_field': 'id',
'sort_order': 'asc'
}
})
}
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
return resp.json()
def get_all_requests() -> List[Dict]:
"""Get all requests."""
all_requests = []
start_index = 1
while True:
data = get_requests_page(start_index, 100)
batch = data.get('requests', [])
has_more = data.get('list_info', {}).get('has_more_rows', False)
if not batch:
break
all_requests.extend(batch)
print(f" Fetched {len(all_requests)} requests...")
if not has_more or len(batch) < 100:
break
start_index += 100
time.sleep(0.3)
return all_requests
def get_request_detail(request_id: int) -> Optional[Dict]:
"""Get full request details."""
url = f'{BASE_URL}/requests/{request_id}'
params = {'TECHNICIAN_KEY': API_KEY}
try:
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
data = resp.json()
return data.get('request')
except Exception as e:
print(f" Error fetching request {request_id}: {e}")
return None
def get_conversations(request_id: int) -> List[Dict]:
"""Get conversations for a request."""
url = f'{BASE_URL}/requests/{request_id}/conversations'
params = {'TECHNICIAN_KEY': API_KEY}
try:
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
data = resp.json()
return data.get('conversations', [])
except:
return []
def get_conversation_content(request_id: int, notification_id: int) -> Optional[Dict]:
"""Get conversation content."""
url = f'{BASE_URL}/requests/{request_id}/notifications/{notification_id}'
params = {
'TECHNICIAN_KEY': API_KEY,
'INPUT_DATA': json.dumps({'type': 'conversation'})
}
try:
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
data = resp.json()
return data.get('notification')
except:
return None
def get_notes(request_id: int) -> List[Dict]:
"""Get notes for a request."""
url = f'{BASE_URL}/requests/{request_id}/notes'
params = {'TECHNICIAN_KEY': API_KEY}
try:
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
data = resp.json()
return data.get('notes', [])
except:
return []
def get_note_content(request_id: int, note_id: int) -> Optional[Dict]:
"""Get note content."""
url = f'{BASE_URL}/requests/{request_id}/notes/{note_id}'
params = {'TECHNICIAN_KEY': API_KEY}
try:
resp = requests.get(url, params=params, timeout=30, verify=False)
resp.raise_for_status()
data = resp.json()
return data.get('note')
except:
return None
def download_attachment(request_id: int, attachment_id: int, filename: str) -> Optional[str]:
"""Download attachment and return local path."""
# Create directory for this request
req_dir = os.path.join(ATTACHMENTS_DIR, str(request_id))
os.makedirs(req_dir, exist_ok=True)
# Check if already downloaded
local_path = os.path.join(req_dir, filename)
if os.path.exists(local_path):
return local_path
url = f'{BASE_URL}/requests/{request_id}/attachments/{attachment_id}'
params = {'TECHNICIAN_KEY': API_KEY}
try:
resp = requests.get(url, params=params, timeout=60, verify=False)
resp.raise_for_status()
with open(local_path, 'wb') as f:
f.write(resp.content)
return local_path
except Exception as e:
print(f" Error downloading attachment {attachment_id}: {e}")
return None
def extract_full_data() -> Dict:
"""Extract all data with conversations and attachments."""
os.makedirs(ATTACHMENTS_DIR, exist_ok=True)
extracted_data = {
'tickets': [],
'users': [],
'categories': [],
'priorities': [],
'statuses': [],
'conversations': [],
'attachments': []
}
# Get all requests
print("Extracting requests...")
requests_list = get_all_requests()
print(f"Total requests: {len(requests_list)}")
# Process each request
print("\nProcessing requests with conversations and attachments...")
for i, req_summary in enumerate(requests_list):
req_id = req_summary.get('id')
# Get full details
req = get_request_detail(req_id)
if not req:
continue
# Store ticket data
ticket = {
'ticket_id': req_id,
'subject': req.get('subject', ''),
'description': req.get('description', ''),
'requester': req.get('requester', {}),
'status': req.get('status', {}),
'priority': req.get('priority', {}),
'category': req.get('category', {}),
'technician': req.get('technician', {}),
'created_time': req.get('created_time', {}),
'completed_time': req.get('completed_time', {}),
'resolution': req.get('resolution', {}),
'mode': req.get('mode', {}),
'source': req.get('source', {}),
'has_conversation': req.get('has_conversation', False),
'has_notes': req.get('has_notes', False),
'has_attachments': req.get('has_attachments', False)
}
extracted_data['tickets'].append(ticket)
# Extract user
requester = req.get('requester', {})
if requester and requester.get('id'):
user = {
'user_id': requester.get('id'),
'name': requester.get('name', ''),
'email': requester.get('email_id', ''),
'phone': ''
}
if user not in extracted_data['users']:
extracted_data['users'].append(user)
# Extract category
category = req.get('category', {})
if category and category.get('id'):
cat = {'category_id': category.get('id'), 'name': category.get('name', '')}
if cat not in extracted_data['categories']:
extracted_data['categories'].append(cat)
# Extract priority
priority = req.get('priority', {})
if priority and priority.get('id'):
pri = {'priority_id': priority.get('id'), 'name': priority.get('name', '')}
if pri not in extracted_data['priorities']:
extracted_data['priorities'].append(pri)
# Extract status
status = req.get('status', {})
if status and status.get('id'):
stat = {'status_id': status.get('id'), 'name': status.get('name', '')}
if stat not in extracted_data['statuses']:
extracted_data['statuses'].append(stat)
# Get conversations
if req.get('has_conversation'):
convs = get_conversations(req_id)
for conv in convs:
conv_id = conv.get('id')
# Get full content
content = get_conversation_content(req_id, conv_id)
conversation = {
'ticket_id': req_id,
'conversation_id': conv_id,
'type': conv.get('type', 'conversation'),
'from': conv.get('from', {}),
'to': content.get('to', []) if content else [],
'cc': content.get('cc', []) if content else [],
'subject': content.get('title', '') if content else '',
'description': content.get('description', '') if content else '',
'sent_time': conv.get('sent_time', {}),
'has_attachments': conv.get('has_attachments', False),
'attachments': content.get('attachments', []) if content else []
}
extracted_data['conversations'].append(conversation)
# Download conversation attachments
if content and content.get('attachments'):
for att in content['attachments']:
att_id = att.get('id')
att_name = att.get('file_name', f'attachment_{att_id}')
local_path = download_attachment(req_id, att_id, att_name)
attachment = {
'ticket_id': req_id,
'attachment_id': att_id,
'filename': att_name,
'size': att.get('size', ''),
'content_url': att.get('content_url', ''),
'local_path': local_path,
'source': 'conversation',
'conversation_id': conv_id
}
extracted_data['attachments'].append(attachment)
# Get notes
if req.get('has_notes'):
notes = get_notes(req_id)
for note in notes:
note_id = note.get('id')
content = get_note_content(req_id, note_id)
note_data = {
'ticket_id': req_id,
'note_id': note_id,
'from': note.get('owner', {}) if note else {},
'description': content.get('description', '') if content else note.get('description', ''),
'created_time': note.get('created_time', {}),
'has_attachments': note.get('has_attachments', False)
}
# Store notes as conversations with type 'note'
note_data['type'] = 'note'
extracted_data['conversations'].append(note_data)
# Get request attachments
if req.get('has_attachments'):
for att in req.get('attachments', []):
att_id = att.get('id')
att_name = att.get('file_name', f'attachment_{att_id}')
local_path = download_attachment(req_id, att_id, att_name)
attachment = {
'ticket_id': req_id,
'attachment_id': att_id,
'filename': att_name,
'size': att.get('size', ''),
'content_url': att.get('content_url', ''),
'local_path': local_path,
'source': 'request'
}
extracted_data['attachments'].append(attachment)
if (i + 1) % 20 == 0:
print(f" Processed {i + 1}/{len(requests_list)} requests...")
print(f" Conversations so far: {len(extracted_data['conversations'])}")
print(f" Attachments so far: {len(extracted_data['attachments'])}")
print(f"\nExtraction complete!")
print(f" - Tickets: {len(extracted_data['tickets'])}")
print(f" - Users: {len(extracted_data['users'])}")
print(f" - Conversations: {len(extracted_data['conversations'])}")
print(f" - Attachments: {len(extracted_data['attachments'])}")
return extracted_data
def main():
"""Main execution function."""
try:
extracted_data = extract_full_data()
output_file = os.path.join(os.path.dirname(__file__), "extracted_full.json")
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(extracted_data, f, ensure_ascii=False, indent=2, default=str)
print(f"\nData saved to: {output_file}")
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()