review_utils.py 7.9 KB

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