def get(self, *args, **kwargs): comm = self.request.GET.get('comment') # post_id=self.request.GET.get('id') post_slug = self.request.GET.get('post_slug') post_username = self.request.GET.get('post_username') now = datetime.datetime.now() new_slug = now.strftime("%Y-%m-%d-%H%M") slug = slugify(comm) + new_slug user = self.request.user #post = Post.objects.get(id=post_id) comment = Comment(author=user.username, body=comm, permlink=slug, title='', parent_permlink=post_slug, parent_author=post_username, json_metadata={"app": "sportherald.app"}) #pdb.set_trace() profile = Profile.objects.get(user=user) com = get_c(profile) rich = com.broadcast([comment.to_operation_structure()]) #pdb.set_trace() return JsonResponse({ 'status': 200, 'message': 'Successfully Updated', })
def get_comment(request, question, choices, permlink, tags=None): post_tags = copy.copy(settings.DEFAULT_TAGS) if tags: post_tags += tags comment = Comment(author=request.user.username, permlink=question.permlink, body=get_body( question, choices, request.user.username, permlink, ), title=question.text, parent_permlink=settings.COMMUNITY_TAG, json_metadata={ "tags": post_tags, "app": f"dpoll/{settings.DPOLL_APP_VERSION}", "content_type": "poll", "question": question.text, "description": question.description or "", "choices": choices, "expire_at": str(question.expire_at), "allow_multiple_choices": str(question.allow_multiple_choices), }) return comment
def create_post(): data_dict = json.loads(request.data) if 'user_id' not in data_dict: raise BadRequest('user_id is mandatory param') if 'title' not in data_dict: raise BadRequest('title is mandatory param') if 'body' not in data_dict: raise BadRequest('body is mandatory param') user_id = data_dict['user_id'] title = data_dict['title'] body = data_dict['body'] force_permlink = data_dict[ 'force_permlink'] if 'force_permlink' in data_dict else '' cover_image_url = data_dict.get('cover_image_url', '') user = User.query.filter_by(user_id=user_id).first() if not user: raise Unauthorized('Not authorized with steemconnect') client = Client(access_token=user.steem_token) permlink = force_permlink or title.lower().replace(' ', '-')\ .replace('_', '-')\ .replace(')', '-')\ .replace('(', '-')\ .encode('ascii', 'ignore') if not permlink or len(permlink) < 4: permlink = str(uuid4()) comment = Comment( user.user_id, permlink, "Make donations/tipping easy <a href=\"http://donatenow.io\">donatenow!</a>", title=title, json_metadata={ "app": app_name, "body": body, "cover_image_url": cover_image_url }) r = client.broadcast([comment.to_operation_structure()]) if 'error_description' in r and r['error_description']: raise BadRequest(r['error_description']) all_posts = get_all(user_id) post = all_posts['posts'][permlink] response = Response(json.dumps(post), mimetype='application/json') response.headers.add('Access-Control-Allow-Origin', '*') return response
def r_broadcastcomment(yon): try: global comment, posts, Option if yon == 'Yes': finalcomment = Comment( sc.me()["name"], #author randomperm(10), #permlink comment, #body parent_author=posts[Option]['author'], parent_permlink=posts[Option]['permlink'], ) sc.broadcast([finalcomment.to_operation_structure()]) return ask('broadcasting %s to %s' % (comment, posts[Option]['title'])) else: return ask('Canceling comment') except: # If the user didn't connect his account return ask('Please connect your account before using this command')
def post(self, request, *args, **kwargs): id = request.POST.get('id') status = request.POST.get('status') comment = request.POST.get('comment') try: post = Post.objects.get(id=id) post.status = status post.approved_date = timezone.now() post.save() posts = Post.objects.filter( status='submitted')[:settings.PAGE_LENGTH] response = render_to_string('includes/post_list.html', { 'posts': posts, 'page': 'review' }) now = datetime.datetime.now() new_slug = now.strftime("%Y-%m-%d-%H%M") slug = slugify(comment) + new_slug if not self.request.user.username == 'admin': # remember to remove in production user = self.request.user else: user = User.objects.get(username='******') comment = Comment(author=user.username, body=comment, permlink=slug, title='', parent_permlink=post.slug, parent_author=post.author.username, json_metadata={"app": "sportherald.app"}) profile = Profile.objects.get(user=user) com = get_c(profile) rich = com.broadcast([comment.to_operation_structure()]) #pdb.set_trace() return JsonResponse({ 'status': 200, 'message': 'Successfully Updated', 'data': response }) except Post.DoesNotExist: return JsonResponse({'status': 404, 'message': 'Post not found'})
def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user tags = self.request.POST.get('tags') tags_list = tags.split(',') post.status = 'submitted' if not self.request.user.username == 'admin': # remember to remove in production user = self.request.user else: user = User.objects.get(username='******') profile = Profile.objects.get(user=user) status = post.save() if status == 'Exist': messages.warning(self.request, 'Value Error, Use a different title ') #pdb.set_trace() return HttpResponseRedirect('/') form.save_m2m() cli = get_c(profile) comment = Comment(author=user.username, permlink=post.slug, body=post.body, title=post.title, parent_permlink="sportherald", json_metadata={ "app": "sportherald.app", 'tags': tags_list }) try: rich = cli.broadcast([comment.to_operation_structure()]) messages.success(self.request, 'Post Submitted and under review') #pdb.set_trace() except: messages.warning(self.request, 'Network Error') #pdb.set_trace() #return JsonResponse({'status': 200, 'slug': post.slug, 'posting_key': posting_key, 'username': user.username}) return HttpResponseRedirect('/')
def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user tags = self.request.POST.get('tags') tags_list = tags.split(',') post.status = 'submitted' post.save() form.save_m2m() messages.success(self.request, 'Post Submitted and under review') if not self.request.user.username == 'admin': # remember to remove in production user = self.request.user else: user = User.objects.get(username='******') profile = Profile.objects.get(user=user) posting_key = profile.posting_key refresh_token = profile.refresh_token url = "https://v2.steemconnect.com/api/oauth2/token" response_access = requests.post(url, data={ 'refresh_token': refresh_token, 'client_id': 'sportherald.app', 'client_secret': settings.CLIENT_SECRET, 'scope': "vote,comment,offline" }) access_token = response_access.json().get('access_token') c = Client(access_token=access_token) comment = Comment(author=user.username, permlink=post.slug, body=post.body, title=post.title, parent_permlink="sportherald", json_metadata={ "app": "sportherlad.app", 'tags': tags_list }) c.broadcast([comment.to_operation_structure()]) #return JsonResponse({'status': 200, 'slug': post.slug, 'posting_key': posting_key, 'username': user.username}) return HttpResponseRedirect('/')
def steemconnect_post(self, op_name): context = dict( image=self.get_first_image(soup=self.marktohtml(self.body)), username=self.username, permlink=self.permlink, ) comment = Comment( parent_author="", parent_permlink="coogger", author=str(self.user.username), permlink=self.permlink, title=self.title, body=render_to_string("post/steem-post-note.html", context), json_metadata=dict(format="markdown", tags=self.tags.split(), app="coogger/1.4.1", ecosystem=dict( version="1.4.1", body=self.body, )), ) if op_name == "save": if self.get_user_beneficiaries != []: comment_options = CommentOptions( parent_comment=comment, beneficiaries=self.get_user_beneficiaries) operation = comment_options.operation else: operation = comment.operation elif op_name == "update": operation = comment.operation steem_connect_user = SteemConnectUser.objects.filter(user=self.user) try: access_token = steem_connect_user[0].access_token return SteemConnect(token=access_token, data=operation).run except: access_token = steem_connect_user.update_access_token( settings.APP_SECRET) return SteemConnect(token=access_token, data=operation).run
def create_poll(request): if not request.user.is_authenticated: return redirect('login') error = False # @todo: create a form class for that. this is very ugly. if request.method == 'POST': if not 'sc_token' in request.session: return redirect("/") required_fields = ["question", "answers[]", "expire-at"] for field in required_fields: if not request.POST.get(field): error = True messages.add_message(request, messages.ERROR, f"{field} field is required.") question = request.POST.get("question") choices = request.POST.getlist("answers[]") expire_at = request.POST.get("expire-at") if question: if not (4 < len(question) < 256): messages.add_message( request, messages.ERROR, "Question text should be between 6-256 chars.") error = True if 'choices' in request.POST: if len(choices) < 2: messages.add_message(request, messages.ERROR, f"At least 2 choices are required.") error = True elif len(choices) > 20: messages.add_message(request, messages.ERROR, f"Maximum number of choices is 20.") error = True if 'expire-at' in request.POST: if expire_at not in ["1_week", "1_month"]: messages.add_message(request, messages.ERROR, f"Invalid expiration value.") error = True if error: return render(request, "add.html") days = 7 if expire_at == "1_week" else 30 # add the question permlink = slugify(question)[0:256] if not permlink: permlink = str(uuid.uuid4()) # @todo: also check for duplicates in the blockchain. # client.get_content() if (Question.objects.filter(permlink=permlink, username=request.user)).exists(): messages.add_message(request, messages.ERROR, "You have already a similar poll.") return redirect('create-poll') question = Question(text=question, username=request.user.username, description=request.POST.get("description"), permlink=permlink, expire_at=now() + timedelta(days=days)) question.save() # add answers attached to it for choice in choices: choice_instance = Choice( question=question, text=choice, ) choice_instance.save() # send it to the steem blockchain sc_client = Client(access_token=request.session.get("sc_token")) comment = Comment(author=request.user.username, permlink=question.permlink, body=get_body( question, choices, request.user.username, permlink, ), title=question.text, parent_permlink=settings.COMMUNITY_TAG, json_metadata={ "tags": settings.DEFAULT_TAGS, "app": f"dpoll/{settings.DPOLL_APP_VERSION}", "content_type": "poll", "question": question.text, "description": question.description or "", "choices": choices, "expire_at": str(question.expire_at), }) comment_options = get_comment_options(comment) resp = sc_client.broadcast([ comment.to_operation_structure(), comment_options.to_operation_structure(), ]) if 'error' in resp: if 'The token has invalid role' in resp.get("error_description"): # expired token auth_logout(request) return redirect('login') messages.add_message(request, messages.ERROR, resp.get("error_description", "error")) question.delete() return redirect('create-poll') return redirect('detail', question.username, question.permlink) return render(request, "add.html")
def vote(request, user, permlink): if request.method != "POST": raise Http404 # django admin users should not be able to vote. if not request.session.get("sc_token"): redirect('logout') try: poll = Question.objects.get(username=user, permlink=permlink) except Question.DoesNotExist: raise Http404 if not request.user.is_authenticated: return redirect('login') choice_id = request.POST.get("choice-id") additional_thoughts = request.POST.get("vote-comment", "") if not choice_id: raise Http404 if Choice.objects.filter(voted_users__username=request.user, question=poll).exists(): messages.add_message(request, messages.ERROR, "You have already voted for this poll!") return redirect("detail", poll.username, poll.permlink) if not poll.is_votable(): messages.add_message(request, messages.ERROR, "This poll is expired!") return redirect("detail", poll.username, poll.permlink) try: choice = Choice.objects.get(pk=int(choice_id)) except Choice.DoesNotExist: raise Http404 choice.voted_users.add(request.user) # send it to the steem blockchain sc_client = Client(access_token=request.session.get("sc_token")) choice_text = choice.text.strip() body = f"Voted for *{choice_text}*." if additional_thoughts: body += f"\n\n{additional_thoughts}" comment = Comment(author=request.user.username, permlink=str(uuid.uuid4()), body=body, parent_author=poll.username, parent_permlink=poll.permlink, json_metadata={ "tags": settings.DEFAULT_TAGS, "app": f"dpoll/{settings.DPOLL_APP_VERSION}", "content_type": "poll_vote", "vote": choice.text }) comment_options = get_comment_options(comment) resp = sc_client.broadcast([ comment.to_operation_structure(), comment_options.to_operation_structure(), ]) if 'error' in resp: messages.add_message(request, messages.ERROR, resp.get("error_description", "error")) choice.voted_users.remove(request.user) return redirect("detail", poll.username, poll.permlink) messages.add_message(request, messages.SUCCESS, "You have successfully voted!") return redirect("detail", poll.username, poll.permlink)
def vote(request, user, permlink): if request.method != "POST": raise Http404 # django admin users should not be able to vote. if not request.session.get("sc_token"): redirect('logout') try: poll = Question.objects.get(username=user, permlink=permlink) except Question.DoesNotExist: raise Http404 if not request.user.is_authenticated: return redirect('login') if poll.allow_multiple_choices: choice_ids = request.POST.getlist("choice-id") else: choice_ids = [ request.POST.get("choice-id"), ] # remove noise choice_ids = [x for x in choice_ids if x is not None] additional_thoughts = request.POST.get("vote-comment", "") if not len(choice_ids): messages.add_message(request, messages.ERROR, "You need to pick a choice to vote.") return redirect("detail", poll.username, poll.permlink) if Choice.objects.filter(voted_users__username=request.user, question=poll).exists(): messages.add_message(request, messages.ERROR, "You have already voted for this poll!") return redirect("detail", poll.username, poll.permlink) if not poll.is_votable(): messages.add_message(request, messages.ERROR, "This poll is expired!") return redirect("detail", poll.username, poll.permlink) for choice_id in choice_ids: try: choice = Choice.objects.get(pk=int(choice_id)) except Choice.DoesNotExist: raise Http404 choice_instances = [] for choice_id in choice_ids: choice = Choice.objects.get(pk=int(choice_id)) choice_instances.append(choice) # send it to the steem blockchain sc_client = Client(access_token=request.session.get("sc_token")) choice_text = "" for c in choice_instances: choice_text += f" - {c.text.strip()}\n" body = f"Voted for \n {choice_text}" if additional_thoughts: body += f"\n\n{additional_thoughts}" comment = Comment(author=request.user.username, permlink=str(uuid.uuid4()), body=body, parent_author=poll.username, parent_permlink=poll.permlink, json_metadata={ "tags": settings.DEFAULT_TAGS, "app": f"dpoll/{settings.DPOLL_APP_VERSION}", "content_type": "poll_vote", "votes": [c.text.strip() for c in choice_instances], }) comment_options = get_comment_options(comment) if not settings.BROADCAST_TO_BLOCKCHAIN: resp = {} else: resp = sc_client.broadcast([ comment.to_operation_structure(), comment_options.to_operation_structure(), ]) # Steemconnect sometimes returns 503. # https://github.com/steemscript/steemconnect/issues/356 if not isinstance(resp, dict): messages.add_message( request, messages.ERROR, "We got an unexpected error from Steemconnect. Please, try again.") return redirect("detail", poll.username, poll.permlink) # Expected way to receive errors on broadcasting if 'error' in resp: messages.add_message(request, messages.ERROR, resp.get("error_description", "error")) return redirect("detail", poll.username, poll.permlink) # register the vote to the database for choice_instance in choice_instances: choice_instance.voted_users.add(request.user) block_id = resp.get("result", {}).get("block_num") trx_id = resp.get("result", {}).get("id") # add trx id and block id to the audit log vote_audit = VoteAudit(question=poll, voter=request.user, block_id=block_id, trx_id=trx_id) vote_audit.save() for choice_instance in choice_instances: vote_audit.choices.add(choice_instance) messages.add_message(request, messages.SUCCESS, "You have successfully voted!") return redirect("detail", poll.username, poll.permlink)
def steemconnect_post(self, permlink, json_metadata): def_name = json_metadata if json_metadata == "save": self.content += "\n" + self.community.ms.format( self.get_absolute_url()) json_metadata = { "format": "markdown", "tags": self.tag.split(), "app": "coogger/1.3.9", "ecosystem": "coogger", "community": self.community.name, "topic": self.topic, "category": self.category, "language": self.language, "dor": self.dor, } comment = Comment( parent_permlink=self.community.name, author=str(self.user.username), permlink=permlink, title=self.title, body=self.content, json_metadata=json_metadata, ) if def_name == "save": beneficiaries_weight = OtherInformationOfUsers.objects.filter( user=self.user)[0].beneficiaries beneficiaries_weight = round(float(beneficiaries_weight), 3) if beneficiaries_weight >= 15: ben_weight = beneficiaries_weight * 100 - 1000 if self.community.name == "coogger": beneficiaries = [ { "account": "hakancelik", "weight": ben_weight + 1000 }, ] else: beneficiaries = [{ "account": "hakancelik", "weight": ben_weight + 500 }, { "account": self.community.name, "weight": 500 }] comment_options = CommentOptions(comment_class=comment, beneficiaries=beneficiaries) operation = comment_options.operation elif beneficiaries_weight < 15 and beneficiaries_weight > 0: ben_weight = beneficiaries_weight * 100 / 3 if self.community.name == "coogger": beneficiaries = [ { "account": "hakancelik", "weight": 3 * ben_weight }, ] else: beneficiaries = [{ "account": "hakancelik", "weight": 2 * ben_weight }, { "account": self.community.name, "weight": ben_weight }] comment_options = CommentOptions(comment_class=comment, beneficiaries=beneficiaries) operation = comment_options.operation else: operation = comment.operation else: operation = comment.operation steem_connect_user = SteemConnectUser.objects.filter(user=self.user) try: access_token = steem_connect_user[0].access_token return SteemConnect(token=access_token, data=operation).run except: sc_community_name = steem_connect_user[0].community_name secret = Community.objects.filter( name=sc_community_name)[0].app_secret access_token = steem_connect_user.set_new_access_token(secret) return SteemConnect(token=access_token, data=operation).run