You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

520 lines
18 KiB

  1. # Copyright 2020 Dirk Klimpel
  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 json
  15. from binascii import unhexlify
  16. from typing import Any, Dict, List, Optional
  17. import synapse.rest.admin
  18. from synapse.api.errors import Codes
  19. from synapse.rest.client import login
  20. from tests import unittest
  21. class UserMediaStatisticsTestCase(unittest.HomeserverTestCase):
  22. servlets = [
  23. synapse.rest.admin.register_servlets,
  24. login.register_servlets,
  25. ]
  26. def prepare(self, reactor, clock, hs):
  27. self.media_repo = hs.get_media_repository_resource()
  28. self.admin_user = self.register_user("admin", "pass", admin=True)
  29. self.admin_user_tok = self.login("admin", "pass")
  30. self.other_user = self.register_user("user", "pass")
  31. self.other_user_tok = self.login("user", "pass")
  32. self.url = "/_synapse/admin/v1/statistics/users/media"
  33. def test_no_auth(self):
  34. """
  35. Try to list users without authentication.
  36. """
  37. channel = self.make_request("GET", self.url, b"{}")
  38. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  39. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  40. def test_requester_is_no_admin(self):
  41. """
  42. If the user is not a server admin, an error 403 is returned.
  43. """
  44. channel = self.make_request(
  45. "GET",
  46. self.url,
  47. json.dumps({}),
  48. access_token=self.other_user_tok,
  49. )
  50. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  51. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  52. def test_invalid_parameter(self):
  53. """
  54. If parameters are invalid, an error is returned.
  55. """
  56. # unkown order_by
  57. channel = self.make_request(
  58. "GET",
  59. self.url + "?order_by=bar",
  60. access_token=self.admin_user_tok,
  61. )
  62. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  63. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  64. # negative from
  65. channel = self.make_request(
  66. "GET",
  67. self.url + "?from=-5",
  68. access_token=self.admin_user_tok,
  69. )
  70. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  71. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  72. # negative limit
  73. channel = self.make_request(
  74. "GET",
  75. self.url + "?limit=-5",
  76. access_token=self.admin_user_tok,
  77. )
  78. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  79. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  80. # negative from_ts
  81. channel = self.make_request(
  82. "GET",
  83. self.url + "?from_ts=-1234",
  84. access_token=self.admin_user_tok,
  85. )
  86. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  87. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  88. # negative until_ts
  89. channel = self.make_request(
  90. "GET",
  91. self.url + "?until_ts=-1234",
  92. access_token=self.admin_user_tok,
  93. )
  94. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  95. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  96. # until_ts smaller from_ts
  97. channel = self.make_request(
  98. "GET",
  99. self.url + "?from_ts=10&until_ts=5",
  100. access_token=self.admin_user_tok,
  101. )
  102. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  103. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  104. # empty search term
  105. channel = self.make_request(
  106. "GET",
  107. self.url + "?search_term=",
  108. access_token=self.admin_user_tok,
  109. )
  110. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  111. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  112. # invalid search order
  113. channel = self.make_request(
  114. "GET",
  115. self.url + "?dir=bar",
  116. access_token=self.admin_user_tok,
  117. )
  118. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  119. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  120. def test_limit(self):
  121. """
  122. Testing list of media with limit
  123. """
  124. self._create_users_with_media(10, 2)
  125. channel = self.make_request(
  126. "GET",
  127. self.url + "?limit=5",
  128. access_token=self.admin_user_tok,
  129. )
  130. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  131. self.assertEqual(channel.json_body["total"], 10)
  132. self.assertEqual(len(channel.json_body["users"]), 5)
  133. self.assertEqual(channel.json_body["next_token"], 5)
  134. self._check_fields(channel.json_body["users"])
  135. def test_from(self):
  136. """
  137. Testing list of media with a defined starting point (from)
  138. """
  139. self._create_users_with_media(20, 2)
  140. channel = self.make_request(
  141. "GET",
  142. self.url + "?from=5",
  143. access_token=self.admin_user_tok,
  144. )
  145. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  146. self.assertEqual(channel.json_body["total"], 20)
  147. self.assertEqual(len(channel.json_body["users"]), 15)
  148. self.assertNotIn("next_token", channel.json_body)
  149. self._check_fields(channel.json_body["users"])
  150. def test_limit_and_from(self):
  151. """
  152. Testing list of media with a defined starting point and limit
  153. """
  154. self._create_users_with_media(20, 2)
  155. channel = self.make_request(
  156. "GET",
  157. self.url + "?from=5&limit=10",
  158. access_token=self.admin_user_tok,
  159. )
  160. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  161. self.assertEqual(channel.json_body["total"], 20)
  162. self.assertEqual(channel.json_body["next_token"], 15)
  163. self.assertEqual(len(channel.json_body["users"]), 10)
  164. self._check_fields(channel.json_body["users"])
  165. def test_next_token(self):
  166. """
  167. Testing that `next_token` appears at the right place
  168. """
  169. number_users = 20
  170. self._create_users_with_media(number_users, 3)
  171. # `next_token` does not appear
  172. # Number of results is the number of entries
  173. channel = self.make_request(
  174. "GET",
  175. self.url + "?limit=20",
  176. access_token=self.admin_user_tok,
  177. )
  178. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  179. self.assertEqual(channel.json_body["total"], number_users)
  180. self.assertEqual(len(channel.json_body["users"]), number_users)
  181. self.assertNotIn("next_token", channel.json_body)
  182. # `next_token` does not appear
  183. # Number of max results is larger than the number of entries
  184. channel = self.make_request(
  185. "GET",
  186. self.url + "?limit=21",
  187. access_token=self.admin_user_tok,
  188. )
  189. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  190. self.assertEqual(channel.json_body["total"], number_users)
  191. self.assertEqual(len(channel.json_body["users"]), number_users)
  192. self.assertNotIn("next_token", channel.json_body)
  193. # `next_token` does appear
  194. # Number of max results is smaller than the number of entries
  195. channel = self.make_request(
  196. "GET",
  197. self.url + "?limit=19",
  198. access_token=self.admin_user_tok,
  199. )
  200. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  201. self.assertEqual(channel.json_body["total"], number_users)
  202. self.assertEqual(len(channel.json_body["users"]), 19)
  203. self.assertEqual(channel.json_body["next_token"], 19)
  204. # Set `from` to value of `next_token` for request remaining entries
  205. # Check `next_token` does not appear
  206. channel = self.make_request(
  207. "GET",
  208. self.url + "?from=19",
  209. access_token=self.admin_user_tok,
  210. )
  211. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  212. self.assertEqual(channel.json_body["total"], number_users)
  213. self.assertEqual(len(channel.json_body["users"]), 1)
  214. self.assertNotIn("next_token", channel.json_body)
  215. def test_no_media(self):
  216. """
  217. Tests that a normal lookup for statistics is successfully
  218. if users have no media created
  219. """
  220. channel = self.make_request(
  221. "GET",
  222. self.url,
  223. access_token=self.admin_user_tok,
  224. )
  225. self.assertEqual(200, channel.code, msg=channel.json_body)
  226. self.assertEqual(0, channel.json_body["total"])
  227. self.assertEqual(0, len(channel.json_body["users"]))
  228. def test_order_by(self):
  229. """
  230. Testing order list with parameter `order_by`
  231. """
  232. # create users
  233. self.register_user("user_a", "pass", displayname="UserZ")
  234. userA_tok = self.login("user_a", "pass")
  235. self._create_media(userA_tok, 1)
  236. self.register_user("user_b", "pass", displayname="UserY")
  237. userB_tok = self.login("user_b", "pass")
  238. self._create_media(userB_tok, 3)
  239. self.register_user("user_c", "pass", displayname="UserX")
  240. userC_tok = self.login("user_c", "pass")
  241. self._create_media(userC_tok, 2)
  242. # order by user_id
  243. self._order_test("user_id", ["@user_a:test", "@user_b:test", "@user_c:test"])
  244. self._order_test(
  245. "user_id",
  246. ["@user_a:test", "@user_b:test", "@user_c:test"],
  247. "f",
  248. )
  249. self._order_test(
  250. "user_id",
  251. ["@user_c:test", "@user_b:test", "@user_a:test"],
  252. "b",
  253. )
  254. # order by displayname
  255. self._order_test(
  256. "displayname", ["@user_c:test", "@user_b:test", "@user_a:test"]
  257. )
  258. self._order_test(
  259. "displayname",
  260. ["@user_c:test", "@user_b:test", "@user_a:test"],
  261. "f",
  262. )
  263. self._order_test(
  264. "displayname",
  265. ["@user_a:test", "@user_b:test", "@user_c:test"],
  266. "b",
  267. )
  268. # order by media_length
  269. self._order_test(
  270. "media_length",
  271. ["@user_a:test", "@user_c:test", "@user_b:test"],
  272. )
  273. self._order_test(
  274. "media_length",
  275. ["@user_a:test", "@user_c:test", "@user_b:test"],
  276. "f",
  277. )
  278. self._order_test(
  279. "media_length",
  280. ["@user_b:test", "@user_c:test", "@user_a:test"],
  281. "b",
  282. )
  283. # order by media_count
  284. self._order_test(
  285. "media_count",
  286. ["@user_a:test", "@user_c:test", "@user_b:test"],
  287. )
  288. self._order_test(
  289. "media_count",
  290. ["@user_a:test", "@user_c:test", "@user_b:test"],
  291. "f",
  292. )
  293. self._order_test(
  294. "media_count",
  295. ["@user_b:test", "@user_c:test", "@user_a:test"],
  296. "b",
  297. )
  298. def test_from_until_ts(self):
  299. """
  300. Testing filter by time with parameters `from_ts` and `until_ts`
  301. """
  302. # create media earlier than `ts1` to ensure that `from_ts` is working
  303. self._create_media(self.other_user_tok, 3)
  304. self.pump(1)
  305. ts1 = self.clock.time_msec()
  306. # list all media when filter is not set
  307. channel = self.make_request(
  308. "GET",
  309. self.url,
  310. access_token=self.admin_user_tok,
  311. )
  312. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  313. self.assertEqual(channel.json_body["users"][0]["media_count"], 3)
  314. # filter media starting at `ts1` after creating first media
  315. # result is 0
  316. channel = self.make_request(
  317. "GET",
  318. self.url + "?from_ts=%s" % (ts1,),
  319. access_token=self.admin_user_tok,
  320. )
  321. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  322. self.assertEqual(channel.json_body["total"], 0)
  323. self._create_media(self.other_user_tok, 3)
  324. self.pump(1)
  325. ts2 = self.clock.time_msec()
  326. # create media after `ts2` to ensure that `until_ts` is working
  327. self._create_media(self.other_user_tok, 3)
  328. # filter media between `ts1` and `ts2`
  329. channel = self.make_request(
  330. "GET",
  331. self.url + "?from_ts=%s&until_ts=%s" % (ts1, ts2),
  332. access_token=self.admin_user_tok,
  333. )
  334. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  335. self.assertEqual(channel.json_body["users"][0]["media_count"], 3)
  336. # filter media until `ts2` and earlier
  337. channel = self.make_request(
  338. "GET",
  339. self.url + "?until_ts=%s" % (ts2,),
  340. access_token=self.admin_user_tok,
  341. )
  342. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  343. self.assertEqual(channel.json_body["users"][0]["media_count"], 6)
  344. def test_search_term(self):
  345. self._create_users_with_media(20, 1)
  346. # check without filter get all users
  347. channel = self.make_request(
  348. "GET",
  349. self.url,
  350. access_token=self.admin_user_tok,
  351. )
  352. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  353. self.assertEqual(channel.json_body["total"], 20)
  354. # filter user 1 and 10-19 by `user_id`
  355. channel = self.make_request(
  356. "GET",
  357. self.url + "?search_term=foo_user_1",
  358. access_token=self.admin_user_tok,
  359. )
  360. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  361. self.assertEqual(channel.json_body["total"], 11)
  362. # filter on this user in `displayname`
  363. channel = self.make_request(
  364. "GET",
  365. self.url + "?search_term=bar_user_10",
  366. access_token=self.admin_user_tok,
  367. )
  368. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  369. self.assertEqual(channel.json_body["users"][0]["displayname"], "bar_user_10")
  370. self.assertEqual(channel.json_body["total"], 1)
  371. # filter and get empty result
  372. channel = self.make_request(
  373. "GET",
  374. self.url + "?search_term=foobar",
  375. access_token=self.admin_user_tok,
  376. )
  377. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  378. self.assertEqual(channel.json_body["total"], 0)
  379. def _create_users_with_media(self, number_users: int, media_per_user: int):
  380. """
  381. Create a number of users with a number of media
  382. Args:
  383. number_users: Number of users to be created
  384. media_per_user: Number of media to be created for each user
  385. """
  386. for i in range(number_users):
  387. self.register_user("foo_user_%s" % i, "pass", displayname="bar_user_%s" % i)
  388. user_tok = self.login("foo_user_%s" % i, "pass")
  389. self._create_media(user_tok, media_per_user)
  390. def _create_media(self, user_token: str, number_media: int):
  391. """
  392. Create a number of media for a specific user
  393. Args:
  394. user_token: Access token of the user
  395. number_media: Number of media to be created for the user
  396. """
  397. upload_resource = self.media_repo.children[b"upload"]
  398. for _ in range(number_media):
  399. # file size is 67 Byte
  400. image_data = unhexlify(
  401. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  402. b"0000001f15c4890000000a49444154789c63000100000500010d"
  403. b"0a2db40000000049454e44ae426082"
  404. )
  405. # Upload some media into the room
  406. self.helper.upload_media(
  407. upload_resource, image_data, tok=user_token, expect_code=200
  408. )
  409. def _check_fields(self, content: List[Dict[str, Any]]):
  410. """Checks that all attributes are present in content
  411. Args:
  412. content: List that is checked for content
  413. """
  414. for c in content:
  415. self.assertIn("user_id", c)
  416. self.assertIn("displayname", c)
  417. self.assertIn("media_count", c)
  418. self.assertIn("media_length", c)
  419. def _order_test(
  420. self, order_type: str, expected_user_list: List[str], dir: Optional[str] = None
  421. ):
  422. """Request the list of users in a certain order. Assert that order is what
  423. we expect
  424. Args:
  425. order_type: The type of ordering to give the server
  426. expected_user_list: The list of user_ids in the order we expect to get
  427. back from the server
  428. dir: The direction of ordering to give the server
  429. """
  430. url = self.url + "?order_by=%s" % (order_type,)
  431. if dir is not None and dir in ("b", "f"):
  432. url += "&dir=%s" % (dir,)
  433. channel = self.make_request(
  434. "GET",
  435. url.encode("ascii"),
  436. access_token=self.admin_user_tok,
  437. )
  438. self.assertEqual(200, channel.code, msg=channel.json_body)
  439. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  440. returned_order = [row["user_id"] for row in channel.json_body["users"]]
  441. self.assertListEqual(expected_user_list, returned_order)
  442. self._check_fields(channel.json_body["users"])