|
| 1 | +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. |
| 2 | + |
| 3 | +import logging |
| 4 | +from functools import partial |
| 5 | +from typing import Any, Iterable, List, Mapping, Optional |
| 6 | + |
| 7 | +import requests |
| 8 | +from airbyte_cdk.models import SyncMode |
| 9 | +from airbyte_cdk.sources.declarative.partition_routers import SinglePartitionRouter |
| 10 | +from airbyte_cdk.sources.declarative.retrievers import SimpleRetriever |
| 11 | +from airbyte_cdk.sources.declarative.types import Record, StreamSlice |
| 12 | +from airbyte_cdk.sources.streams.core import StreamData |
| 13 | +from airbyte_cdk.sources.streams.http import HttpStream |
| 14 | +from airbyte_cdk.sources.streams.http.auth import TokenAuthenticator |
| 15 | + |
| 16 | +LOGGER = logging.getLogger("airbyte_logger") |
| 17 | + |
| 18 | + |
| 19 | +class JoinChannelsStream(HttpStream): |
| 20 | + """ |
| 21 | + This class is a special stream which joins channels because the Slack API only returns messages from channels this bot is in. |
| 22 | + Its responses should only be logged for debugging reasons, not read as records. |
| 23 | + """ |
| 24 | + |
| 25 | + url_base = "https://slack.com/api/" |
| 26 | + http_method = "POST" |
| 27 | + primary_key = "id" |
| 28 | + |
| 29 | + def __init__(self, channel_filter: List[str] = None, **kwargs): |
| 30 | + self.channel_filter = channel_filter or [] |
| 31 | + super().__init__(**kwargs) |
| 32 | + |
| 33 | + def path(self, **kwargs) -> str: |
| 34 | + return "conversations.join" |
| 35 | + |
| 36 | + def parse_response(self, response: requests.Response, stream_slice: Mapping[str, Any] = None, **kwargs) -> Iterable: |
| 37 | + """ |
| 38 | + Override to simply indicate that the specific channel was joined successfully. |
| 39 | + This method should not return any data, but should return an empty iterable. |
| 40 | + """ |
| 41 | + is_ok = response.json().get("ok", False) |
| 42 | + if is_ok: |
| 43 | + self.logger.info(f"Successfully joined channel: {stream_slice['channel_name']}") |
| 44 | + else: |
| 45 | + self.logger.info(f"Unable to joined channel: {stream_slice['channel_name']}. Reason: {response.json()}") |
| 46 | + return [] |
| 47 | + |
| 48 | + def request_body_json(self, stream_slice: Mapping = None, **kwargs) -> Optional[Mapping]: |
| 49 | + if stream_slice: |
| 50 | + return {"channel": stream_slice.get("channel")} |
| 51 | + |
| 52 | + def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: |
| 53 | + """ |
| 54 | + The pagination is not applicable to this Service Stream. |
| 55 | + """ |
| 56 | + return None |
| 57 | + |
| 58 | + |
| 59 | +class ChannelsRetriever(SimpleRetriever): |
| 60 | + def __post_init__(self, parameters: Mapping[str, Any]): |
| 61 | + super().__post_init__(parameters) |
| 62 | + self.stream_slicer = SinglePartitionRouter(parameters={}) |
| 63 | + self.record_selector.transformations = [] |
| 64 | + |
| 65 | + def should_join_to_channel(self, config: Mapping[str, Any], record: Record) -> bool: |
| 66 | + """ |
| 67 | + The `is_member` property indicates whether the API Bot is already assigned / joined to the channel. |
| 68 | + https://api.slack.com/types/conversation#booleans |
| 69 | + """ |
| 70 | + return config["join_channels"] and not record.get("is_member") |
| 71 | + |
| 72 | + def make_join_channel_slice(self, channel: Mapping[str, Any]) -> Mapping[str, Any]: |
| 73 | + channel_id: str = channel.get("id") |
| 74 | + channel_name: str = channel.get("name") |
| 75 | + LOGGER.info(f"Joining Slack Channel: `{channel_name}`") |
| 76 | + return {"channel": channel_id, "channel_name": channel_name} |
| 77 | + |
| 78 | + def join_channels_stream(self, config) -> JoinChannelsStream: |
| 79 | + token = config["credentials"].get("api_token") or config["credentials"].get("access_token") |
| 80 | + authenticator = TokenAuthenticator(token) |
| 81 | + channel_filter = config["channel_filter"] |
| 82 | + return JoinChannelsStream(authenticator=authenticator, channel_filter=channel_filter) |
| 83 | + |
| 84 | + def join_channel(self, config: Mapping[str, Any], record: Mapping[str, Any]): |
| 85 | + list( |
| 86 | + self.join_channels_stream(config).read_records( |
| 87 | + sync_mode=SyncMode.full_refresh, |
| 88 | + stream_slice=self.make_join_channel_slice(record), |
| 89 | + ) |
| 90 | + ) |
| 91 | + |
| 92 | + def read_records( |
| 93 | + self, |
| 94 | + records_schema: Mapping[str, Any], |
| 95 | + stream_slice: Optional[StreamSlice] = None, |
| 96 | + ) -> Iterable[StreamData]: |
| 97 | + _slice = stream_slice or StreamSlice(partition={}, cursor_slice={}) # None-check |
| 98 | + |
| 99 | + self._paginator.reset() |
| 100 | + |
| 101 | + most_recent_record_from_slice = None |
| 102 | + record_generator = partial( |
| 103 | + self._parse_records, |
| 104 | + stream_state=self.state or {}, |
| 105 | + stream_slice=_slice, |
| 106 | + records_schema=records_schema, |
| 107 | + ) |
| 108 | + |
| 109 | + for stream_data in self._read_pages(record_generator, self.state, _slice): |
| 110 | + # joining channel logic |
| 111 | + if self.should_join_to_channel(self.config, stream_data): |
| 112 | + self.join_channel(self.config, stream_data) |
| 113 | + |
| 114 | + current_record = self._extract_record(stream_data, _slice) |
| 115 | + if self.cursor and current_record: |
| 116 | + self.cursor.observe(_slice, current_record) |
| 117 | + |
| 118 | + most_recent_record_from_slice = self._get_most_recent_record(most_recent_record_from_slice, current_record, _slice) |
| 119 | + yield stream_data |
| 120 | + |
| 121 | + if self.cursor: |
| 122 | + self.cursor.observe(_slice, most_recent_record_from_slice) |
| 123 | + return |
0 commit comments