|
| 1 | +import logging |
| 2 | +from dataclasses import dataclass, asdict |
| 3 | +from datetime import datetime |
| 4 | +from functools import lru_cache |
| 5 | +from typing import Dict, List, Optional |
| 6 | +from urllib.parse import urlparse |
| 7 | + |
| 8 | +from mattermostdriver import Driver |
| 9 | + |
| 10 | +from data_source_api.base_data_source import BaseDataSource, ConfigField, HTMLInputType |
| 11 | +from data_source_api.basic_document import BasicDocument, DocumentType |
| 12 | +from data_source_api.exception import InvalidDataSourceConfig |
| 13 | +from data_source_api.utils import parse_with_workers |
| 14 | +from indexing_queue import IndexingQueue |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class MattermostChannel: |
| 21 | + id: str |
| 22 | + name: str |
| 23 | + team_id: str |
| 24 | + |
| 25 | + |
| 26 | +@dataclass |
| 27 | +class MattermostConfig: |
| 28 | + url: str |
| 29 | + token: str |
| 30 | + scheme: Optional[str] = "https" |
| 31 | + port: Optional[int] = 443 |
| 32 | + |
| 33 | + def __post_init__(self): |
| 34 | + try: |
| 35 | + parsed_url = urlparse(self.url) |
| 36 | + except Exception as e: |
| 37 | + raise ValueError from e |
| 38 | + |
| 39 | + self.url = parsed_url.hostname |
| 40 | + self.port = parsed_url.port if parsed_url.port is not None else self.port |
| 41 | + self.scheme = parsed_url.scheme if parsed_url.scheme != "" else self.scheme |
| 42 | + |
| 43 | + |
| 44 | +class MattermostDataSource(BaseDataSource): |
| 45 | + FEED_BATCH_SIZE = 500 |
| 46 | + |
| 47 | + @staticmethod |
| 48 | + def get_config_fields() -> List[ConfigField]: |
| 49 | + return [ |
| 50 | + ConfigField(label="Mattermost Server", name="url", placeholder="https://mattermost.server.com", |
| 51 | + input_type=HTMLInputType.TEXT), |
| 52 | + ConfigField(label="Access Token", name="token", placeholder="paste-your-access-token-here", |
| 53 | + input_type=HTMLInputType.PASSWORD), |
| 54 | + ] |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def validate_config(config: Dict) -> None: |
| 58 | + try: |
| 59 | + parsed_config = MattermostConfig(**config) |
| 60 | + maattermost = Driver(options=asdict(parsed_config)) |
| 61 | + maattermost.login() |
| 62 | + except Exception as e: |
| 63 | + raise InvalidDataSourceConfig from e |
| 64 | + |
| 65 | + def __init__(self, *args, **kwargs): |
| 66 | + super().__init__(*args, **kwargs) |
| 67 | + mattermost_config = MattermostConfig(**self._config) |
| 68 | + self._mattermost = Driver(options=asdict(mattermost_config)) |
| 69 | + |
| 70 | + def _list_channels(self) -> List[MattermostChannel]: |
| 71 | + channels = self._mattermost.channels.client.get(f"/users/me/channels") |
| 72 | + return [MattermostChannel(id=channel["id"], name=channel["name"], team_id=channel["team_id"]) |
| 73 | + for channel in channels] |
| 74 | + |
| 75 | + def _is_valid_message(self, message: Dict) -> bool: |
| 76 | + return message["type"] == "" |
| 77 | + |
| 78 | + def _is_valid_channel(self, channel: MattermostChannel) -> bool: |
| 79 | + return channel.team_id != "" |
| 80 | + |
| 81 | + def _list_posts_in_channel(self, channel_id: str, page: int) -> Dict: |
| 82 | + endpoint = f"/channels/{channel_id}/posts" |
| 83 | + params = { |
| 84 | + "since": int(self._last_index_time.timestamp()) * 1000, |
| 85 | + "page": page |
| 86 | + } |
| 87 | + |
| 88 | + posts = self._mattermost.channels.client.get(endpoint, params=params) |
| 89 | + return posts |
| 90 | + |
| 91 | + def _feed_new_documents(self) -> None: |
| 92 | + self._mattermost.login() |
| 93 | + channels = self._list_channels() |
| 94 | + |
| 95 | + logger.info(f'Found {len(channels)} channels') |
| 96 | + parse_with_workers(self._parse_channel_worker, channels) |
| 97 | + |
| 98 | + def _parse_channel_worker(self, channels: List[MattermostChannel]): |
| 99 | + for channel in channels: |
| 100 | + self._feed_channel(channel) |
| 101 | + |
| 102 | + def _get_mattermost_url(self): |
| 103 | + options = self._mattermost.options |
| 104 | + return f"{options['scheme']}://{options['url']}:{options['port']}" |
| 105 | + |
| 106 | + def _get_team_url(self, channel: MattermostChannel): |
| 107 | + url = self._get_mattermost_url() |
| 108 | + team = self._mattermost.teams.get_team(channel.team_id) |
| 109 | + return f"{url}/{team['name']}" |
| 110 | + |
| 111 | + @lru_cache(maxsize=512) |
| 112 | + def _get_mattermost_user(self, user_id: str): |
| 113 | + return self._mattermost.users.get_user(user_id)["username"] |
| 114 | + |
| 115 | + def _feed_channel(self, channel: MattermostChannel): |
| 116 | + if not self._is_valid_channel(channel): |
| 117 | + return |
| 118 | + logger.info(f'Feeding channel {channel.name}') |
| 119 | + |
| 120 | + page = 0 |
| 121 | + total_fed = 0 |
| 122 | + |
| 123 | + parsed_posts = [] |
| 124 | + |
| 125 | + team_url = self._get_team_url(channel) |
| 126 | + |
| 127 | + while True: |
| 128 | + posts = self._list_posts_in_channel(channel.id, page) |
| 129 | + |
| 130 | + last_message: Optional[BasicDocument] = None |
| 131 | + |
| 132 | + posts["order"].reverse() |
| 133 | + for id in posts["order"]: |
| 134 | + post = posts["posts"][id] |
| 135 | + |
| 136 | + if not self._is_valid_message(post): |
| 137 | + if last_message is not None: |
| 138 | + parsed_posts.append(last_message) |
| 139 | + last_message = None |
| 140 | + continue |
| 141 | + |
| 142 | + author = self._get_mattermost_user(post["user_id"]) |
| 143 | + content = post["message"] |
| 144 | + |
| 145 | + if last_message is not None: |
| 146 | + if last_message.author == author: |
| 147 | + last_message.content += f"\n{content}" |
| 148 | + continue |
| 149 | + else: |
| 150 | + parsed_posts.append(last_message) |
| 151 | + if len(parsed_posts) >= MattermostDataSource.FEED_BATCH_SIZE: |
| 152 | + total_fed += len(parsed_posts) |
| 153 | + IndexingQueue.get().feed(docs=parsed_posts) |
| 154 | + parsed_posts = [] |
| 155 | + |
| 156 | + author_image_url = f"{self._get_mattermost_url()}/api/v4/users/{post['user_id']}/image?_=0" |
| 157 | + timestamp = datetime.fromtimestamp(post["update_at"] / 1000) |
| 158 | + last_message = BasicDocument( |
| 159 | + id=id, |
| 160 | + data_source_id=self._data_source_id, |
| 161 | + title=channel.name, |
| 162 | + content=content, |
| 163 | + timestamp=timestamp, |
| 164 | + author=author, |
| 165 | + author_image_url=author_image_url, |
| 166 | + location=channel.name, |
| 167 | + url=f"{team_url}/pl/{id}", |
| 168 | + type=DocumentType.MESSAGE |
| 169 | + ) |
| 170 | + |
| 171 | + if last_message is not None: |
| 172 | + parsed_posts.append(last_message) |
| 173 | + |
| 174 | + if posts["prev_post_id"] == "": |
| 175 | + break |
| 176 | + page += 1 |
| 177 | + |
| 178 | + IndexingQueue.get().feed(docs=parsed_posts) |
| 179 | + total_fed += len(parsed_posts) |
| 180 | + |
| 181 | + if len(parsed_posts) > 0: |
| 182 | + logger.info(f"Worker fed {total_fed} documents") |
0 commit comments