# Connectors Package

A comprehensive collection of connector libraries for various services and APIs. This package provides a unified interface for connecting to different platforms and services.

## Available Connectors

### Jira Connector
A flexible and powerful Python connector for interacting with Jira API.

- **Generic Design**: Works with any Jira instance (Atlassian Cloud, Jira Server, Jira Data Center)
- **Flexible Authentication**: Supports both Bearer token and basic authentication
- **Dynamic Property Reading**: Extract any Jira issue properties using dot notation
- **Error Handling**: Comprehensive error handling with retry logic
- **Logging**: Detailed logging for debugging and monitoring

### Confluence Connector
A comprehensive Python connector for interacting with Confluence API, supporting reading, writing, and managing Confluence pages, spaces, and content.

- **Page Operations**: Read, create, update, and manage Confluence pages
- **Content Explanation**: Automatically explain and parse different content types (Gliffy diagrams, images, text)
- **Attachment Handling**: Download and manage page attachments
- **Space Management**: Work with Confluence spaces and their content
- **Search Functionality**: Search content using CQL (Confluence Query Language)

## Installation

### Install from PyPI (Recommended)

```bash
pip install connectors
```

This will automatically install all required dependencies:
- `requests>=2.31.0`
- `urllib3>=1.26.0`
- `pillow>=10.0.0` (for image processing)
- `pytesseract>=0.3.10` (for OCR functionality)

### Additional Requirements for OCR

For OCR functionality in the Confluence connector, install Tesseract OCR:

**Windows:**
```bash
# Download and install from: https://github.com/UB-Mannheim/tesseract/wiki
```

**macOS:**
```bash
brew install tesseract
```

**Linux:**
```bash
sudo apt-get install tesseract-ocr
```

### Install from Source

```bash
git clone https://github.com/yourusername/connectors.git
cd connectors
pip install .
```

## Quick Start

### Using Jira Connector

```python
from connectors.jira_connector import JiraConnector

# Initialize connector
connector = JiraConnector(
    jira_url="https://yourcompany.atlassian.net",
    token="your_api_token_here",
    service="my_service"
)

# Test connection
if connector.test_connection():
    print("Connected successfully!")
    
    # Get specific issue with custom properties
    properties = [
        'key',
        'fields.summary',
        'fields.status.name',
        'fields.assignee.displayName'
    ]
    
    issue = connector.get_issue("PROJ-123", properties)
    print(issue)

# Close connection
connector.close()
```

### Using Confluence Connector

```python
from connectors.confluence_connector import ConfluenceConnector

# Initialize connector
connector = ConfluenceConnector(
    confluence_url="https://yourcompany.atlassian.net",
    token="your_api_token_here",
    cloud=True
)

# Test connection
if connector.test_connection():
    print("Connected successfully!")
    
    # Get a page
    page = connector.get_page_by_id("PAGE-123", expand=["body.storage"])
    print(f"Page title: {page['title']}")
    
    # Explain page attachments
    explanations = connector.explain_all_attachments("PAGE-123")
    for title, explanation in explanations.items():
        print(f"\n{title}:\n{explanation}")

# Close connection
connector.close()
```

### Using Environment Variables

```bash
export JIRA_URL="https://yourcompany.atlassian.net"
export JIRA_TOKEN="your_api_token_here"
export JIRA_USERNAME="your_username"  # Optional
```

```python
import os
from connectors.jira_connector import JiraConnector

connector = JiraConnector(
    jira_url=os.getenv('JIRA_URL'),
    token=os.getenv('JIRA_TOKEN'),
    service="my_service",
    username=os.getenv('JIRA_USERNAME')  # Optional
)
```

## API Reference

### JiraConnector Class

#### Initialization Parameters

- `jira_url` (str): Base URL of Jira instance
- `token` (str): API token for authentication
- `service` (str): Service name for logging (default: "jira")
- `username` (str, optional): Username for basic auth
- `timeout` (int): Request timeout in seconds (default: 30)
- `verify_ssl` (bool): Verify SSL certificates (default: True)
- `max_retries` (int): Maximum retry attempts (default: 3)

#### Main Methods

##### Connection Methods
- `test_connection()`: Test connection to Jira
- `close()`: Close the session

##### Issue Methods
- `get_issue(issue_key, properties=None)`: Get issue details
- `search_issues(jql, properties=None, max_results=50, start_at=0)`: Search issues using JQL
- `get_projects()`: Get all accessible projects
- `get_project_issues(project_key, properties=None, max_results=50, start_at=0)`: Get issues from project
- `create_issue(project_key, issue_type, summary, description=None, **fields)`: Create new issue
- `update_issue(issue_key, **fields)`: Update existing issue

##### Comment Methods
- `add_comment(issue_key, comment)`: Add comment to issue

##### Transition Methods
- `get_issue_transitions(issue_key)`: Get available transitions
- `transition_issue(issue_key, transition_id)`: Transition issue to new status

##### Utility Methods
- `get_custom_fields()`: Get all custom fields

### ConfluenceConnector Class

#### Initialization Parameters

- `confluence_url` (str): Base URL of Confluence instance
- `token` (str): API token for authentication
- `verify_ssl` (bool): Verify SSL certificates (default: True)
- `max_retries` (int): Maximum retry attempts (default: 3)
- `cloud` (bool): Whether this is Atlassian Cloud instance

#### Main Methods

##### Connection Methods
- `test_connection()`: Test connection to Confluence
- `close()`: Close the session

##### Page Methods
- `get_page_by_id(page_id, expand=None)`: Get page by ID
- `get_page_by_title(space_key, title, expand=None)`: Get page by title
- `create_page(space_key, title, content, parent_id=None, content_format="storage")`: Create new page
- `update_page(page_id, title=None, content=None, content_format="storage")`: Update existing page
- `get_page_content(page_id, content_format="storage")`: Get page content
- `extract_text_from_page(page_id, include_metadata=False)`: Extract plain text from page

##### Attachment Methods
- `get_page_attachments(page_id)`: Get page attachments
- `explain_attachment(page_id, attachment_title)`: Explain attachment content
- `explain_all_attachments(page_id)`: Explain all page attachments

##### Space and Search Methods
- `get_space(space_key, expand=None)`: Get space information
- `get_space_pages(space_key, limit=25, start=0)`: Get pages in space
- `search_content(cql, limit=25, start=0)`: Search content using CQL

##### Comment and Label Methods
- `add_comment(page_id, comment)`: Add comment to page
- `get_page_comments(page_id)`: Get page comments
- `get_page_labels(page_id)`: Get page labels
- `add_labels(page_id, labels)`: Add labels to page

### Property Extraction

Use dot notation to extract nested properties:

```python
properties = [
    'key',                                    # Issue key
    'fields.summary',                         # Issue summary
    'fields.status.name',                     # Status name
    'fields.status.statusCategory.name',     # Status category
    'fields.assignee.displayName',           # Assignee name
    'fields.customfield_10010',               # Custom field
]
```

## Examples

### Search Issues with JQL

```python
# Find all open bugs in a project
jql = "project = PROJ AND issuetype = Bug AND status != Closed"
issues = connector.search_issues(jql, properties, max_results=100)

# Find issues assigned to me
jql = "assignee = currentUser() AND status = 'In Progress'"
my_issues = connector.search_issues(jql, properties)
```

### Work with Custom Fields

```python
# Get all custom fields
custom_fields = connector.get_custom_fields()

# Use custom field in property extraction
properties = [
    'key',
    'fields.summary',
    'fields.customfield_10010',  # Text field
    'fields.customfield_10020.value',  # Select field
]

issues = connector.search_issues("project = PROJ", properties)
```

### Create and Update Issues

```python
# Create new issue
new_issue = connector.create_issue(
    project_key="PROJ",
    issue_type="Task",
    summary="New task from connector",
    description="Task description",
    priority={"name": "High"},
    labels=["urgent", "backend"]
)

# Update issue
connector.update_issue(
    issue_key="PROJ-123",
    summary="Updated summary",
    priority={"name": "Medium"}
)
```

## Environment Variables

### Jira Connector

#### Required
- `JIRA_URL`: Your Jira instance URL
- `JIRA_TOKEN`: Your API token

#### Optional
- `JIRA_USERNAME`: Username for basic auth
- `JIRA_TIMEOUT`: Request timeout (default: 30)
- `JIRA_VERIFY_SSL`: Verify SSL certificates (default: true)
- `JIRA_MAX_RETRIES`: Maximum retry attempts (default: 3)

### Confluence Connector

#### Required
- `CONFLUENCE_URL`: Your Confluence instance URL
- `CONFLUENCE_TOKEN`: Your API token

#### Optional
- `CONFLUENCE_TIMEOUT`: Request timeout (default: 30)
- `CONFLUENCE_VERIFY_SSL`: Verify SSL certificates (default: true)
- `CONFLUENCE_MAX_RETRIES`: Maximum retry attempts (default: 3)
- `CONFLUENCE_CLOUD`: Whether this is Atlassian Cloud (default: false)

## Error Handling

The connector includes comprehensive error handling:

- **Retry Logic**: Automatic retries for failed requests
- **Logging**: Detailed error messages and debug information
- **Graceful Degradation**: Continues operation even if some requests fail

```python
try:
    issues = connector.search_issues(jql, properties)
except Exception as e:
    print(f"Search failed: {e}")
    # Handle error appropriately
```

## Security Considerations

1. **API Tokens**: Store API tokens securely, don't commit them to version control
2. **Environment Variables**: Use environment variables for sensitive data
3. **SSL Verification**: Keep SSL verification enabled in production
4. **Access Control**: Use tokens with minimal required permissions

## Troubleshooting

### Common Issues

1. **Authentication Failed**
   - Check API token is valid and not expired
   - Verify correct authentication method (token vs basic auth)

2. **SSL Certificate Error**
   - Set `verify_ssl=False` for self-signed certificates (not recommended for production)
   - Check if Jira URL is correct

3. **Permission Denied**
   - Ensure token has required permissions
   - Check user has access to the project/issue

4. **Rate Limiting**
   - Implement delays between requests
   - Use appropriate timeout values

### Debug Logging

Enable debug logging:

```python
import logging
logging.getLogger("JiraConnector").setLevel(logging.DEBUG)
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

This project is licensed under the MIT License.

## Support

For issues and questions:
- Check the troubleshooting section
- Create an issue in the repository

## Additional Connectors

This package includes Jira and Confluence connectors. Future additions may include:

- GitHub Connector
- Slack Connector
- Azure DevOps Connector
- Salesforce Connector
- And more...

Contributions for new connectors are welcome!
