def create_vote_node(node_id, vote_type, voter, parent_object): """ Creates a vote node that we can use to track reputation changes over time for users. This node is hooked up to the object that has been voted on and the user that voted. The node is created every time someone votes and does not get updated when someone changes their vote, it just makes a new one, this may not be the final functionality but this is the current implementation. :param node_id: :param vote_type: :param voter: :param parent_object: :return: """ sb_object = get_parent_votable_content(parent_object) try: current_pleb = Pleb.get(username=voter) except (DoesNotExist, Pleb.DoesNotExist, CypherException, ClientError, IOError) as e: raise create_vote_node.retry(exc=e, countdown=10, max_retries=None) try: owner = Pleb.get(username=sb_object.owner_username) except (DoesNotExist, Pleb.DoesNotExist, CypherException, ClientError, IOError) as e: raise create_vote_node.retry(exc=e, countdown=10, max_retries=None) last_vote = sb_object.get_last_user_vote(current_pleb.username) if sb_object.visibility == 'public': if vote_type == 1: reputation_change = sb_object.up_vote_adjustment else: reputation_change = sb_object.down_vote_adjustment else: reputation_change = 0 try: vote_node = Vote.nodes.get(object_uuid=node_id) except (Vote.DoesNotExist, DoesNotExist): vote_node = Vote(object_uuid=node_id, vote_type=vote_type, reputation_change=reputation_change).save() if last_vote is None: sb_object.first_votes.connect(vote_node) sb_object.last_votes.connect(vote_node) else: sb_object.last_votes.disconnect(last_vote) last_vote.next_vote.connect(vote_node) sb_object.last_votes.connect(vote_node) vote_node.vote_on.connect(sb_object) vote_node.owned_by.connect(current_pleb) if not owner.last_counted_vote_node: owner.last_counted_vote_node = node_id owner.reputation_update_seen = False owner.save() cache.delete(owner.username) # See reputation_change method on pleb for where this is set cache.delete("%s_reputation_change" % owner.username) return True
def complete_order(self, request, object_uuid=None): if request.user.username != "tyler_wiersing" \ and request.user.username != "devon_bleibtrey": return Response({"detail": "You do not have permission to " "perform this action.", "status_code": status.HTTP_403_FORBIDDEN}, status=status.HTTP_403_FORBIDDEN) order = self.get_object() tracking_url = request.data.get("tracking_url", None) if tracking_url: order.tracking_url = tracking_url order.completed = True order.save() order_owner = Pleb.get(order.owner_username) message_data = { 'message_type': 'email', 'subject': 'Sagebrew Order Processed', 'body': 'Hi %s,\nYour Order has been processed and you ' 'can track the delivery here:\n\n%s ' % (order_owner.first_name, tracking_url), 'template': "personal", 'from_user': { 'type': "admin", 'id': settings.INTERCOM_ADMIN_ID_DEVON}, 'to_user': { 'type': "user", 'user_id': order.owner_username} } serializer = IntercomMessageSerializer(data=message_data) if serializer.is_valid(): serializer.save() mission = order.get_mission() mission_owner = Pleb.get(mission.owner_username) message_data = { 'message_type': 'email', 'subject': 'Someone has given you a Gift!', 'body': 'Hi %s,\nSomeone has sent you a Gift from your ' 'Giftlist!\nYou can track the delivery here:\n\n' '%s' % (mission_owner.first_name, tracking_url), 'template': "personal", 'from_user': { 'type': "admin", 'id': settings.INTERCOM_ADMIN_ID_DEVON}, 'to_user': { 'type': "user", 'user_id': mission.owner_username} } serializer = IntercomMessageSerializer(data=message_data) if serializer.is_valid(): serializer.save() return Response(OrderSerializer(order).data, status=status.HTTP_200_OK)
def create(self, validated_data): request = self.context["request"] owner = Pleb.get(request.user.username) wall_owner = validated_data.pop('wall_owner_profile', None) images = validated_data.pop('images', []) included_urls = validated_data.pop('included_urls', []) uuid = str(uuid1()) url = reverse('profile_page', kwargs={'pleb_username': request.user.username}, request=request) href = reverse('post-detail', kwargs={'object_uuid': uuid}, request=request) post = Post(owner_username=owner.username, wall_owner_username=wall_owner.username, object_uuid=uuid, url=url, href=href, **validated_data).save() post.owned_by.connect(owner) wall = wall_owner.get_wall() post.posted_on_wall.connect(wall) wall.posts.connect(post) [ post.uploaded_objects.connect( UploadedObject.nodes.get(object_uuid=image)) for image in images ] for url in included_urls: try: post.url_content.connect(URLContent.nodes.get(url=url)) except (DoesNotExist, URLContent.DoesNotExist): pass return post
def create(self, request, *args, **kwargs): croppic = request.query_params.get('croppic', 'false').lower() editor = request.query_params.get('editor', 'false').lower() file_object = request.data.get('file_object', None) if file_object is None: file_object = request.data.get('file', None) if file_object is None: file_object = request.data.get('img', None) serializer = self.get_serializer(data={"file_object": file_object}, context={'request': request}) if serializer.is_valid(): owner = Pleb.get(request.user.username) upload = serializer.save(owner=owner) if croppic == 'true': return Response( { "status": "success", "url": upload.url, "width": upload.width, "height": upload.height }, status=status.HTTP_200_OK) if editor == 'true': return Response({"files": [serializer.data]}, status=status.HTTP_200_OK) return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def remove_profiles(self, instance): for profile in self.data['profiles']: profile_pleb = Pleb.get(username=profile) instance.accountants.disconnect(profile_pleb) profile_pleb.campaign_accountant.disconnect(instance) cache.delete("%s_accountants" % instance.object_uuid) return instance
def update_view_count_task(object_uuid, username): try: profile = Pleb.get(username) except (Pleb.DoesNotExist, DoesNotExist) as e: raise update_view_count_task.retry(exc=e, max_retries=5, countdown=45) sb_object = cache.get(object_uuid) if sb_object is None: sb_object = Searchable.nodes.get(object_uuid=object_uuid) query = 'MATCH (a:Pleb {username: "******"})-[b:VIEWED]->' \ ' (c:Searchable {object_uuid: "%s"}) RETURN b' % ( username, object_uuid) res, col = db.cypher_query(query) if len(res) == 0: res = update_view_count(sb_object) if isinstance(res, Exception): raise update_view_count_task.retry(exc=res, countdown=5, max_retries=None) relationship = profile.viewed.connect(sb_object) sb_object.viewed_by.connect(profile) else: relationship = profile.viewed.relationship(sb_object) relationship.times_viewed += 1 relationship.save() return True
def create(self, request, *args, **kwargs): wall_pleb = Pleb.get(self.kwargs[self.lookup_field]) friend_with = wall_pleb.is_friends_with(request.user.username) if friend_with is False and wall_pleb.username != request.user.username: return Response( {"detail": "Sorry you are not friends with this" " person."}, status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(data=request.data) if serializer.is_valid(): instance = serializer.save(wall_owner_profile=wall_pleb) spawn_task(task_func=spawn_notifications, task_param={ "from_pleb": request.user.username, "sb_object": serializer.data['object_uuid'], "url": reverse('single_post_page', kwargs={ "object_uuid": serializer.data["object_uuid"] }), "to_plebs": [ self.kwargs[self.lookup_field], ], "notification_id": str(uuid1()), "action_name": instance.action_name }) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): request, _, _, _, _ = gather_request_data(self.context) stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION donor = Pleb.get(request.user.username) token = validated_data.pop('token', None) # TODO add payment_method selection support to direct donations # this pop is just to allow the donation to save using **validated_data validated_data.pop('payment_method', None) donation = Donation(owner_username=donor.username, **validated_data).save() if not donor.stripe_customer_id: customer = stripe.Customer.create( description="Customer for %s" % donor.username, card=token, email=donor.email) donor.stripe_customer_id = customer['id'] donor.save() cache.delete(donor.username) donor.refresh() donor.donations.connect(donation) donation.owned_by.connect(donor) charge = stripe.Charge.create( amount=donation.amount, currency="usd", customer=donor.stripe_customer_id, receipt_email=donor.email, description="Donation to Sagebrew from %s" % donor.username ) donation.stripe_charge_id = charge['id'] donation.save() spawn_task(task_func=check_privileges, task_param={"username": donor.username}) return donation
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, context={'request': request}) if serializer.is_valid(): pleb = Pleb.get(request.user.username) parent_object = cache.get(self.kwargs[self.lookup_field]) if parent_object is None: parent_object = SBContent.nodes.get( object_uuid=self.kwargs[self.lookup_field]) # Don't set it here as only questions will be # retrievable/settable serializer.save(owner=pleb, parent_object=parent_object) serializer_data = serializer.data ''' Not doing this yet as I don't know how much info we want to give to someone about there info being flagged. I think we'll just want to notify them just not give them the person who did flag their content. We'll also need to allow them to provide a rebuttal. data = { "username": request.user.username, "flag": serializer_data['object_uuid'], "url": serializer_data['url'], "parent_object": self.kwargs[self.lookup_field] } spawn_task(task_func=create_flag_relations, task_param=data) ''' return Response(serializer_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): request = self.context["request"] # Note that DRF requires us to use the source as the key here but # tags prior to serializing mission = None tags = validated_data.pop('get_tags', []) owner = Pleb.get(request.user.username) mission_id = validated_data.get('mission', '') if mission_id: mission = Mission.get(mission_id) validated_data['owner_username'] = owner.username uuid = str(uuid1()) validated_data['content'] = render_content( validated_data.get('content', "")) url = reverse('question_detail_page', kwargs={ 'question_uuid': uuid, "slug": slugify(validated_data['title']) }, request=request) href = reverse('question-detail', kwargs={'object_uuid': uuid}, request=request) soup = BeautifulSoup(validated_data['content'], "lxml").get_text() question = Question(url=url, href=href, object_uuid=uuid, summary=smart_truncate(soup), **validated_data).save() question.owned_by.connect(owner) if mission is not None: mission.associated_with.connect(question) for tag in tags: query = 'MATCH (t:Tag {name:"%s"}) WHERE NOT t:AutoTag ' \ 'RETURN t' % slugify(tag) res, _ = db.cypher_query(query) if not res.one: if (request.user.username == "devon_bleibtrey" or request.user.username == "tyler_wiersing" or owner.reputation >= 1250): tag_obj = Tag(name=slugify(tag)).save() question.tags.connect(tag_obj) else: continue else: tag_obj = Tag.inflate(res.one) question.tags.connect(tag_obj) spawn_task(task_func=update_tags, task_param={"tags": tags}) if validated_data.get('external_location_id', None) is not None: spawn_task( task_func=create_location_tree, task_param={"external_id": question.external_location_id}) spawn_task(task_func=add_auto_tags_to_question_task, task_param={"object_uuid": question.object_uuid}) spawn_task(task_func=create_question_summary_task, task_param={'object_uuid': question.object_uuid}) question.refresh() cache.set(question.object_uuid, question) return question
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save(owner=Pleb.get(self.request.user.username)) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def dispatch(self, *args, **kwargs): profile = Pleb.get(username=self.request.user.username) if self.request.user.username == 'tyler_wiersing' \ or self.request.user.username == 'devon_bleibtrey' or \ profile.reputation >= 10000: return super(CouncilView, self).dispatch(*args, **kwargs) return redirect('profile_page', pleb_username=self.request.user.username)
def create(self, request, *args, **kwargs): object_uuid = self.kwargs[self.lookup_field] now = str(datetime.now(pytz.utc)) vote_data = request.data serializer = self.get_serializer(data=vote_data, context={"request": request}) if not Pleb.get(request.user.username).is_verified: return Response( { "detail": "Sorry, you cannot vote unless you are verified!", "status": status.HTTP_401_UNAUTHORIZED, "developer_message": "A user can only vote on content " "if they are verified." }, status=status.HTTP_401_UNAUTHORIZED) if serializer.is_valid(): parent_object_uuid = self.kwargs[self.lookup_field] vote_status = int(serializer.validated_data['vote_type']) handle_vote(parent_object_uuid, vote_status, request.user.username, now) async_result = cache.get("%s_%s_vote" % (request.user.username, object_uuid)) task_params = { "username": request.user.username, "object_uuid": object_uuid } if async_result is not None: # if there is already a task lined up, # revoke it and spawn a new one async_result.revoke() # spawn a task which will execute 30 seconds from now # potential improvement here is to have a way to detect if the new_task = spawn_task(spawn_user_updates, task_param=task_params, countdown=30) cache.set("%s_%s_vote" % (request.user.username, object_uuid), new_task) search_result = cache.get("%s_vote_search_update" % object_uuid) if search_result is not None: search_result.revoke() task_param = {"object_uuid": object_uuid} spawned = spawn_task(task_func=update_search_object, task_param=task_param, countdown=10) cache.set("%s_vote_search_update" % object_uuid, spawned) return Response({ "detail": "Successfully created or modified " "vote.", "status": status.HTTP_200_OK, "developer_message": None }) else: return Response(serializer.errors, status=400)
def update(self, instance, validated_data): current_moderators = cache.get( "%s_moderators" % instance.owner_username, []) for profile in \ list(set(validated_data['profiles']) - set( current_moderators)): profile_pleb = Pleb.get(username=profile) instance.moderators.connect(profile_pleb) cache.delete("%s_moderators" % instance.owner_username) return instance
def update(self, instance, validated_data): request, _, _, _, _ = gather_request_data(self.context) stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION mission = validated_data.pop('mission', None) quest = validated_data.pop('quest', None) payment_method = validated_data.pop('payment_method', None) donor = Pleb.get(instance.owner_username) quest_desc = quest.title \ if quest.title else "%s %s" % (quest.first_name, quest.last_name) mission_desc = mission.get_mission_title() description = "Gift purchase to %s's mission for %s" % (quest_desc, mission_desc) payment_method = payment_method if payment_method is not None \ else donor.stripe_default_card_id stripe_res = stripe.Charge.create(customer=donor.stripe_customer_id, amount=instance.total, currency="usd", description=description, receipt_email=donor.email, source=payment_method) instance.stripe_charge_id = stripe_res['id'] instance.paid = True instance.save() message_data = { 'message_type': 'email', 'subject': 'New Gift', 'body': get_template('orders/email/new_order.html').render( Context({ 'first_name': quest.first_name, 'mission_title': mission_desc, "donor_first_name": donor.first_name, "donor_last_name": donor.last_name, })), 'template': "personal", 'from_user': { 'type': "admin", 'id': settings.INTERCOM_ADMIN_ID_DEVON }, 'to_user': { 'type': "user", 'user_id': quest.owner_username } } serializer = IntercomMessageSerializer(data=message_data) serializer.is_valid(raise_exception=True) serializer.save() return instance
def update(self, instance, validated_data): current_accountants = cache.get( "%s_accountants" % instance.object_uuid, []) for profile in \ list(set(validated_data['profiles']) - set( current_accountants)): profile_pleb = Pleb.get(username=profile) instance.accountants.connect(profile_pleb) profile_pleb.campaign_accountant.connect(instance) cache.delete("%s_accountants" % instance.object_uuid) return instance
def crop(self, request, object_uuid=None): resize = self.request.query_params.get("resize", "false").lower() croppic = self.request.query_params.get('croppic', 'false').lower() img_file = urllib2.urlopen(request.data['imgUrl']) read_file = img_file.read() file_object = BytesIO(read_file) image = Image.open(file_object) image_format = image.format crop_serializer = CropSerializer(data=request.data) if crop_serializer.is_valid(): crop_data = crop_serializer.data else: return Response(crop_serializer.errors, status=status.HTTP_400_BAD_REQUEST) if resize == 'true': image = resize_image(image, int(crop_data['resize_width']), int(crop_data['resize_height'])) cropped_image = crop_image2(image, crop_data['crop_width'], crop_data['crop_height'], crop_data['image_x1'], crop_data['image_y1']) # Fill cropped image into buffer file_stream = BytesIO() cropped_image.save(file_stream, format=image_format) file_stream.seek(0) # Upload cropped pic and then run serializer # Not the best solution but simplifies the logic. If someone has a # better approach feel free to update. Perhaps an InMemoryFile passed # to the serializer file_name = "%s-%sx%s.%s" % (object_uuid, crop_data['crop_width'], crop_data['crop_height'], image_format.lower()) serializer = upload_modified_image(file_name, file_stream.read(), request, object_uuid) if serializer.is_valid(): owner = Pleb.get(request.user.username) upload = serializer.save(owner=owner) if croppic == 'true': profile_page_url = reverse( "profile_page", kwargs={"pleb_username": request.user.username}, request=request) return Response( { "status": "success", "url": upload.url, "profile": profile_page_url }, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_can_comment(self, obj): """ Determine if the currently logged in user can flag this object. :param obj: :return: """ request, _, _, _, _ = gather_request_data(self.context) detail = None short_detail = None if request is None: return { "status": False, "detail": "You must be logged in to comment on content.", "short_detail": "Signup To Comment" } if not request.user.is_authenticated(): return { "status": False, "detail": "You must be logged in to comment on content.", "short_detail": "Signup To Comment" } if obj.owner_username == request.user.username: # Always allow the owner to comment on their own content return { "status": True, "detail": detail, "short_detail": short_detail } obj_type = obj.__class__.__name__.lower() if obj_type == "question" or obj_type == "solution": can_comment = "comment" in Pleb.get( username=request.user.username).get_privileges() if not can_comment: mission = obj.get_mission(obj.object_uuid, request) if mission: if mission['owner_username'] == request.user.username: return { "status": True, "detail": detail, "short_detail": short_detail } detail = "You must have 20+ reputation to comment on " \ "Conversation Cloud content." short_detail = "Requirement: 20+ Reputation" else: can_comment = True return { "status": can_comment, "detail": detail, "short_detail": short_detail }
def perform_create(self, serializer): donor = Pleb.get(self.request.user.username) if "/v1/missions/" in self.request.path: mission = Mission.get(object_uuid=self.kwargs[self.lookup_field]) quest = Mission.get_quest( object_uuid=self.kwargs[self.lookup_field]) else: mission = None quest = Quest.get(owner_username=self.kwargs[self.lookup_field]) serializer.save(mission=mission, donor=donor, quest=quest, owner_username=donor.username)
def create(self, validated_data): volunteer = validated_data.pop('volunteer', None) mission = validated_data.pop('mission', None) activity = Volunteer(mission_id=mission.object_uuid, **validated_data).save() activity.volunteer.connect(volunteer) activity.mission.connect(mission) mission_owner = Pleb.get(username=mission.owner_username) message_data = { 'message_type': 'email', 'subject': 'New Volunteer', 'body': get_template('volunteer/email/new_volunteer.html').render( Context({ 'first_name': mission_owner.first_name, 'mission_title': mission.get_mission_title(), "activities": [ dict(settings.VOLUNTEER_ACTIVITIES)[item] for item in validated_data['activities'] ], "volunteer_first_name": volunteer.first_name, "volunteer_last_name": volunteer.last_name, "mission_volunteers": reverse('mission_volunteers', kwargs={ 'object_uuid': mission.object_uuid, 'slug': slugify(mission.get_mission_title()) }, request=self.context.get('request')) })), 'template': "personal", 'from_user': { 'type': "admin", 'id': settings.INTERCOM_ADMIN_ID_DEVON }, 'to_user': { 'type': "user", 'user_id': mission.owner_username } } serializer = IntercomMessageSerializer(data=message_data) serializer.is_valid(raise_exception=True) serializer.save() return activity
def spawn_notifications(sb_object, from_pleb, to_plebs, notification_id, url, action_name, public=False): """ This function will take an object(post,comment,solution,etc.), the type of the object, from_pleb and a to_pleb. To pleb can be a list of people or just a singular pleb and will create a notification about the object :param url: :param sb_object: :param from_pleb: :param to_plebs: :param notification_id :param action_name :param public :return: """ plebeians = [] if from_pleb in to_plebs: to_plebs.remove(from_pleb) try: from_pleb = Pleb.get(username=from_pleb) except(CypherException, Pleb.DoesNotExist, DoesNotExist, IOError) as e: raise spawn_notifications.retry(exc=e, countdown=3, max_retries=100) for plebeian in to_plebs: try: to_pleb = Pleb.get(username=plebeian) plebeians.append(to_pleb) except(CypherException, Pleb.DoesNotExist, DoesNotExist, IOError) as e: raise spawn_notifications.retry( exc=e, countdown=3, max_retries=100) response = create_notification_util(sb_object, from_pleb, plebeians, notification_id, url, action_name, public) if isinstance(response, Exception) is True: raise spawn_notifications.retry(exc=response, countdown=3, max_retries=100) return response
def get_conversation_authors(self): from plebs.neo_models import Pleb query = 'MATCH (a:Question {object_uuid: "%s"}) WITH a ' \ 'OPTIONAL MATCH (a)-[:POSSIBLE_ANSWER]->(solutions:Solution) ' \ 'WHERE solutions.to_be_deleted = false ' \ 'RETURN collect(a.owner_username) + ' \ 'collect(solutions.owner_username) as authors' % ( self.object_uuid) res, _ = db.cypher_query(query) authors = list(set(res.one)) author_list = [] for author in authors: pleb = Pleb.get(author) author_list.append("%s %s" % (pleb.first_name, pleb.last_name)) return ", ".join(author_list[::-1])
def update(self, instance, validated_data): """ The instance passed here much be a Campaign or any subclass of a Campaign :param instance: :param validated_data: :return: """ current_editors = cache.get("%s_editors" % instance.object_uuid, []) for profile in \ list(set(validated_data['profiles']) - set(current_editors)): profile_pleb = Pleb.get(username=profile) instance.editors.connect(profile_pleb) cache.delete("%s_editors" % instance.owner_username) return instance
def spawn_system_notification(to_plebs, notification_id, url, action_name): plebeians = [] for plebeian in to_plebs: try: to_pleb = Pleb.get(username=plebeian) plebeians.append(to_pleb) except(CypherException, Pleb.DoesNotExist, DoesNotExist, IOError) as e: raise spawn_notifications.retry( exc=e, countdown=3, max_retries=100) res = create_system_notification(plebeians, notification_id, url, action_name) if isinstance(res, Exception) is True: create_system_notification.retry(exc=res, countdown=3, max_retries=100) return res
def council_update(self, request, object_uuid=None): profile = Pleb.get(username=request.user.username) if request.user.username == "tyler_wiersing" \ or request.user.username == "devon_bleibtrey"\ or profile.reputation >= 10000: queryset = self.get_object() serializer = PositionSerializer( queryset, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response( {"detail": "You are not authorized to perform this action.", "status": status.HTTP_403_FORBIDDEN}, status.HTTP_403_FORBIDDEN)
def thumbnail(self, request, object_uuid=None): uploaded_object = self.get_object() img_file = urllib2.urlopen(uploaded_object.url) read_file = img_file.read() file_object = BytesIO(read_file) image = Image.open(file_object) image_format = image.format thumbnail_serializer = ThumbnailSerializer(data=request.data) if thumbnail_serializer.is_valid(): thumbnail_data = thumbnail_serializer.data else: return Response(thumbnail_serializer.errors, status=status.HTTP_400_BAD_REQUEST) thumbnailed_image = thumbnail_image(image, thumbnail_data['thumbnail_height'], thumbnail_data['thumbnail_width']) # Fill thumbnailed image into buffer file_stream = BytesIO() thumbnailed_image.save(file_stream, format=image_format) file_stream.seek(0) # Upload cropped pic and then run serializer # Not the best solution but simplifies the logic. If someone has a # better approach feel free to update. Perhaps an InMemoryFile passed # to the serializer file_name = "%s-%sx%s.%s" % ( object_uuid, thumbnail_data['thumbnail_width'], thumbnail_data['thumbnail_height'], image_format.lower()) serializer = upload_modified_image(file_name, file_stream.read(), request, object_uuid) if serializer.is_valid(): owner = Pleb.get(request.user.username) upload = serializer.save(owner=owner) profile_page_url = reverse( "profile_page", kwargs={"pleb_username": request.user.username}, request=request) return Response( { "status": "success", "url": upload.url, "profile": profile_page_url }, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): # TODO we don't have a way currently to distinguish what a Update is # about. Think it'll be based on an attribute submitted by the front # end. That will be based on where it's at (make update from Public # Office Mission vs Advocate Mission vs Quest vs etc) request, _, _, _, _ = gather_request_data(self.context) quest = validated_data.pop('quest', None) owner = Pleb.get(request.user.username) validated_data['owner_username'] = owner.username about = validated_data.pop('about', None) about_type = validated_data.get('about_type') validated_data['content'] = \ render_content(validated_data.get('content', '')) update = Update(**validated_data).save() quest.updates.connect(update) url = None if about_type == 'mission': update.mission.connect(about) url = reverse('mission_updates', kwargs={ 'object_uuid': about.object_uuid, 'slug': slugify(about.get_mission_title()) }) elif about_type == 'quest': update.quest.connect(about) cache.delete("%s_updates" % quest.object_uuid) task_params = { "sb_object": update.object_uuid, "to_plebs": quest.get_followers(), "from_pleb": request.user.username, "notification_id": str(uuid1()), "url": url, "action_name": "%s %s has made an Update on a Quest you follow!" % (request.user.first_name, request.user.last_name), "public": True } spawn_task(task_func=spawn_notifications, task_param=task_params) return update
def sagebrew_donation(request): if not Pleb.get(request.user.username).is_verified: return Response( { "detail": "You cannot donate to us unless you are verified.", "status": status.HTTP_401_UNAUTHORIZED, "developer_message": "A user may only donate on Sagebrew " "if they are verified." }, status=status.HTTP_401_UNAUTHORIZED) serializer = SBDonationSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save(token=request.data.get('token', None)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_profile(self, obj): from plebs.serializers import PlebSerializerNeo request, expand, _, relation, _ = gather_request_data( self.context, expedite_param=self.context.get('expedite_param', None), expand_param=self.context.get('expand_param', None)) owner_username = obj.owner_username if expand == "true": owner = Pleb.get(username=owner_username) profile_dict = PlebSerializerNeo(owner, context={ 'request': request }).data elif relation == 'hyperlink': profile_dict = reverse('profile-detail', kwargs={"username": owner_username}, request=request) else: profile_dict = obj.owner_username return profile_dict
def create(self, validated_data): request, _, _, _, _ = gather_request_data(self.context) product_ids = validated_data.get('product_ids', []) mission = validated_data.get('mission', None) total = validated_data.get('total', 0) owner = Pleb.get(request.user.username) order = Order(total=total, owner_username=owner.username).save() order.owner.connect(owner) order.mission.connect(mission) for product_id in product_ids: product = Product.nodes.get(object_uuid=product_id) product.orders.connect(order) message_data = { 'message_type': 'email', 'subject': 'Submit Mission For Review', 'body': 'Hi Team,\n%s has submitted an Order. ' 'Please review it in the <a href="%s">' 'council area</a>. ' % (order.owner_username, reverse('council_orders', request=self.context.get('request'))), 'template': "personal", 'from_user': { 'type': "admin", 'id': settings.INTERCOM_ADMIN_ID_DEVON }, 'to_user': { 'type': "user", 'user_id': settings.INTERCOM_USER_ID_DEVON } } serializer = IntercomMessageSerializer(data=message_data) if serializer.is_valid(): serializer.save() return order