filtering.py 2.8 KB

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