filtering.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 canonicaljson import encode_canonical_json
  16. from synapse.api.errors import Codes, SynapseError
  17. from synapse.util.caches.descriptors import cachedInlineCallbacks
  18. from ._base import SQLBaseStore, db_to_json
  19. class FilteringStore(SQLBaseStore):
  20. @cachedInlineCallbacks(num_args=2)
  21. def get_user_filter(self, user_localpart, filter_id):
  22. # filter_id is BIGINT UNSIGNED, so if it isn't a number, fail
  23. # with a coherent error message rather than 500 M_UNKNOWN.
  24. try:
  25. int(filter_id)
  26. except ValueError:
  27. raise SynapseError(400, "Invalid filter ID", Codes.INVALID_PARAM)
  28. def_json = yield self._simple_select_one_onecol(
  29. table="user_filters",
  30. keyvalues={"user_id": user_localpart, "filter_id": filter_id},
  31. retcol="filter_json",
  32. allow_none=False,
  33. desc="get_user_filter",
  34. )
  35. return db_to_json(def_json)
  36. def add_user_filter(self, user_localpart, user_filter):
  37. def_json = encode_canonical_json(user_filter)
  38. # Need an atomic transaction to SELECT the maximal ID so far then
  39. # INSERT a new one
  40. def _do_txn(txn):
  41. sql = (
  42. "SELECT filter_id FROM user_filters "
  43. "WHERE user_id = ? AND filter_json = ?"
  44. )
  45. txn.execute(sql, (user_localpart, def_json))
  46. filter_id_response = txn.fetchone()
  47. if filter_id_response is not None:
  48. return filter_id_response[0]
  49. sql = "SELECT MAX(filter_id) FROM user_filters " "WHERE user_id = ?"
  50. txn.execute(sql, (user_localpart,))
  51. max_id = txn.fetchone()[0]
  52. if max_id is None:
  53. filter_id = 0
  54. else:
  55. filter_id = max_id + 1
  56. sql = (
  57. "INSERT INTO user_filters (user_id, filter_id, filter_json)"
  58. "VALUES(?, ?, ?)"
  59. )
  60. txn.execute(sql, (user_localpart, filter_id, def_json))
  61. return filter_id
  62. return self.runInteraction("add_user_filter", _do_txn)