review_utils.py 7.8 KB

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