Skip to content

Commit

Permalink
Merge pull request #58 from bugout-dev/slack-integration-tags-edit-fix
Browse files Browse the repository at this point in the history
Slack integration tags edit fix
  • Loading branch information
Andrei-Dolgolev committed Jan 11, 2023
2 parents e5f536d + 95012f7 commit cf02199
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 36 deletions.
4 changes: 2 additions & 2 deletions spire/broodusers.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def bugout_auth_user_info(
user_url = f"{bugout_auth_url}/user"
headers = {"Authorization": access_token}
try:
user_response = requests.get(user_url, headers=headers)
user_response = requests.get(user_url, headers=headers) # type: ignore
user_response.raise_for_status()
user_response_body = user_response.json()
user_response_body["user_id"]
Expand All @@ -110,7 +110,7 @@ def bugout_auth_user_info(

user_info_url = f"{user_url}/{user_response_body['user_id']}"
try:
user_info_response = requests.get(user_info_url, headers=headers)
user_info_response = requests.get(user_info_url, headers=headers) # type: ignore
user_info_response.raise_for_status()
body: Dict[str, Any] = user_info_response.json()
body["user_id"]
Expand Down
34 changes: 17 additions & 17 deletions spire/journal/actions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
Journal-related actions in Spire
"""
from asyncio import streams
from datetime import date, timedelta, datetime
import calendar
import json
Expand Down Expand Up @@ -156,7 +155,7 @@ def acl_auth(
def acl_check(
acl: Dict[HolderType, List[str]],
required_scopes: Set[Union[JournalScopes, JournalEntryScopes]],
check_type: HolderType = None,
check_type: Optional[HolderType] = None,
) -> None:
"""
Checks if provided scopes from handler intersect with existing permissions for user/group
Expand All @@ -176,7 +175,7 @@ def acl_check(


async def find_journals(
db_session: Session, user_id: UUID, user_group_id_list: List[str] = None
db_session: Session, user_id: UUID, user_group_id_list: Optional[List[str]] = None
) -> List[Journal]:
"""
Return list of journals for requested user.
Expand Down Expand Up @@ -220,7 +219,7 @@ async def find_journals(
async def find_journal(
db_session: Session,
journal_spec: JournalSpec,
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
deleted: bool = False,
) -> Journal:
"""
Expand Down Expand Up @@ -321,7 +320,7 @@ async def update_journal(
db_session: Session,
journal_spec: JournalSpec,
update_spec: UpdateJournalSpec,
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
) -> Journal:
"""
Updates a journal object in the database. If the record to be updated does not exist, raises a
Expand All @@ -343,7 +342,9 @@ async def update_journal(


async def delete_journal(
db_session: Session, journal_spec: JournalSpec, user_group_id_list: List[str] = None
db_session: Session,
journal_spec: JournalSpec,
user_group_id_list: Optional[List[str]] = None,
) -> Journal:
"""
Deletes the given journal from the database. If there is no journal with that ID, raises a
Expand All @@ -367,7 +368,7 @@ async def journal_statistics(
journal_spec: JournalSpec,
stats_spec: JournalStatisticsSpecs,
tags: List[str],
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
) -> JournalStatisticsResponse:

"""
Expand Down Expand Up @@ -609,7 +610,7 @@ async def get_journal_entries(
db_session: Session,
journal_spec: JournalSpec,
entry_id: Optional[UUID],
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
context_spec: Optional[ContextSpec] = None,
limit: Optional[int] = 10,
offset: int = 0,
Expand Down Expand Up @@ -748,7 +749,7 @@ async def delete_journal_entries(
db_session: Session,
journal_spec: JournalSpec,
entry_ids: List[UUID],
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
) -> ListJournalEntriesResponse:
"""
Deletes the given journal entries.
Expand Down Expand Up @@ -877,11 +878,11 @@ async def get_entries_count_by_tags(
async def get_journal_most_used_tags(
db_session: Session,
journal_spec: JournalSpec,
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
limit: int = 7,
) -> List[Any]:
) -> List[Tuple[str, int]]:
"""
Returns a list of tags for a given entry.
Returns most used tags in journal.
"""

journal = await find_journal(
Expand All @@ -893,9 +894,8 @@ async def get_journal_most_used_tags(
db_session.query(
JournalEntryTag.tag, func.count(JournalEntryTag.tag).label("total")
)
.join(JournalEntry)
.join(Journal)
.filter(Journal.id == journal.id)
.join(JournalEntry, JournalEntryTag.journal_entry_id == JournalEntry.id)
.filter(JournalEntry.journal_id == journal.id)
.order_by(text("total DESC"))
.group_by(JournalEntryTag.tag)
.limit(limit)
Expand Down Expand Up @@ -944,7 +944,7 @@ async def get_journal_entry_tags(
db_session: Session,
journal_spec: JournalSpec,
entry_id: UUID,
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
) -> List[JournalEntryTag]:
"""
Returns a list of tags for a given entry.
Expand Down Expand Up @@ -1019,7 +1019,7 @@ async def delete_journal_entry_tag(
journal_spec: JournalSpec,
entry_id: UUID,
tag: str,
user_group_id_list: List[str] = None,
user_group_id_list: Optional[List[str]] = None,
) -> Optional[JournalEntryTag]:
"""
Delete the given tags from the given journal entry (all specified in the tag_request).
Expand Down
14 changes: 8 additions & 6 deletions spire/journal/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime, timezone
import logging
from typing import Any, cast, Dict, List, Optional, Set, Union
from typing import Any, cast, Dict, List, Optional, Set, Union, Tuple
from uuid import UUID

from elasticsearch import Elasticsearch
Expand Down Expand Up @@ -64,6 +64,7 @@
EntryUpdateTagActions,
StatsTypes,
TimeScale,
TagUsage,
)
from ..data import VersionResponse
from ..middleware import BroodAuthMiddleware
Expand Down Expand Up @@ -669,7 +670,7 @@ async def update_journal_stats(
"stats_type": update_request.stats_type,
"timescale": update_request.timescale,
},
headers={BUGOUT_DRONES_TOKEN_HEADER: BUGOUT_DRONES_TOKEN},
headers={BUGOUT_DRONES_TOKEN_HEADER: BUGOUT_DRONES_TOKEN}, # type: ignore
timeout=7,
).json()
return DronesStatisticsResponce.parse_obj(drones_statistics)
Expand Down Expand Up @@ -1670,15 +1671,16 @@ async def delete_entries_by_tags(
)


@app.get("/{journal_id}/tags", tags=["tags"], response_model=List[List[Any]])
@app.get("/{journal_id}/tags", tags=["tags"], response_model=List[TagUsage])
async def most_used_tags(
journal_id: UUID,
request: Request,
db_session: Session = Depends(db.yield_connection_from_env),
) -> List[List[Any]]:
) -> List[TagUsage]:
"""
Get all tags for a journal entry.
"""

ensure_journal_permission(
db_session,
request.state.user_id,
Expand All @@ -1689,7 +1691,7 @@ async def most_used_tags(

journal_spec = JournalSpec(id=journal_id, bugout_user_id=request.state.user_id)
try:
tags = await actions.get_journal_most_used_tags(
tags: List[Tuple[str, int]] = await actions.get_journal_most_used_tags(
db_session,
journal_spec,
user_group_id_list=request.state.user_group_id_list,
Expand All @@ -1703,7 +1705,7 @@ async def most_used_tags(
logger.error(f"Error listing journal entries: {str(e)}")
raise HTTPException(status_code=500)

return tags
return [TagUsage(tag=tag[0], count=tag[1]) for tag in tags]


@app.post(
Expand Down
5 changes: 5 additions & 0 deletions spire/journal/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,8 @@ class JournalTTLRulesListResponse(BaseModel):

class DeletingQuery(BaseModel):
search_query: str


class TagUsage(BaseModel):
tag: str
count: int
2 changes: 1 addition & 1 deletion spire/slack/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ async def slack_interaction(

body = await request.form()
try:
payload = json.loads(body["payload"])
payload = json.loads(body["payload"]) # type: ignore
except Exception as e:
logger.error("Error parsing interaction payload:")
logger.error(repr(e))
Expand Down
26 changes: 16 additions & 10 deletions spire/slack/interactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import argparse
import json
import logging
from typing import Any, Callable, cast, Coroutine, Dict, List, Optional, Union, Tuple
from typing import Any, Callable, cast, Coroutine, Dict, List, Optional, Union

import requests
import requests # type: ignore
from concurrent.futures import ThreadPoolExecutor

from .models import SlackOAuthEvent, SlackIndexConfiguration, SlackBugoutUser
Expand Down Expand Up @@ -45,7 +45,7 @@
action_for_logs = {"POST": "Creating", "PUT": "Updating", "DELETE": "Deleting"}


def generate_entry_form(form: Dict[str, Any] = None) -> List[Any]:
def generate_entry_form(form: Optional[Dict[str, Any]] = None) -> List[Any]:
"""
Generate modal blocks for create/update entry form
note: If form init is None then return empty entry form
Expand Down Expand Up @@ -105,7 +105,10 @@ def generate_entry_form(form: Dict[str, Any] = None) -> List[Any]:
"type": "multi_external_select",
"min_query_length": 0,
},
"hint": {"type": "plain_text", "text": "Select tags from dropdown menu."},
"hint": {
"type": "plain_text",
"text": "Select tags from dropdown menu or type them manually. Limit 75 characters per tag.",
},
}
if form.get("tags_initial", None):
modal_tags["element"]["initial_options"] = []
Expand Down Expand Up @@ -789,8 +792,8 @@ async def create_journal_msg_open(payload: Dict[str, Any]) -> None:
raise ValueError("Bad interaction payload for view_submission")

message_channel = payload.get("channel", {}).get("id")
message_ts = payload.get("message_ts")
message_user = message_context.get("user")
message_ts = payload.get("message_ts", "")
message_user = message_context.get("user", "")

with ThreadPoolExecutor(max_workers=THREAD_WORKERS) as executor:
f_permalink = executor.submit(
Expand Down Expand Up @@ -994,7 +997,7 @@ def journal_entry_request_handler(
"Authorization": f"Bearer {bugout_user.bugout_access_token}",
}
try:
r = requests.request(method, headers=headers, url=url, json=payload, timeout=3)
r = requests.request(method, headers=headers, url=url, json=payload, timeout=5)
r.raise_for_status()
except Exception as e:
logger.error(
Expand Down Expand Up @@ -1124,11 +1127,11 @@ async def return_tags_options(payload: Dict[str, Any]) -> Dict[str, Any]:

options: Dict[str, Any] = {"options": []}

if len(payload.get("value", "")) > 0:
if len(payload.get("value", "")) > 0 and len(payload.get("value", "")) <= 75:
options["options"].append(
{
"text": {"type": "plain_text", "text": payload["value"]},
"value": "value-0",
"value": payload["value"],
}
)
return options
Expand Down Expand Up @@ -1189,7 +1192,10 @@ async def return_tags_options(payload: Dict[str, Any]) -> Dict[str, Any]:
raise
[
options["options"].append(
{"text": {"type": "plain_text", "text": text[0]}, "value": f"value-{index}"}
{
"text": {"type": "plain_text", "text": text["tag"]},
"value": f"most-used-tag-{index}",
}
)
for index, text in enumerate(most_used_tags)
]
Expand Down

0 comments on commit cf02199

Please sign in to comment.