push_tools.py 2.5 KB

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