push_tools.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Dict
  15. from synapse.events import EventBase
  16. from synapse.push.presentable_names import calculate_room_name, name_from_member_event
  17. from synapse.storage.controllers import StorageControllers
  18. from synapse.storage.databases.main import DataStore
  19. from synapse.util.async_helpers import concurrently_execute
  20. async def get_badge_count(store: DataStore, user_id: str, group_by_room: bool) -> int:
  21. invites = await store.get_invited_rooms_for_local_user(user_id)
  22. joins = await store.get_rooms_for_user(user_id)
  23. badge = len(invites)
  24. room_notifs = []
  25. async def get_room_unread_count(room_id: str) -> None:
  26. room_notifs.append(
  27. await store.get_unread_event_push_actions_by_room_for_user(
  28. room_id,
  29. user_id,
  30. )
  31. )
  32. await concurrently_execute(get_room_unread_count, joins, 10)
  33. for notifs in room_notifs:
  34. if notifs.notify_count == 0:
  35. continue
  36. if group_by_room:
  37. # return one badge count per conversation
  38. badge += 1
  39. else:
  40. # increment the badge count by the number of unread messages in the room
  41. badge += notifs.notify_count
  42. return badge
  43. async def get_context_for_event(
  44. storage: StorageControllers, ev: EventBase, user_id: str
  45. ) -> Dict[str, str]:
  46. ctx = {}
  47. room_state_ids = await storage.state.get_state_ids_for_event(ev.event_id)
  48. # we no longer bother setting room_alias, and make room_name the
  49. # human-readable name instead, be that m.room.name, an alias or
  50. # a list of people in the room
  51. name = await calculate_room_name(
  52. storage.main, room_state_ids, user_id, fallback_to_single_member=False
  53. )
  54. if name:
  55. ctx["name"] = name
  56. sender_state_event_id = room_state_ids[("m.room.member", ev.sender)]
  57. sender_state_event = await storage.main.get_event(sender_state_event_id)
  58. ctx["sender_display_name"] = name_from_member_event(sender_state_event)
  59. return ctx