Coverage for src/couchers/servicers/api.py: 97%

364 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-11-04 02:51 +0000

1from datetime import timedelta 

2from urllib.parse import urlencode 

3 

4import grpc 

5from google.protobuf import empty_pb2 

6from sqlalchemy.orm import aliased 

7from sqlalchemy.sql import and_, delete, func, intersect, or_, union 

8 

9from couchers import errors, urls 

10from couchers.config import config 

11from couchers.crypto import b64encode, generate_hash_signature, random_hex 

12from couchers.materialized_views import lite_users 

13from couchers.models import ( 

14 FriendRelationship, 

15 FriendStatus, 

16 GroupChatSubscription, 

17 HostingStatus, 

18 HostRequest, 

19 InitiatedUpload, 

20 LanguageAbility, 

21 LanguageFluency, 

22 MeetupStatus, 

23 Message, 

24 ParkingDetails, 

25 Reference, 

26 RegionLived, 

27 RegionVisited, 

28 SleepingArrangement, 

29 SmokingLocation, 

30 User, 

31) 

32from couchers.notifications.notify import notify 

33from couchers.resources import language_is_allowed, region_is_allowed 

34from couchers.servicers.account import get_strong_verification_fields 

35from couchers.sql import couchers_select as select 

36from couchers.sql import is_valid_user_id, is_valid_username 

37from couchers.utils import ( 

38 Timestamp_from_datetime, 

39 create_coordinate, 

40 get_coordinates, 

41 is_valid_name, 

42 now, 

43) 

44from proto import api_pb2, api_pb2_grpc, media_pb2, notification_data_pb2 

45 

46MAX_USERS_PER_QUERY = 200 

47 

48hostingstatus2sql = { 

49 api_pb2.HOSTING_STATUS_UNKNOWN: None, 

50 api_pb2.HOSTING_STATUS_CAN_HOST: HostingStatus.can_host, 

51 api_pb2.HOSTING_STATUS_MAYBE: HostingStatus.maybe, 

52 api_pb2.HOSTING_STATUS_CANT_HOST: HostingStatus.cant_host, 

53} 

54 

55hostingstatus2api = { 

56 None: api_pb2.HOSTING_STATUS_UNKNOWN, 

57 HostingStatus.can_host: api_pb2.HOSTING_STATUS_CAN_HOST, 

58 HostingStatus.maybe: api_pb2.HOSTING_STATUS_MAYBE, 

59 HostingStatus.cant_host: api_pb2.HOSTING_STATUS_CANT_HOST, 

60} 

61 

62meetupstatus2sql = { 

63 api_pb2.MEETUP_STATUS_UNKNOWN: None, 

64 api_pb2.MEETUP_STATUS_WANTS_TO_MEETUP: MeetupStatus.wants_to_meetup, 

65 api_pb2.MEETUP_STATUS_OPEN_TO_MEETUP: MeetupStatus.open_to_meetup, 

66 api_pb2.MEETUP_STATUS_DOES_NOT_WANT_TO_MEETUP: MeetupStatus.does_not_want_to_meetup, 

67} 

68 

69meetupstatus2api = { 

70 None: api_pb2.MEETUP_STATUS_UNKNOWN, 

71 MeetupStatus.wants_to_meetup: api_pb2.MEETUP_STATUS_WANTS_TO_MEETUP, 

72 MeetupStatus.open_to_meetup: api_pb2.MEETUP_STATUS_OPEN_TO_MEETUP, 

73 MeetupStatus.does_not_want_to_meetup: api_pb2.MEETUP_STATUS_DOES_NOT_WANT_TO_MEETUP, 

74} 

75 

76smokinglocation2sql = { 

77 api_pb2.SMOKING_LOCATION_UNKNOWN: None, 

78 api_pb2.SMOKING_LOCATION_YES: SmokingLocation.yes, 

79 api_pb2.SMOKING_LOCATION_WINDOW: SmokingLocation.window, 

80 api_pb2.SMOKING_LOCATION_OUTSIDE: SmokingLocation.outside, 

81 api_pb2.SMOKING_LOCATION_NO: SmokingLocation.no, 

82} 

83 

84smokinglocation2api = { 

85 None: api_pb2.SMOKING_LOCATION_UNKNOWN, 

86 SmokingLocation.yes: api_pb2.SMOKING_LOCATION_YES, 

87 SmokingLocation.window: api_pb2.SMOKING_LOCATION_WINDOW, 

88 SmokingLocation.outside: api_pb2.SMOKING_LOCATION_OUTSIDE, 

89 SmokingLocation.no: api_pb2.SMOKING_LOCATION_NO, 

90} 

91 

92sleepingarrangement2sql = { 

93 api_pb2.SLEEPING_ARRANGEMENT_UNKNOWN: None, 

94 api_pb2.SLEEPING_ARRANGEMENT_PRIVATE: SleepingArrangement.private, 

95 api_pb2.SLEEPING_ARRANGEMENT_COMMON: SleepingArrangement.common, 

96 api_pb2.SLEEPING_ARRANGEMENT_SHARED_ROOM: SleepingArrangement.shared_room, 

97 api_pb2.SLEEPING_ARRANGEMENT_SHARED_SPACE: SleepingArrangement.shared_space, 

98} 

99 

100sleepingarrangement2api = { 

101 None: api_pb2.SLEEPING_ARRANGEMENT_UNKNOWN, 

102 SleepingArrangement.private: api_pb2.SLEEPING_ARRANGEMENT_PRIVATE, 

103 SleepingArrangement.common: api_pb2.SLEEPING_ARRANGEMENT_COMMON, 

104 SleepingArrangement.shared_room: api_pb2.SLEEPING_ARRANGEMENT_SHARED_ROOM, 

105 SleepingArrangement.shared_space: api_pb2.SLEEPING_ARRANGEMENT_SHARED_SPACE, 

106} 

107 

108parkingdetails2sql = { 

109 api_pb2.PARKING_DETAILS_UNKNOWN: None, 

110 api_pb2.PARKING_DETAILS_FREE_ONSITE: ParkingDetails.free_onsite, 

111 api_pb2.PARKING_DETAILS_FREE_OFFSITE: ParkingDetails.free_offsite, 

112 api_pb2.PARKING_DETAILS_PAID_ONSITE: ParkingDetails.paid_onsite, 

113 api_pb2.PARKING_DETAILS_PAID_OFFSITE: ParkingDetails.paid_offsite, 

114} 

115 

116parkingdetails2api = { 

117 None: api_pb2.PARKING_DETAILS_UNKNOWN, 

118 ParkingDetails.free_onsite: api_pb2.PARKING_DETAILS_FREE_ONSITE, 

119 ParkingDetails.free_offsite: api_pb2.PARKING_DETAILS_FREE_OFFSITE, 

120 ParkingDetails.paid_onsite: api_pb2.PARKING_DETAILS_PAID_ONSITE, 

121 ParkingDetails.paid_offsite: api_pb2.PARKING_DETAILS_PAID_OFFSITE, 

122} 

123 

124fluency2sql = { 

125 api_pb2.LanguageAbility.Fluency.FLUENCY_UNKNOWN: None, 

126 api_pb2.LanguageAbility.Fluency.FLUENCY_BEGINNER: LanguageFluency.beginner, 

127 api_pb2.LanguageAbility.Fluency.FLUENCY_CONVERSATIONAL: LanguageFluency.conversational, 

128 api_pb2.LanguageAbility.Fluency.FLUENCY_FLUENT: LanguageFluency.fluent, 

129} 

130 

131fluency2api = { 

132 None: api_pb2.LanguageAbility.Fluency.FLUENCY_UNKNOWN, 

133 LanguageFluency.beginner: api_pb2.LanguageAbility.Fluency.FLUENCY_BEGINNER, 

134 LanguageFluency.conversational: api_pb2.LanguageAbility.Fluency.FLUENCY_CONVERSATIONAL, 

135 LanguageFluency.fluent: api_pb2.LanguageAbility.Fluency.FLUENCY_FLUENT, 

136} 

137 

138 

139class API(api_pb2_grpc.APIServicer): 

140 def Ping(self, request, context, session): 

141 # auth ought to make sure the user exists 

142 user = session.execute(select(User).where(User.id == context.user_id)).scalar_one() 

143 

144 # gets only the max message by self-joining messages which have a greater id 

145 # if it doesn't have a greater id, it's the biggest 

146 message_2 = aliased(Message) 

147 unseen_sent_host_request_count = session.execute( 

148 select(func.count()) 

149 .select_from(Message) 

150 .join(HostRequest, Message.conversation_id == HostRequest.conversation_id) 

151 .outerjoin(message_2, and_(Message.conversation_id == message_2.conversation_id, Message.id < message_2.id)) 

152 .where(HostRequest.surfer_user_id == context.user_id) 

153 .where_users_column_visible(context, HostRequest.host_user_id) 

154 .where(message_2.id == None) 

155 .where(HostRequest.surfer_last_seen_message_id < Message.id) 

156 ).scalar_one() 

157 

158 unseen_received_host_request_count = session.execute( 

159 select(func.count()) 

160 .select_from(Message) 

161 .join(HostRequest, Message.conversation_id == HostRequest.conversation_id) 

162 .outerjoin(message_2, and_(Message.conversation_id == message_2.conversation_id, Message.id < message_2.id)) 

163 .where_users_column_visible(context, HostRequest.surfer_user_id) 

164 .where(HostRequest.host_user_id == context.user_id) 

165 .where(message_2.id == None) 

166 .where(HostRequest.host_last_seen_message_id < Message.id) 

167 ).scalar_one() 

168 

169 unseen_message_count = session.execute( 

170 select(func.count()) 

171 .select_from(Message) 

172 .outerjoin(GroupChatSubscription, GroupChatSubscription.group_chat_id == Message.conversation_id) 

173 .where(GroupChatSubscription.user_id == context.user_id) 

174 .where(Message.time >= GroupChatSubscription.joined) 

175 .where(or_(Message.time <= GroupChatSubscription.left, GroupChatSubscription.left == None)) 

176 .where(Message.id > GroupChatSubscription.last_seen_message_id) 

177 ).scalar_one() 

178 

179 pending_friend_request_count = session.execute( 

180 select(func.count()) 

181 .select_from(FriendRelationship) 

182 .where(FriendRelationship.to_user_id == context.user_id) 

183 .where_users_column_visible(context, FriendRelationship.from_user_id) 

184 .where(FriendRelationship.status == FriendStatus.pending) 

185 ).scalar_one() 

186 

187 return api_pb2.PingRes( 

188 user=user_model_to_pb(user, session, context), 

189 unseen_message_count=unseen_message_count, 

190 unseen_sent_host_request_count=unseen_sent_host_request_count, 

191 unseen_received_host_request_count=unseen_received_host_request_count, 

192 pending_friend_request_count=pending_friend_request_count, 

193 ) 

194 

195 def GetUser(self, request, context, session): 

196 user = session.execute( 

197 select(User).where_users_visible(context).where_username_or_id(request.user) 

198 ).scalar_one_or_none() 

199 

200 if not user: 

201 context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND) 

202 

203 return user_model_to_pb(user, session, context) 

204 

205 def GetLiteUser(self, request, context, session): 

206 lite_user = session.execute( 

207 select(lite_users) 

208 .where_users_visible(context, table=lite_users.c) 

209 .where_username_or_id(request.user, table=lite_users.c) 

210 ).one_or_none() 

211 

212 if not lite_user: 

213 context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND) 

214 

215 return lite_user_to_pb(lite_user) 

216 

217 def GetLiteUsers(self, request, context, session): 

218 if len(request.users) > MAX_USERS_PER_QUERY: 

219 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.REQUESTED_TOO_MANY_USERS) 

220 

221 usernames = {u for u in request.users if is_valid_username(u)} 

222 ids = {u for u in request.users if is_valid_user_id(u)} 

223 

224 users = session.execute( 

225 select(lite_users) 

226 .where_users_visible(context, table=lite_users.c) 

227 .where(or_(lite_users.c.username.in_(usernames), lite_users.c.id.in_(ids))) 

228 ).all() 

229 

230 users_by_id = {str(user.id): user for user in users} 

231 users_by_username = {user.username: user for user in users} 

232 

233 res = api_pb2.GetLiteUsersRes() 

234 

235 for user in request.users: 

236 lite_user = None 

237 if user in users_by_id: 

238 lite_user = users_by_id[user] 

239 elif user in users_by_username: 

240 lite_user = users_by_username[user] 

241 

242 res.responses.append( 

243 api_pb2.LiteUserRes( 

244 query=user, 

245 not_found=lite_user is None, 

246 user=lite_user_to_pb(lite_user) if lite_user else None, 

247 ) 

248 ) 

249 

250 return res 

251 

252 def UpdateProfile(self, request, context, session): 

253 user = session.execute(select(User).where(User.id == context.user_id)).scalar_one() 

254 

255 if request.HasField("name"): 

256 if not is_valid_name(request.name.value): 

257 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_NAME) 

258 user.name = request.name.value 

259 

260 if request.HasField("city"): 

261 user.city = request.city.value 

262 

263 if request.HasField("hometown"): 

264 if request.hometown.is_null: 

265 user.hometown = None 

266 else: 

267 user.hometown = request.hometown.value 

268 

269 if request.HasField("lat") and request.HasField("lng"): 

270 if request.lat.value == 0 and request.lng.value == 0: 

271 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_COORDINATE) 

272 user.geom = create_coordinate(request.lat.value, request.lng.value) 

273 

274 if request.HasField("radius"): 

275 user.geom_radius = request.radius.value 

276 

277 if request.HasField("avatar_key"): 

278 if request.avatar_key.is_null: 

279 user.avatar_key = None 

280 else: 

281 user.avatar_key = request.avatar_key.value 

282 

283 # if request.HasField("gender"): 

284 # user.gender = request.gender.value 

285 

286 if request.HasField("pronouns"): 

287 if request.pronouns.is_null: 

288 user.pronouns = None 

289 else: 

290 user.pronouns = request.pronouns.value 

291 

292 if request.HasField("occupation"): 

293 if request.occupation.is_null: 

294 user.occupation = None 

295 else: 

296 user.occupation = request.occupation.value 

297 

298 if request.HasField("education"): 

299 if request.education.is_null: 

300 user.education = None 

301 else: 

302 user.education = request.education.value 

303 

304 if request.HasField("about_me"): 

305 if request.about_me.is_null: 

306 user.about_me = None 

307 else: 

308 user.about_me = request.about_me.value 

309 

310 if request.HasField("my_travels"): 

311 if request.my_travels.is_null: 

312 user.my_travels = None 

313 else: 

314 user.my_travels = request.my_travels.value 

315 

316 if request.HasField("things_i_like"): 

317 if request.things_i_like.is_null: 

318 user.things_i_like = None 

319 else: 

320 user.things_i_like = request.things_i_like.value 

321 

322 if request.HasField("about_place"): 

323 if request.about_place.is_null: 

324 user.about_place = None 

325 else: 

326 user.about_place = request.about_place.value 

327 

328 if request.hosting_status != api_pb2.HOSTING_STATUS_UNSPECIFIED: 

329 if user.do_not_email and request.hosting_status != api_pb2.HOSTING_STATUS_CANT_HOST: 

330 context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.DO_NOT_EMAIL_CANNOT_HOST) 

331 user.hosting_status = hostingstatus2sql[request.hosting_status] 

332 

333 if request.meetup_status != api_pb2.MEETUP_STATUS_UNSPECIFIED: 

334 if user.do_not_email and request.meetup_status != api_pb2.MEETUP_STATUS_DOES_NOT_WANT_TO_MEETUP: 

335 context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.DO_NOT_EMAIL_CANNOT_MEET) 

336 user.meetup_status = meetupstatus2sql[request.meetup_status] 

337 

338 if request.HasField("language_abilities"): 

339 # delete all existing abilities 

340 for ability in user.language_abilities: 

341 session.delete(ability) 

342 session.flush() 

343 

344 # add the new ones 

345 for language_ability in request.language_abilities.value: 

346 if not language_is_allowed(language_ability.code): 

347 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_LANGUAGE) 

348 session.add( 

349 LanguageAbility( 

350 user=user, 

351 language_code=language_ability.code, 

352 fluency=fluency2sql[language_ability.fluency], 

353 ) 

354 ) 

355 

356 if request.HasField("regions_visited"): 

357 session.execute(delete(RegionVisited).where(RegionVisited.user_id == context.user_id)) 

358 

359 for region in request.regions_visited.value: 

360 if not region_is_allowed(region): 

361 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_REGION) 

362 session.add( 

363 RegionVisited( 

364 user_id=user.id, 

365 region_code=region, 

366 ) 

367 ) 

368 

369 if request.HasField("regions_lived"): 

370 session.execute(delete(RegionLived).where(RegionLived.user_id == context.user_id)) 

371 

372 for region in request.regions_lived.value: 

373 if not region_is_allowed(region): 

374 context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_REGION) 

375 session.add( 

376 RegionLived( 

377 user_id=user.id, 

378 region_code=region, 

379 ) 

380 ) 

381 

382 if request.HasField("additional_information"): 

383 if request.additional_information.is_null: 

384 user.additional_information = None 

385 else: 

386 user.additional_information = request.additional_information.value 

387 

388 if request.HasField("max_guests"): 

389 if request.max_guests.is_null: 

390 user.max_guests = None 

391 else: 

392 user.max_guests = request.max_guests.value 

393 

394 if request.HasField("last_minute"): 

395 if request.last_minute.is_null: 

396 user.last_minute = None 

397 else: 

398 user.last_minute = request.last_minute.value 

399 

400 if request.HasField("has_pets"): 

401 if request.has_pets.is_null: 

402 user.has_pets = None 

403 else: 

404 user.has_pets = request.has_pets.value 

405 

406 if request.HasField("accepts_pets"): 

407 if request.accepts_pets.is_null: 

408 user.accepts_pets = None 

409 else: 

410 user.accepts_pets = request.accepts_pets.value 

411 

412 if request.HasField("pet_details"): 

413 if request.pet_details.is_null: 

414 user.pet_details = None 

415 else: 

416 user.pet_details = request.pet_details.value 

417 

418 if request.HasField("has_kids"): 

419 if request.has_kids.is_null: 

420 user.has_kids = None 

421 else: 

422 user.has_kids = request.has_kids.value 

423 

424 if request.HasField("accepts_kids"): 

425 if request.accepts_kids.is_null: 

426 user.accepts_kids = None 

427 else: 

428 user.accepts_kids = request.accepts_kids.value 

429 

430 if request.HasField("kid_details"): 

431 if request.kid_details.is_null: 

432 user.kid_details = None 

433 else: 

434 user.kid_details = request.kid_details.value 

435 

436 if request.HasField("has_housemates"): 

437 if request.has_housemates.is_null: 

438 user.has_housemates = None 

439 else: 

440 user.has_housemates = request.has_housemates.value 

441 

442 if request.HasField("housemate_details"): 

443 if request.housemate_details.is_null: 

444 user.housemate_details = None 

445 else: 

446 user.housemate_details = request.housemate_details.value 

447 

448 if request.HasField("wheelchair_accessible"): 

449 if request.wheelchair_accessible.is_null: 

450 user.wheelchair_accessible = None 

451 else: 

452 user.wheelchair_accessible = request.wheelchair_accessible.value 

453 

454 if request.smoking_allowed != api_pb2.SMOKING_LOCATION_UNSPECIFIED: 

455 user.smoking_allowed = smokinglocation2sql[request.smoking_allowed] 

456 

457 if request.HasField("smokes_at_home"): 

458 if request.smokes_at_home.is_null: 

459 user.smokes_at_home = None 

460 else: 

461 user.smokes_at_home = request.smokes_at_home.value 

462 

463 if request.HasField("drinking_allowed"): 

464 if request.drinking_allowed.is_null: 

465 user.drinking_allowed = None 

466 else: 

467 user.drinking_allowed = request.drinking_allowed.value 

468 

469 if request.HasField("drinks_at_home"): 

470 if request.drinks_at_home.is_null: 

471 user.drinks_at_home = None 

472 else: 

473 user.drinks_at_home = request.drinks_at_home.value 

474 

475 if request.HasField("other_host_info"): 

476 if request.other_host_info.is_null: 

477 user.other_host_info = None 

478 else: 

479 user.other_host_info = request.other_host_info.value 

480 

481 if request.sleeping_arrangement != api_pb2.SLEEPING_ARRANGEMENT_UNSPECIFIED: 

482 user.sleeping_arrangement = sleepingarrangement2sql[request.sleeping_arrangement] 

483 

484 if request.HasField("sleeping_details"): 

485 if request.sleeping_details.is_null: 

486 user.sleeping_details = None 

487 else: 

488 user.sleeping_details = request.sleeping_details.value 

489 

490 if request.HasField("area"): 

491 if request.area.is_null: 

492 user.area = None 

493 else: 

494 user.area = request.area.value 

495 

496 if request.HasField("house_rules"): 

497 if request.house_rules.is_null: 

498 user.house_rules = None 

499 else: 

500 user.house_rules = request.house_rules.value 

501 

502 if request.HasField("parking"): 

503 if request.parking.is_null: 

504 user.parking = None 

505 else: 

506 user.parking = request.parking.value 

507 

508 if request.parking_details != api_pb2.PARKING_DETAILS_UNSPECIFIED: 

509 user.parking_details = parkingdetails2sql[request.parking_details] 

510 

511 if request.HasField("camping_ok"): 

512 if request.camping_ok.is_null: 

513 user.camping_ok = None 

514 else: 

515 user.camping_ok = request.camping_ok.value 

516 

517 # save updates 

518 session.commit() 

519 

520 return empty_pb2.Empty() 

521 

522 def ListFriends(self, request, context, session): 

523 rels = ( 

524 session.execute( 

525 select(FriendRelationship) 

526 .where_users_column_visible(context, FriendRelationship.from_user_id) 

527 .where_users_column_visible(context, FriendRelationship.to_user_id) 

528 .where( 

529 or_( 

530 FriendRelationship.from_user_id == context.user_id, 

531 FriendRelationship.to_user_id == context.user_id, 

532 ) 

533 ) 

534 .where(FriendRelationship.status == FriendStatus.accepted) 

535 ) 

536 .scalars() 

537 .all() 

538 ) 

539 return api_pb2.ListFriendsRes( 

540 user_ids=[rel.from_user.id if rel.from_user.id != context.user_id else rel.to_user.id for rel in rels], 

541 ) 

542 

543 def ListMutualFriends(self, request, context, session): 

544 if context.user_id == request.user_id: 

545 return api_pb2.ListMutualFriendsRes(mutual_friends=[]) 

546 

547 user = session.execute( 

548 select(User).where_users_visible(context).where(User.id == request.user_id) 

549 ).scalar_one_or_none() 

550 

551 if not user: 

552 context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND) 

553 

554 q1 = ( 

555 select(FriendRelationship.from_user_id.label("user_id")) 

556 .where(FriendRelationship.to_user_id == context.user_id) 

557 .where(FriendRelationship.from_user_id != request.user_id) 

558 .where(FriendRelationship.status == FriendStatus.accepted) 

559 ) 

560 

561 q2 = ( 

562 select(FriendRelationship.to_user_id.label("user_id")) 

563 .where(FriendRelationship.from_user_id == context.user_id) 

564 .where(FriendRelationship.to_user_id != request.user_id) 

565 .where(FriendRelationship.status == FriendStatus.accepted) 

566 ) 

567 

568 q3 = ( 

569 select(FriendRelationship.from_user_id.label("user_id")) 

570 .where(FriendRelationship.to_user_id == request.user_id) 

571 .where(FriendRelationship.from_user_id != context.user_id) 

572 .where(FriendRelationship.status == FriendStatus.accepted) 

573 ) 

574 

575 q4 = ( 

576 select(FriendRelationship.to_user_id.label("user_id")) 

577 .where(FriendRelationship.from_user_id == request.user_id) 

578 .where(FriendRelationship.to_user_id != context.user_id) 

579 .where(FriendRelationship.status == FriendStatus.accepted) 

580 ) 

581 

582 mutual = select(intersect(union(q1, q2), union(q3, q4)).subquery()) 

583 

584 mutual_friends = ( 

585 session.execute(select(User).where_users_visible(context).where(User.id.in_(mutual))).scalars().all() 

586 ) 

587 

588 return api_pb2.ListMutualFriendsRes( 

589 mutual_friends=[ 

590 api_pb2.MutualFriend(user_id=mutual_friend.id, username=mutual_friend.username, name=mutual_friend.name) 

591 for mutual_friend in mutual_friends 

592 ] 

593 ) 

594 

595 def SendFriendRequest(self, request, context, session): 

596 if context.user_id == request.user_id: 

597 context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.CANT_FRIEND_SELF) 

598 

599 user = session.execute(select(User).where(User.id == context.user_id)).scalar_one() 

600 to_user = session.execute( 

601 select(User).where_users_visible(context).where(User.id == request.user_id) 

602 ).scalar_one_or_none() 

603 

604 if not to_user: 

605 context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND) 

606 

607 if ( 

608 session.execute( 

609 select(FriendRelationship) 

610 .where( 

611 or_( 

612 and_( 

613 FriendRelationship.from_user_id == context.user_id, 

614 FriendRelationship.to_user_id == request.user_id, 

615 ), 

616 and_( 

617 FriendRelationship.from_user_id == request.user_id, 

618 FriendRelationship.to_user_id == context.user_id, 

619 ), 

620 ) 

621 ) 

622 .where( 

623 or_( 

624 FriendRelationship.status == FriendStatus.accepted, 

625 FriendRelationship.status == FriendStatus.pending, 

626 ) 

627 ) 

628 ).scalar_one_or_none() 

629 is not None 

630 ): 

631 context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.FRIENDS_ALREADY_OR_PENDING) 

632 

633 # TODO: Race condition where we can create two friend reqs, needs db constraint! See comment in table 

634 

635 friend_relationship = FriendRelationship(from_user=user, to_user=to_user, status=FriendStatus.pending) 

636 session.add(friend_relationship) 

637 session.flush() 

638 

639 notify( 

640 session, 

641 user_id=friend_relationship.to_user_id, 

642 topic_action="friend_request:create", 

643 key=friend_relationship.from_user_id, 

644 data=notification_data_pb2.FriendRequestCreate( 

645 other_user=user_model_to_pb(friend_relationship.from_user, session, context), 

646 ), 

647 ) 

648 

649 return empty_pb2.Empty() 

650 

651 def ListFriendRequests(self, request, context, session): 

652 # both sent and received 

653 sent_requests = ( 

654 session.execute( 

655 select(FriendRelationship) 

656 .where_users_column_visible(context, FriendRelationship.to_user_id) 

657 .where(FriendRelationship.from_user_id == context.user_id) 

658 .where(FriendRelationship.status == FriendStatus.pending) 

659 ) 

660 .scalars() 

661 .all() 

662 ) 

663 

664 received_requests = ( 

665 session.execute( 

666 select(FriendRelationship) 

667 .where_users_column_visible(context, FriendRelationship.from_user_id) 

668 .where(FriendRelationship.to_user_id == context.user_id) 

669 .where(FriendRelationship.status == FriendStatus.pending) 

670 ) 

671 .scalars() 

672 .all() 

673 ) 

674 

675 return api_pb2.ListFriendRequestsRes( 

676 sent=[ 

677 api_pb2.FriendRequest( 

678 friend_request_id=friend_request.id, 

679 state=api_pb2.FriendRequest.FriendRequestStatus.PENDING, 

680 user_id=friend_request.to_user.id, 

681 sent=True, 

682 ) 

683 for friend_request in sent_requests 

684 ], 

685 received=[ 

686 api_pb2.FriendRequest( 

687 friend_request_id=friend_request.id, 

688 state=api_pb2.FriendRequest.FriendRequestStatus.PENDING, 

689 user_id=friend_request.from_user.id, 

690 sent=False, 

691 ) 

692 for friend_request in received_requests 

693 ], 

694 ) 

695 

696 def RespondFriendRequest(self, request, context, session): 

697 friend_request = session.execute( 

698 select(FriendRelationship) 

699 .where_users_column_visible(context, FriendRelationship.from_user_id) 

700 .where(FriendRelationship.to_user_id == context.user_id) 

701 .where(FriendRelationship.status == FriendStatus.pending) 

702 .where(FriendRelationship.id == request.friend_request_id) 

703 ).scalar_one_or_none() 

704 

705 if not friend_request: 

706 context.abort(grpc.StatusCode.NOT_FOUND, errors.FRIEND_REQUEST_NOT_FOUND) 

707 

708 friend_request.status = FriendStatus.accepted if request.accept else FriendStatus.rejected 

709 friend_request.time_responded = func.now() 

710 

711 session.flush() 

712 

713 if friend_request.status == FriendStatus.accepted: 

714 notify( 

715 session, 

716 user_id=friend_request.from_user_id, 

717 topic_action="friend_request:accept", 

718 key=friend_request.to_user_id, 

719 data=notification_data_pb2.FriendRequestAccept( 

720 other_user=user_model_to_pb(friend_request.to_user, session, context), 

721 ), 

722 ) 

723 

724 return empty_pb2.Empty() 

725 

726 def CancelFriendRequest(self, request, context, session): 

727 friend_request = session.execute( 

728 select(FriendRelationship) 

729 .where_users_column_visible(context, FriendRelationship.to_user_id) 

730 .where(FriendRelationship.from_user_id == context.user_id) 

731 .where(FriendRelationship.status == FriendStatus.pending) 

732 .where(FriendRelationship.id == request.friend_request_id) 

733 ).scalar_one_or_none() 

734 

735 if not friend_request: 

736 context.abort(grpc.StatusCode.NOT_FOUND, errors.FRIEND_REQUEST_NOT_FOUND) 

737 

738 friend_request.status = FriendStatus.cancelled 

739 friend_request.time_responded = func.now() 

740 

741 # note no notifications 

742 

743 session.commit() 

744 

745 return empty_pb2.Empty() 

746 

747 def InitiateMediaUpload(self, request, context, session): 

748 key = random_hex() 

749 

750 created = now() 

751 expiry = created + timedelta(minutes=20) 

752 

753 upload = InitiatedUpload(key=key, created=created, expiry=expiry, initiator_user_id=context.user_id) 

754 session.add(upload) 

755 session.commit() 

756 

757 req = media_pb2.UploadRequest( 

758 key=upload.key, 

759 type=media_pb2.UploadRequest.UploadType.IMAGE, 

760 created=Timestamp_from_datetime(upload.created), 

761 expiry=Timestamp_from_datetime(upload.expiry), 

762 max_width=2000, 

763 max_height=1600, 

764 ).SerializeToString() 

765 

766 data = b64encode(req) 

767 sig = b64encode(generate_hash_signature(req, config["MEDIA_SERVER_SECRET_KEY"])) 

768 

769 path = "upload?" + urlencode({"data": data, "sig": sig}) 

770 

771 return api_pb2.InitiateMediaUploadRes( 

772 upload_url=urls.media_upload_url(path=path), 

773 expiry=Timestamp_from_datetime(expiry), 

774 ) 

775 

776 

777def user_model_to_pb(db_user, session, context): 

778 num_references = session.execute( 

779 select(func.count()) 

780 .select_from(Reference) 

781 .join(User, User.id == Reference.from_user_id) 

782 .where(User.is_visible) 

783 .where(Reference.to_user_id == db_user.id) 

784 ).scalar_one() 

785 

786 # returns (lat, lng) 

787 # we put people without coords on null island 

788 # https://en.wikipedia.org/wiki/Null_Island 

789 lat, lng = db_user.coordinates or (0, 0) 

790 

791 pending_friend_request = None 

792 if db_user.id == context.user_id: 

793 friends_status = api_pb2.User.FriendshipStatus.NA 

794 else: 

795 friend_relationship = session.execute( 

796 select(FriendRelationship) 

797 .where( 

798 or_( 

799 and_( 

800 FriendRelationship.from_user_id == context.user_id, 

801 FriendRelationship.to_user_id == db_user.id, 

802 ), 

803 and_( 

804 FriendRelationship.from_user_id == db_user.id, 

805 FriendRelationship.to_user_id == context.user_id, 

806 ), 

807 ) 

808 ) 

809 .where( 

810 or_( 

811 FriendRelationship.status == FriendStatus.accepted, 

812 FriendRelationship.status == FriendStatus.pending, 

813 ) 

814 ) 

815 ).scalar_one_or_none() 

816 

817 if friend_relationship: 

818 if friend_relationship.status == FriendStatus.accepted: 

819 friends_status = api_pb2.User.FriendshipStatus.FRIENDS 

820 else: 

821 friends_status = api_pb2.User.FriendshipStatus.PENDING 

822 if friend_relationship.from_user_id == context.user_id: 

823 # we sent it 

824 pending_friend_request = api_pb2.FriendRequest( 

825 friend_request_id=friend_relationship.id, 

826 state=api_pb2.FriendRequest.FriendRequestStatus.PENDING, 

827 user_id=friend_relationship.to_user.id, 

828 sent=True, 

829 ) 

830 else: 

831 # we received it 

832 pending_friend_request = api_pb2.FriendRequest( 

833 friend_request_id=friend_relationship.id, 

834 state=api_pb2.FriendRequest.FriendRequestStatus.PENDING, 

835 user_id=friend_relationship.from_user.id, 

836 sent=False, 

837 ) 

838 else: 

839 friends_status = api_pb2.User.FriendshipStatus.NOT_FRIENDS 

840 

841 verification_score = 0.0 

842 if db_user.phone_verification_verified: 

843 verification_score += 1.0 * db_user.phone_is_verified 

844 

845 user = api_pb2.User( 

846 user_id=db_user.id, 

847 username=db_user.username, 

848 name=db_user.name, 

849 city=db_user.city, 

850 hometown=db_user.hometown, 

851 timezone=db_user.timezone, 

852 lat=lat, 

853 lng=lng, 

854 radius=db_user.geom_radius, 

855 verification=verification_score, 

856 community_standing=db_user.community_standing, 

857 num_references=num_references, 

858 gender=db_user.gender, 

859 pronouns=db_user.pronouns, 

860 age=int(db_user.age), 

861 joined=Timestamp_from_datetime(db_user.display_joined), 

862 last_active=Timestamp_from_datetime(db_user.display_last_active), 

863 hosting_status=hostingstatus2api[db_user.hosting_status], 

864 meetup_status=meetupstatus2api[db_user.meetup_status], 

865 occupation=db_user.occupation, 

866 education=db_user.education, 

867 about_me=db_user.about_me, 

868 my_travels=db_user.my_travels, 

869 things_i_like=db_user.things_i_like, 

870 about_place=db_user.about_place, 

871 language_abilities=[ 

872 api_pb2.LanguageAbility(code=ability.language_code, fluency=fluency2api[ability.fluency]) 

873 for ability in db_user.language_abilities 

874 ], 

875 regions_visited=[region.code for region in db_user.regions_visited], 

876 regions_lived=[region.code for region in db_user.regions_lived], 

877 additional_information=db_user.additional_information, 

878 friends=friends_status, 

879 pending_friend_request=pending_friend_request, 

880 smoking_allowed=smokinglocation2api[db_user.smoking_allowed], 

881 sleeping_arrangement=sleepingarrangement2api[db_user.sleeping_arrangement], 

882 parking_details=parkingdetails2api[db_user.parking_details], 

883 avatar_url=db_user.avatar.full_url if db_user.avatar else None, 

884 avatar_thumbnail_url=db_user.avatar.thumbnail_url if db_user.avatar else None, 

885 badges=[badge.badge_id for badge in db_user.badges], 

886 **get_strong_verification_fields(session, db_user), 

887 ) 

888 

889 if db_user.max_guests is not None: 

890 user.max_guests.value = db_user.max_guests 

891 

892 if db_user.last_minute is not None: 

893 user.last_minute.value = db_user.last_minute 

894 

895 if db_user.has_pets is not None: 

896 user.has_pets.value = db_user.has_pets 

897 

898 if db_user.accepts_pets is not None: 

899 user.accepts_pets.value = db_user.accepts_pets 

900 

901 if db_user.pet_details is not None: 

902 user.pet_details.value = db_user.pet_details 

903 

904 if db_user.has_kids is not None: 

905 user.has_kids.value = db_user.has_kids 

906 

907 if db_user.accepts_kids is not None: 

908 user.accepts_kids.value = db_user.accepts_kids 

909 

910 if db_user.kid_details is not None: 

911 user.kid_details.value = db_user.kid_details 

912 

913 if db_user.has_housemates is not None: 

914 user.has_housemates.value = db_user.has_housemates 

915 

916 if db_user.housemate_details is not None: 

917 user.housemate_details.value = db_user.housemate_details 

918 

919 if db_user.wheelchair_accessible is not None: 

920 user.wheelchair_accessible.value = db_user.wheelchair_accessible 

921 

922 if db_user.smokes_at_home is not None: 

923 user.smokes_at_home.value = db_user.smokes_at_home 

924 

925 if db_user.drinking_allowed is not None: 

926 user.drinking_allowed.value = db_user.drinking_allowed 

927 

928 if db_user.drinks_at_home is not None: 

929 user.drinks_at_home.value = db_user.drinks_at_home 

930 

931 if db_user.other_host_info is not None: 

932 user.other_host_info.value = db_user.other_host_info 

933 

934 if db_user.sleeping_details is not None: 

935 user.sleeping_details.value = db_user.sleeping_details 

936 

937 if db_user.area is not None: 

938 user.area.value = db_user.area 

939 

940 if db_user.house_rules is not None: 

941 user.house_rules.value = db_user.house_rules 

942 

943 if db_user.parking is not None: 

944 user.parking.value = db_user.parking 

945 

946 if db_user.camping_ok is not None: 

947 user.camping_ok.value = db_user.camping_ok 

948 

949 return user 

950 

951 

952def lite_user_to_pb(lite_user): 

953 lat, lng = get_coordinates(lite_user.geom) or (0, 0) 

954 

955 return api_pb2.LiteUser( 

956 user_id=lite_user.id, 

957 username=lite_user.username, 

958 name=lite_user.name, 

959 city=lite_user.city, 

960 age=int(lite_user.age), 

961 avatar_url=urls.media_url(filename=lite_user.avatar_filename, size="full") 

962 if lite_user.avatar_filename 

963 else None, 

964 avatar_thumbnail_url=urls.media_url(filename=lite_user.avatar_filename, size="thumbnail") 

965 if lite_user.avatar_filename 

966 else None, 

967 lat=lat, 

968 lng=lng, 

969 radius=lite_user.radius, 

970 )