as_users.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright 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. import logging
  15. from synapse.config.appservice import load_appservices
  16. logger = logging.getLogger(__name__)
  17. def run_create(cur, database_engine, *args, **kwargs):
  18. # NULL indicates user was not registered by an appservice.
  19. try:
  20. cur.execute("ALTER TABLE users ADD COLUMN appservice_id TEXT")
  21. except Exception:
  22. # Maybe we already added the column? Hope so...
  23. pass
  24. def run_upgrade(cur, database_engine, config, *args, **kwargs):
  25. cur.execute("SELECT name FROM users")
  26. rows = cur.fetchall()
  27. config_files = []
  28. try:
  29. config_files = config.app_service_config_files
  30. except AttributeError:
  31. logger.warning("Could not get app_service_config_files from config")
  32. pass
  33. appservices = load_appservices(config.server_name, config_files)
  34. owned = {}
  35. for row in rows:
  36. user_id = row[0]
  37. for appservice in appservices:
  38. if appservice.is_exclusive_user(user_id):
  39. if user_id in owned.keys():
  40. logger.error(
  41. "user_id %s was owned by more than one application"
  42. " service (IDs %s and %s); assigning arbitrarily to %s"
  43. % (user_id, owned[user_id], appservice.id, owned[user_id])
  44. )
  45. owned.setdefault(appservice.id, []).append(user_id)
  46. for as_id, user_ids in owned.items():
  47. n = 100
  48. user_chunks = (user_ids[i : i + 100] for i in range(0, len(user_ids), n))
  49. for chunk in user_chunks:
  50. cur.execute(
  51. database_engine.convert_param_style(
  52. "UPDATE users SET appservice_id = ? WHERE name IN (%s)"
  53. % (",".join("?" for _ in chunk),)
  54. ),
  55. [as_id] + chunk,
  56. )