Ejemplo n.º 1
0
def Outbox(request, username):
    target = get_object_or_404(User, username__iexact=username)
    if target.is_active == False:
        return HttpResponseGone()
    posts = target.posts.all()
    if "page" in request.GET:
        offset = int(request.GET.get("offset", 1))
        if offset <= 0:
            offset = 1
        pagenated = posts[settings.OBJECT_PER_PAGE *
                          (offset - 1):settings.OBJECT_PER_PAGE * offset]
        output = []
        for post in pagenated:
            output.append(
                RenderCreate(
                    post.uuid, post.parent.username,
                    RenderNote(post.uuid, post.posted.isoformat(
                    ), post.parent.username, post.body, [
                        "https://www.w3.org/ns/activitystreams#Public"
                    ], [
                        f"https://{settings.CP_ENDPOINT}{reverse('Fediverse:Followers', kwargs={'username': post.parent.username})}"
                    ])))
        return APResponse(
            APRender(
                RenderOrderedCollectionPage(
                    str(request.get_full_path()),
                    reverse('Fediverse:Outbox',
                            kwargs={"username": target.username}),
                    posts.count(),
                    output,
                    "".join([
                        reverse('Fediverse:Outbox',
                                kwargs={"username": target.username}), '?',
                        urlencode({
                            'page': 'true',
                            'offset': offset + 1
                        })
                    ]) if
                    (posts.count() - settings.OBJECT_PER_PAGE * offset) > 0
                    else None,
                    "".join([
                        reverse('Fediverse:Outbox',
                                kwargs={"username": target.username}), '?',
                        urlencode({
                            'page': 'true',
                            'offset': offset - 1
                        })
                    ]) if (offset - 1) > 0 else None,
                )))
    else:
        return APResponse(
            APRender(
                RenderOrderedCollection(
                    reverse('Fediverse:Outbox',
                            kwargs={"username": target.username}),
                    posts.count(), "".join([
                        reverse('Fediverse:Outbox',
                                kwargs={"username": target.username}), '?',
                        urlencode({'page': 'true'})
                    ]))))
Ejemplo n.º 2
0
def Following(request, username):
    target = get_object_or_404(User, username__iexact=username)
    if target.is_active == False:
        return HttpResponseGone()
    following = target.following.filter(is_pending=False)
    if "page" in request.GET:
        offset = int(request.GET.get("offset", 1))
        if offset <= 0:
            offset = 1
        pagenated = following[settings.USER_PER_PAGE * (offset - 1):settings.USER_PER_PAGE * offset]
        output = []
        for follow in pagenated:
            if follow.target != None:
                output.append(f"https://{settings.CP_ENDPOINT}{reverse('UserShow', kwargs={'username': follow.target.username})}")
            elif follow.targetFedi != None:
                output.append(follow.targetFedi.Uri)

        return APResponse(APRender(
            RenderOrderedCollectionPage(
                str(request.get_full_path()),
                reverse('Fediverse:Following', kwargs={"username": target.username}),
                following.count(),
                output,
                "".join([reverse('Fediverse:Following', kwargs={"username": target.username}), '?', urlencode({'page': 'true', 'offset': offset + 1})]) if (following.count() - settings.USER_PER_PAGE * offset) > 0 else None,
                "".join([reverse('Fediverse:Following', kwargs={"username": target.username}), '?', urlencode({'page': 'true', 'offset': offset - 1})]) if (offset - 1) > 0 else None,
            )
        ))
    else:
        return APResponse(APRender(
            RenderOrderedCollection(
                reverse('Fediverse:Following', kwargs={"username": target.username}),
                following.count(),
                "".join([reverse('Fediverse:Following', kwargs={"username": target.username}), '?', urlencode({'page': 'true'})])
            )
        ))
Ejemplo n.º 3
0
def UserFollower(request, username):
    targetUser = get_object_or_404(UserModel, username__iexact=username)
    if targetUser.is_active == False:
        return HttpResponseGone()
    renderObj = {
        "targetUser":
        targetUser,
        "targetUserFollower":
        panigateQuery(request, targetUser.followers.filter(is_pending=False),
                      settings.USER_PER_PAGE),
        "targetUserCount": {
            "following": targetUser.following.filter(is_pending=False).count(),
            "followers": targetUser.followers.filter(is_pending=False).count()
        }
    }
    if request.user.is_authenticated and request.user != targetUser:
        renderObj.update({
            "targetUserRelation": {
                "following":
                True if targetUser.followers.filter(fromUser=request.user,
                                                    is_pending=False).count()
                else False,
                "followed":
                True if targetUser.following.filter(
                    target=request.user, is_pending=False).count() else False,
                "followPending":
                True if targetUser.followers.filter(
                    fromUser=request.user, is_pending=True).count() else False,
                "blocked":
                True if targetUser.blocking.filter(
                    target=request.user).count() else False,
            }
        })
    return render_NPForm(request, "profile_follower.html", renderObj)
Ejemplo n.º 4
0
def postDetail(request, uuid):
    post = get_object_or_404(PostModel, uuid=uuid)
    if post.parent != None and post.parent.is_active == False:
        return HttpResponseGone()
    obj = {"post": post}
    if post.announceTo == None:
        obj.update({"scraped_body": scraping(post.body)})
    else:
        obj.update({"scraped_body": f"AN: {scraping(post.announceTo.body)}"})
    return render_NPForm(request, "postDetail.html", obj)
Ejemplo n.º 5
0
def PdfgenDownload(request, pk):
    try:
        pdfgen = Pdfgen.objects.get(pk=pk)
    except Pdfgen.DoesNotExist:
        return HttpResponseNotFound()

    if pdfgen.rendered_file:
        return HttpResponse(pdfgen.rendered_file,
                            content_type='application/pdf')
    else:
        return HttpResponseGone()
Ejemplo n.º 6
0
    def redirect(self, url=None, message=None, *args, **kwargs):
        url = self.get_redirect_url(url, *args, **kwargs)
        if url:
            if message:
                self.set_message(message)

            if self.permanent:
                return HttpResponsePermanentRedirect(url)
            else:
                return HttpResponseRedirect(url)
        else:
            return HttpResponseGone()
Ejemplo n.º 7
0
 def get(self, request, **kwargs):
     _path = json.loads(kwargs["hash"])["path"]
     if os.path.exists(_path):
         act_resp = HttpResponse(content_type="image/png")
         act_resp["Content-disposition"] = "attachment; filename=graph.png"
         act_resp["Content-Transfer-Encoding"] = "binary"
         # print dir(act_resp)
         act_resp.write(file(_path, "rb").read())
         # print len(act_resp.content)
     else:
         # hm, working ... ?
         act_resp = HttpResponseGone()
     return act_resp
Ejemplo n.º 8
0
def guess_ajax(request, user_id, game_id, g1, g2):
    user_id = int(user_id)
    game_id = int(game_id)
    g1 = int(g1)
    g2 = int(g2)
    if user_id != request.user.id:
        return HttpResponseForbidden()
    game = Game.objects.filter(closed=None, id=game_id)[:1]
    if len(game) == 0:
        return HttpResponseGone()

    result = update_single_guess(user_id, game_id, tuple((g1, g2)))
    return JsonResponse({'created': result[1]})
Ejemplo n.º 9
0
def parcel_withdraw_application(request, parcel_id):
    # submit an application to withdraw parcel.
    context_dict = {}
    parcel = get_object_or_404(Parcel, pk=parcel_id)
    if not parcel.recipient == request.user:
        return HttpResponseForbidden()
    else:
        pa = parcel.add_activity(
            locker_base=None,
            activity_type=ParcelActivity.ActivityType.WITHDRAWAPP)
        if isinstance(pa, ParcelActivity):
            context_dict["qr_data"] = parcel.make_retrieval_code()
            return render(request,
                          "parcel/withdraw.html",
                          context=context_dict)
        else:
            return HttpResponseGone()
Ejemplo n.º 10
0
def InboxUser(request, username):
    target = get_object_or_404(User, username__iexact=username)
    if target.is_active == False:
        return HttpResponseGone()

    if request.META.get('HTTP_SIGNATURE') == None:
        return HttpResponseNotFound()

    if request.META.get("CONTENT_TYPE").startswith(
            "application/activity+json") or request.META.get(
                "CONTENT_TYPE").startswith("application/ld+json"):
        pass
    else:
        logging.warn("Content-Type is not ActivityPub")
        return HttpResponseBadRequest()

    signature = parse_signature(request.META.get("HTTP_SIGNATURE"))
    host = urlparse(signature["keyId"])

    try:
        apbody = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        logging.error("JSON decode error")
        return HttpResponseBadRequest()

    if not isAPContext(apbody):
        logging.error("It is not ActivityPub content")
        return HttpResponseBadRequest()

    apbody.pop("@context")

    try:
        fromUser = FediverseUser.objects.get(Uri=apbody["actor"])  # pylint: disable=no-member
    except ObjectDoesNotExist:
        fromUser = registerFediUser(apbody["actor"])
        if fromUser == False:
            logging.warn("Fediverse user fetch failed.")
            return HttpResponseBadRequest()
        else:
            fromUser.save()

    if fromUser.is_suspended == True:
        logging.warn("This user is suspended in this server.")
        if apbody["type"] == "Follow":
            APSend.delay(fromUser.Inbox, target.username,
                         RenderReject(target.username, apbody["object"]))
        return HttpResponse(status=202)

    for bd in BlackDomain.objects.all():  # pylint: disable=no-member
        if host.netloc == bd.targetDomain:
            logging.warn(
                f"ActivityPub Received, but it is blacklisted domain: {host.netloc}"
            )
            if apbody["type"] == "Follow":
                APSend.delay(fromUser.Inbox, target.username,
                             RenderReject(target.username, apbody["object"]))
            return HttpResponse(status=202)

    logging.info("ActivityPub Recieved: ")
    logging.info(pformat(apbody))

    if apbody.get("type") == None or type(apbody.get("type")) != str:
        return HttpResponseBadRequest()

    if apbody["type"] == "Follow":
        return _FollowActivity(apbody, fromUser, target)
    elif apbody["type"] == "Create":
        return _CreateActivity(apbody, fromUser)
    elif apbody["type"] == "Like":
        return _LikeActivity(apbody, fromUser, target)
    elif apbody["type"] == "Accept":
        if apbody["object"].get("type") == "Follow":
            res = re.search(
                f"^https://{settings.CP_ENDPOINT}{reverse('UserShow', kwargs={'username': '******'})}#follow_(.+)",
                apbody["object"]["id"])
            if res == None:
                logging.error("Follow parse error.")
                return HttpResponse(status=202)
            uuid = res.group(2)
            try:
                followObj = Follow.objects.get(uuid=uuid)  # pylint: disable=no-member
                followObj.is_pending = False
                followObj.save()
                logging.info("Follow was accepted")
                return HttpResponse(status=202)
            except ObjectDoesNotExist:
                logging.warn("Follow object was not found")
                return HttpResponse(status=202)
        else:
            logging.info("Accept activity recieved, but type work is unknown.")
        return HttpResponse(status=202)
    elif apbody["type"] == "Reject":
        if apbody["object"].get("type") == "Follow":
            res = re.search(
                f"^https://{settings.CP_ENDPOINT}{reverse('UserShow', kwargs={'username': '******'})}#follow_(.+)",
                apbody["object"]["id"])
            if res == None:
                logging.error("Follow parse error.")
                return HttpResponse(status=202)
            uuid = res.group(2)
            try:
                followObj = Follow.objects.get(uuid=uuid)  # pylint: disable=no-member
                followObj.delete()
                logging.info("Follow was rejected")
                return HttpResponse(status=202)
            except ObjectDoesNotExist:
                logging.warn("Follow object was not found")
                return HttpResponse(status=202)
        else:
            logging.info("Reject activity recieved, but type work is unknown.")
        return HttpResponse(status=202)
    elif apbody["type"] == "Announce":
        return _AnnounceActivity(apbody, fromUser, target)
    elif apbody["type"] == "Block":
        return _BlockActivity(apbody, fromUser, target)
    elif apbody["type"] == "Delete":
        if apbody["object"].get("type") == "Tombstone":
            return _DeletePostActivity(apbody, fromUser, target)
    elif apbody["type"] == "Undo":
        if apbody["object"]["type"] == "Follow":
            return _FollowActivity(apbody, fromUser, target, True)
        elif apbody["object"]["type"] == "Like":
            return _LikeActivity(apbody, fromUser, target, True)
        elif apbody["object"]["type"] == "Block":
            return _BlockActivity(apbody, fromUser, target, True)

    logging.error(f"Sorry, this type is not implemented!: {apbody['type']}")
    return HttpResponse(status=202)
Ejemplo n.º 11
0
def Key(request, username):
    if get_object_or_404(User, username__iexact=username).is_active == False:
        return HttpResponseGone()
    return APResponse(APRender(RenderKey(username)))