push_tools.py 2.6 KB

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