push_tools.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. async def get_badge_count(store: DataStore, user_id: str, group_by_room: bool) -> int:
  20. invites = await store.get_invited_rooms_for_local_user(user_id)
  21. joins = await store.get_rooms_for_user(user_id)
  22. badge = len(invites)
  23. for room_id in joins:
  24. notifs = await (
  25. store.get_unread_event_push_actions_by_room_for_user(
  26. room_id,
  27. user_id,
  28. )
  29. )
  30. if notifs.notify_count == 0:
  31. continue
  32. if group_by_room:
  33. # return one badge count per conversation
  34. badge += 1
  35. else:
  36. # increment the badge count by the number of unread messages in the room
  37. badge += notifs.notify_count
  38. return badge
  39. async def get_context_for_event(
  40. storage: StorageControllers, ev: EventBase, user_id: str
  41. ) -> Dict[str, str]:
  42. ctx = {}
  43. room_state_ids = await storage.state.get_state_ids_for_event(ev.event_id)
  44. # we no longer bother setting room_alias, and make room_name the
  45. # human-readable name instead, be that m.room.name, an alias or
  46. # a list of people in the room
  47. name = await calculate_room_name(
  48. storage.main, room_state_ids, user_id, fallback_to_single_member=False
  49. )
  50. if name:
  51. ctx["name"] = name
  52. sender_state_event_id = room_state_ids[("m.room.member", ev.sender)]
  53. sender_state_event = await storage.main.get_event(sender_state_event_id)
  54. ctx["sender_display_name"] = name_from_member_event(sender_state_event)
  55. return ctx