review_utils.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import json
  2. from requests import get, put
  3. from gauth.auth_utils import get_gmb_id, get_auth_header
  4. from gauth.location_utils import get_all_location_ids
  5. from .models import Review, Reply
  6. from gauth.models import Location
  7. from django.utils import timezone
  8. STAR_REVIEW_NUM = {'STAR_RATING_UNSPECIFIED': 0, 'ONE': 1, 'TWO': 2, 'THREE': 3, 'FOUR': 4, 'FIVE': 5}
  9. def get_review_list_url(location_id, next_page_token=''):
  10. # An helper function that make a url that need to consume GMB review api
  11. _, account_id = get_gmb_id()
  12. return f'https://mybusiness.googleapis.com/v4/accounts/{account_id}/locations/{location_id}/reviews?pageToken='+next_page_token
  13. def get_reply_url(location_id, review_id):
  14. _, account_id = get_gmb_id()
  15. return f'https://mybusiness.googleapis.com/v4/accounts/{account_id}/locations/{location_id}/reviews/{review_id}/reply'
  16. def reply_review(review, replied_text):
  17. '''
  18. reply a review with a put request.
  19. :param review: review object -> a review which you want to reply.
  20. :param replied_text: string -> The actual reply that you want to post.
  21. :return:
  22. '''
  23. url = get_reply_url(review.location_id, review.review_id)
  24. headers = get_auth_header()
  25. payload = json.dumps({'comment': replied_text})
  26. response = put(url, headers=headers, data=payload)
  27. return response
  28. def insert_review_into_database(reviews, loc_id):
  29. '''
  30. Insert reviews to database.
  31. :param unrecorded_reviews: all reviews for location.
  32. :param loc: location that unrecorded_reviews belongs to.
  33. :return: It insert all reviews if it is not exits in database and return nothing.
  34. '''
  35. for rev in reviews:
  36. review_id = rev.get('reviewId')
  37. try:
  38. review = Review.objects.get(pk=review_id)
  39. except Review.DoesNotExist:
  40. review = Review(review_id=review_id)
  41. review.comment = rev.get('comment')
  42. review.create_time = rev.get('createTime')
  43. review.update_time = rev.get('updateTime')
  44. review.star_rating = STAR_REVIEW_NUM[rev.get('starRating')]
  45. reviewer = rev.get('reviewer')
  46. review.reviewer_name = reviewer.get('displayName')
  47. review.reviewer_photo = reviewer.get('profilePhotoUrl')
  48. review.location_id = loc_id
  49. review_reply = rev.get('reviewReply')
  50. # Check if it is already replied.
  51. if review_reply:
  52. replied_text = review_reply.get('comment')
  53. create_time = review_reply.get('updateTime')
  54. review.reply = Reply.objects.create(
  55. replied_text=replied_text,
  56. create_time=create_time
  57. )
  58. else:
  59. review.reply = None
  60. review.save()
  61. def sync_all_review(loc_id):
  62. '''
  63. Sync a location if any bad thing occur i.e. any network break.
  64. :param: loc_id -> Location id of a particular location
  65. :return: None -> It just update all reviews of this location and return nothing.
  66. '''
  67. loc = Location.objects.get(pk=loc_id)
  68. next_page_token = ''
  69. headers = get_auth_header()
  70. while True:
  71. url = get_review_list_url(loc_id, next_page_token)
  72. res = get(url, headers=headers)
  73. if res.status_code == 401:
  74. headers = get_auth_header()
  75. continue
  76. data = res.json()
  77. reviews = data['reviews']
  78. if len(reviews) != 0:
  79. insert_review_into_database(reviews, loc)
  80. next_page_token = data.get('nextPageToken')
  81. if next_page_token is None:
  82. break
  83. average_rating = data.get('averageRating')
  84. total_reviews = data.get('totalReviewCount')
  85. total_reviews_db = Review.objects.filter(location_id=loc_id).count()
  86. update_location_data(loc_id, average_rating, total_reviews, total_reviews_db)
  87. def update_location_data(loc_id, average_rating, total_reviews, total_reviews_db):
  88. loc = Location.objects.get(pk=loc_id)
  89. loc.average_rating = average_rating
  90. loc.total_review = total_reviews
  91. loc.total_review_DB = total_reviews_db
  92. loc.save()
  93. def fetch_last_20_reviews(loc_id):
  94. headers = get_auth_header()
  95. url = get_review_list_url(loc_id)+'&pageSize=20'
  96. res = get(url, headers=headers)
  97. data = res.json()
  98. reviews = data['reviews']
  99. average_rating = data.get('averageRating')
  100. total_reviews = data.get('totalReviewCount')
  101. if len(reviews) > 0:
  102. insert_review_into_database(reviews, loc_id)
  103. total_reviews_db = Review.objects.filter(location_id=loc_id).count()
  104. update_location_data(loc_id, average_rating, total_reviews, total_reviews_db)
  105. def populate_reviews():
  106. start = timezone.now()
  107. locations = get_all_location_ids()
  108. for loc_id in locations:
  109. fetch_last_20_reviews(loc_id)
  110. end = timezone.now()
  111. elapsed = end - start
  112. print(f'Elapsed time: {elapsed.seconds//60} minutes and {elapsed.seconds % 60} secs.')
  113. def get_bad_reviews(location_id, **kwargs):
  114. '''
  115. a utility function that return all reviews has less or equal three.
  116. :param location_id: str -> id of the location where reviews are belongs to
  117. :param kwargs: i.e (days=__, hours=__, minutes=__)
  118. :return: QuerySet -> all low rating reviews in last * days/hours/minutes
  119. Example --------------
  120. >>> get_bad_reviews(location_id='123456', days=5, hours=2, minute=1)
  121. >>> get_bad_reviews(location_id='123456', days=5)
  122. >>> get_bad_reviews(location_id='123456', hours=5)
  123. '''
  124. now = timezone.now()
  125. date = now - timezone.timedelta(**kwargs)
  126. reviews = Review.objects.filter(location_id=location_id, update_time__gte=date, star_rating__lte=3)
  127. return reviews