review_utils.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import re
  2. import json
  3. from requests import get, put, post
  4. from gauth.auth_utils import get_gmb_id, get_auth_header
  5. from .models import Review, Reply
  6. from gauth.models import Location
  7. from django.utils import timezone
  8. _, account_id = get_gmb_id()
  9. STAR_REVIEW_NUM = {'STAR_RATING_UNSPECIFIED': 0, 'ONE': 1, 'TWO': 2, 'THREE': 3, 'FOUR': 4, 'FIVE': 5}
  10. BASE_URL = f'https://mybusiness.googleapis.com/v4/'
  11. def clean_comment(text):
  12. rules = [
  13. {r'[^\x00-\x7F]+': ''},
  14. {r'^\(Google-\s*\)(.|\n|]\s)*\(\)': ''}
  15. ]
  16. for rule in rules:
  17. for (k, v) in rule.items():
  18. regex = re.compile(k)
  19. text = regex.sub(v, text)
  20. text = text.rstrip()
  21. return text
  22. def get_review_list_url(location_id, next_page_token=''):
  23. # An helper function that make a url that need to consume GMB review api
  24. return f'{BASE_URL}accounts/{account_id}/locations/{location_id}/reviews?pageToken='+next_page_token
  25. def get_reply_url(location_id, review_id):
  26. return f'{BASE_URL}accounts/{account_id}/locations/{location_id}/reviews/{review_id}/reply'
  27. def reply_review(review, replied_text):
  28. '''
  29. reply a review with a put request.
  30. :param review: review object -> a review which you want to reply.
  31. :param replied_text: string -> The actual reply that you want to post.
  32. :return:
  33. '''
  34. url = get_reply_url(review.location_id, review.review_id)
  35. headers = get_auth_header()
  36. payload = json.dumps({'comment': replied_text})
  37. response = put(url, headers=headers, data=payload)
  38. return response
  39. def insert_review_into_database(reviews, loc_id):
  40. '''
  41. Insert reviews to database.
  42. :param reviews: all reviews for location.
  43. :param loc_id: location id unrecorded_reviews belongs to.
  44. :return: It insert all reviews if it is not exits in database and return nothing.
  45. '''
  46. for rev in reviews:
  47. review_id = rev.get('reviewId')
  48. try:
  49. review = Review.objects.get(pk=review_id)
  50. except Review.DoesNotExist:
  51. review = Review(review_id=review_id)
  52. review.comment = rev.get('comment')
  53. review.create_time = rev.get('createTime')
  54. review.update_time = rev.get('updateTime')
  55. review.star_rating = STAR_REVIEW_NUM[rev.get('starRating')]
  56. reviewer = rev.get('reviewer')
  57. review.reviewer_name = reviewer.get('displayName')
  58. review.reviewer_photo = reviewer.get('profilePhotoUrl')
  59. review.location_id = loc_id
  60. review_reply = rev.get('reviewReply')
  61. # Check if it is already replied.
  62. if review_reply:
  63. replied_text = review_reply.get('comment')
  64. create_time = review_reply.get('updateTime')
  65. reply, created = Reply.objects.update_or_create(
  66. replied_text=replied_text,
  67. create_time=create_time
  68. )
  69. review.reply = reply
  70. else:
  71. review.reply = None
  72. review.save()
  73. def sync_all_review(loc_id):
  74. '''
  75. Sync a location if any bad thing occur i.e. any network break.
  76. :param: loc_id -> Location id of a particular location
  77. :return: None -> It just update all reviews of this location and return nothing.
  78. '''
  79. next_page_token = ''
  80. headers = get_auth_header()
  81. while True:
  82. url = get_review_list_url(loc_id, next_page_token)
  83. res = get(url, headers=headers)
  84. if res.status_code == 401:
  85. headers = get_auth_header()
  86. continue
  87. data = res.json()
  88. reviews = data['reviews']
  89. if len(reviews) != 0:
  90. insert_review_into_database(reviews, loc_id)
  91. next_page_token = data.get('nextPageToken')
  92. if next_page_token is None:
  93. break
  94. average_rating = data.get('averageRating')
  95. total_reviews = data.get('totalReviewCount')
  96. total_reviews_db = Review.objects.filter(location_id=loc_id).count()
  97. update_location_data(loc_id, average_rating, total_reviews, total_reviews_db)
  98. def update_location_data(loc_id, average_rating, total_reviews, total_reviews_db):
  99. loc = Location.objects.get(pk=loc_id)
  100. loc.average_rating = average_rating
  101. loc.total_review = total_reviews
  102. loc.total_review_DB = total_reviews_db
  103. loc.save()
  104. def fetch_last_20_reviews(loc_id, page_size=20):
  105. headers = get_auth_header()
  106. url = get_review_list_url(loc_id)+'&pageSize='+str(page_size)
  107. res = get(url, headers=headers)
  108. data = res.json()
  109. reviews = data.get('reviews')
  110. average_rating = data.get('averageRating')
  111. total_reviews = data.get('totalReviewCount')
  112. if len(reviews) > 0:
  113. insert_review_into_database(reviews, loc_id)
  114. total_reviews_db = Review.objects.filter(location_id=loc_id).count()
  115. update_location_data(loc_id, average_rating, total_reviews, total_reviews_db)
  116. def store_batch_of_reviews(reviews):
  117. for rev in reviews:
  118. location_id = rev.get('name').split('/')[-1]
  119. rev = rev.get('review')
  120. review_id = rev.get('reviewId')
  121. try:
  122. review = Review.objects.get(pk=review_id)
  123. except Review.DoesNotExist:
  124. review = Review(review_id=review_id)
  125. review.comment = rev.get('comment')
  126. review.create_time = rev.get('createTime')
  127. review.update_time = rev.get('updateTime')
  128. review.star_rating = STAR_REVIEW_NUM[rev.get('starRating')]
  129. reviewer = rev.get('reviewer')
  130. review.reviewer_name = reviewer.get('displayName')
  131. review.reviewer_photo = reviewer.get('profilePhotoUrl')
  132. review.location_id = location_id
  133. review_reply = rev.get('reviewReply')
  134. # Check if it is already replied.
  135. if review_reply:
  136. replied_text = review_reply.get('comment')
  137. create_time = review_reply.get('updateTime')
  138. reply, created = Reply.objects.update_or_create(
  139. replied_text=replied_text,
  140. create_time=create_time
  141. )
  142. review.reply = reply
  143. else:
  144. review.reply = None
  145. review.save()
  146. def fetch_batch_of_reviews():
  147. headers = get_auth_header()
  148. url = f'{BASE_URL}accounts/{account_id}/locations:batchGetReviews'
  149. # location names should be in this format:
  150. # "accounts/103266181421855655295/locations/8918455867446117794",
  151. locations = Location.objects.all()
  152. location_names = [f'accounts/{account_id}/locations/{loc.location_id}' for loc in locations]
  153. '''
  154. post data format:
  155. {
  156. "locationNames": [
  157. string
  158. ],
  159. "pageSize": integer, -> Total number of reviews
  160. "pageToken": string, -> If has any to go next page.
  161. "orderBy": string, -> By-default updateTime desc
  162. "ignoreRatingOnlyReviews": boolean -> Whether to ignore rating-only reviews
  163. }
  164. '''
  165. payload = json.dumps({
  166. "locationNames": location_names
  167. })
  168. response = post(url, headers=headers, data=payload)
  169. if response.status_code == 200:
  170. data = response.json()
  171. location_reviews = data.get('locationReviews')
  172. store_batch_of_reviews(location_reviews)
  173. else:
  174. return None
  175. def populate_reviews():
  176. start = timezone.now()
  177. locations = Location.objects.all().values('location_id')
  178. for loc in locations:
  179. loc_id = loc.get('location_id')
  180. fetch_last_20_reviews(loc_id)
  181. end = timezone.now()
  182. elapsed = end - start
  183. print(f'Elapsed time: {elapsed.seconds//60} minutes and {elapsed.seconds % 60} secs.')
  184. def get_bad_reviews(location_id, **kwargs):
  185. '''
  186. a utility function that return all reviews has less or equal three.
  187. :param location_id: str -> id of the location where reviews are belongs to
  188. :param kwargs: i.e (days=__, hours=__, minutes=__)
  189. :return: QuerySet -> all low rating reviews in last * days/hours/minutes
  190. Example --------------
  191. >>> get_bad_reviews(location_id='123456', days=5, hours=2, minute=1)
  192. >>> get_bad_reviews(location_id='123456', days=5)
  193. >>> get_bad_reviews(location_id='123456', hours=5)
  194. '''
  195. now = timezone.now()
  196. date = now - timezone.timedelta(**kwargs)
  197. reviews = Review.objects.filter(location_id=location_id, update_time__gte=date, star_rating__lte=3)
  198. return reviews