Exemplo n.º 1
0
def channels(request):
    # Comprobamos si el usuario quiere loguearse o desloguearse
    if do_login_logout(request):
        return HttpResponseRedirect(request.path)

    if request.user.is_authenticated():
        if request.method == 'POST':
            # En el caso de que estemos en /canales
            if request.path == '/canales':
                rss = (str(request.POST)).split("'")[3]
                add_channel(request, rss)
                return HttpResponseRedirect(request.path)
            # En el caso de que estemos en /canales/(numero)
            else:
                # si salta la excepcion es porque no hay nada en el POST
                # y por tanto nos piden actualizar el canal.
                # si no salta la excepcion, entoces es porque
                # nos piden seguir una noticia
                try:
                    action = (str(request.POST)).split("'")[1]
                except IndexError:
                    # sacamos el numero del path
                    num = (request.path).split('/')[2]
                    try:
                        channel = Channels.objects.get(id=num)
                    except Channels.DoesNotExist:
                        return HttpResponseNotFound('404 Not Found')
                    rss = channel.RSS
                    # Esta funcion tambien actualiza los canales
                    add_channel(request, rss)
                    return HttpResponseRedirect(request.path)

                # sacamos el link de la noticia y lo usamos como identificador
                new_link = (str(request.POST)).split("'")[3]
                try:
                    record = News.objects.get(url=new_link)
                except News.DoesNotExist:
                    return show_annotated_content(
                        request, "Error: new's url does not found")

                #sacamos el id del ususario que se encuentra logueado
                try:
                    user = User.objects.get(username=str(request.user))
                except User.DoesNotExist:
                    return show_annotated_content(
                        request, "Error: User does not found")

                # Contamos el numero de noticias que sigue el user
                n = New_User.objects.filter(UserId=user.id)
                if len(n) == 10:
                    delete_object = New_User.objects.get(id=n[0].id)
                    delete_object.delete()

                # por defecto se incluye la noticia
                action = 'add'

                # comprobamos si la noticia se a incluido, en tal caso, debemos comprobar
                # si la ha incluido el user actual u otro
                new = New_User.objects.filter(NewId=record.id)

                if len(new) > 0:
                    for n in new:
                        if str(n.UserId) == str(user.id):
                            action = 'donotadd'
                            break

                if action == 'add':
                    # Incluimos la noticia a la tabla de noticias seguidas
                    follow_new = New_User(NewId=record.id,
                                          UserId=user.id,
                                          date=str(datetime.datetime.now()))
                    follow_new.save()

                    # Actualizamos la conf del user, si el usuario no existe, se crea su revista
                    try:
                        user_conf = User_Conf.objects.get(
                            user_name=user.username)
                    except User_Conf.DoesNotExist:
                        create_user_conf(user.username)
                        user_conf = User_Conf.objects.get(
                            user_name=user.username)

                    # Actualizazmos el user_conf del usuario
                    user_conf.last_updated = str(datetime.datetime.now())
                    user_conf.save()

                return HttpResponseRedirect(request.path)

        elif request.method == 'GET':
            # En el caso de que estemos en /canales
            if request.path == '/canales':
                body = ''
                Channels_list = Channels.objects.all().order_by('last_updated')
                for channel in reversed(Channels_list):
                    body += channel.presentation

                return show_annotated_content(request, body)

            # En el caso de que estemos en /canales/(numero)
            else:
                # sacamos el numero del path
                num = (request.path).split('/')[2]
                # contador para recorrer la tabla de noticias
                count = 1
                # Sacamos el titulo del canal
                try:
                    channel = Channels.objects.get(id=num)
                    body = '<h2 class="title"><a href="' + channel.url + '">' + channel.title + '</a></h2>' + \
                           '<form name="input" action="" method="POST">' + \
                               '<input class="more" type="submit" value="Update">' + \
                           '</form>' + \
                           '<a href="' + channel.RSS + '">(canal)</a>' + \
                           '<br><br>'
                except Channels.DoesNotExist:
                    return HttpResponseNotFound('404 Not Found')

                # mostramos las noticias con el ID del canal
                News_Channel_list = News_Channels.objects.filter(ChannelId=num)
                for New_Channel in reversed(News_Channel_list):
                    new = News.objects.get(id=New_Channel.NewId)
                    body += new.presentation

                return show_annotated_content(request, body)

        else:
            return HttpResponseNotAllowed('405 REQUEST METHOD NOT ALLOWED')

    # En caso de que no haya un user autenticado
    else:
        if request.method == 'POST':
            do_login_logout(request)
            return HttpResponseRedirect(request.path)
        else:
            return show_annotated_content(request,
                                          'Please Login to enjoy this page')
Exemplo n.º 2
0
def channels(request):
    # Comprobamos si el usuario quiere loguearse o desloguearse
    if do_login_logout(request):
        return HttpResponseRedirect(request.path)

    if request.user.is_authenticated():
        if request.method == 'POST':
            # En el caso de que estemos en /canales
            if request.path == '/canales':
                rss = (str(request.POST)).split("'")[3]
                add_channel(request, rss)
                return HttpResponseRedirect(request.path)
            # En el caso de que estemos en /canales/(numero)
            else:
                # si salta la excepcion es porque no hay nada en el POST
                # y por tanto nos piden actualizar el canal.
                # si no salta la excepcion, entoces es porque
                # nos piden seguir una noticia
                try:
                    action = (str(request.POST)).split("'")[1]
                except IndexError:
                    # sacamos el numero del path
                    num = (request.path).split('/')[2]
                    try:
                        channel = Channels.objects.get(id=num)
                    except Channels.DoesNotExist:
                        return HttpResponseNotFound('404 Not Found')
                    rss = channel.RSS
                    # Esta funcion tambien actualiza los canales
                    add_channel(request, rss)
                    return HttpResponseRedirect(request.path)
                
                # sacamos el link de la noticia y lo usamos como identificador
                new_link = (str(request.POST)).split("'")[3]
                try:
                    record = News.objects.get(url=new_link)
                except News.DoesNotExist:
                    return show_annotated_content(request, "Error: new's url does not found")
    
                #sacamos el id del ususario que se encuentra logueado
                try:
                    user = User.objects.get(username=str(request.user))
                except User.DoesNotExist:
                    return show_annotated_content(request, "Error: User does not found")

                # Contamos el numero de noticias que sigue el user
                n = New_User.objects.filter(UserId=user.id)
                if len(n) == 10:
                    delete_object = New_User.objects.get(id=n[0].id)
                    delete_object.delete()
                    
                # por defecto se incluye la noticia
                action = 'add'

                # comprobamos si la noticia se a incluido, en tal caso, debemos comprobar
                # si la ha incluido el user actual u otro
                new = New_User.objects.filter(NewId=record.id)

                if len(new) > 0:
                    for n in new:
                        if str(n.UserId) == str(user.id):
                            action = 'donotadd'
                            break

                if action == 'add':
                    # Incluimos la noticia a la tabla de noticias seguidas
                    follow_new = New_User(NewId=record.id, UserId=user.id, date=str(datetime.datetime.now()))
                    follow_new.save()

                    # Actualizamos la conf del user, si el usuario no existe, se crea su revista
                    try:
                        user_conf = User_Conf.objects.get(user_name=user.username)
                    except User_Conf.DoesNotExist:
                        create_user_conf(user.username)
                        user_conf = User_Conf.objects.get(user_name=user.username)

                    # Actualizazmos el user_conf del usuario
                    user_conf.last_updated = str(datetime.datetime.now())
                    user_conf.save()

                return HttpResponseRedirect(request.path)
    
        elif request.method == 'GET':
            # En el caso de que estemos en /canales
            if request.path == '/canales':
                body = ''
                Channels_list = Channels.objects.all().order_by('last_updated')
                for channel in reversed(Channels_list):
                    body += channel.presentation

                return show_annotated_content(request, body)

            # En el caso de que estemos en /canales/(numero)
            else:
                # sacamos el numero del path
                num = (request.path).split('/')[2]
                # contador para recorrer la tabla de noticias
                count = 1
                # Sacamos el titulo del canal
                try:
                    channel = Channels.objects.get(id=num)
                    body = '<h2 class="title"><a href="' + channel.url + '">' + channel.title + '</a></h2>' + \
                           '<form name="input" action="" method="POST">' + \
                               '<input class="more" type="submit" value="Update">' + \
                           '</form>' + \
                           '<a href="' + channel.RSS + '">(canal)</a>' + \
                           '<br><br>'
                except Channels.DoesNotExist:
                    return HttpResponseNotFound('404 Not Found')
    

                # mostramos las noticias con el ID del canal
                News_Channel_list = News_Channels.objects.filter(ChannelId=num)
                for New_Channel in reversed(News_Channel_list):
                    new = News.objects.get(id=New_Channel.NewId)
                    body += new.presentation

                return show_annotated_content(request, body)

        else:
            return HttpResponseNotAllowed('405 REQUEST METHOD NOT ALLOWED')

    # En caso de que no haya un user autenticado
    else:
        if request.method == 'POST':
            do_login_logout(request)
            return HttpResponseRedirect(request.path)
        else:
            return show_annotated_content(request, 'Please Login to enjoy this page')
Exemplo n.º 3
0
def server(request, resource):
    if do_login_logout(request):
        return HttpResponseRedirect(request.path)

    body = ''
    if request.method == 'GET':
        # Me estan pidiendo el recurso /
        if resource == '':
            body = ''
            journals_list = User_Conf.objects.all().order_by('last_updated')
            for journal in journals_list:
                body = '<div class="post"> ' + \
                           '<h2 class="title"><a href="/' + journal.user_name + '">' + journal.journal_title + '</a></h2>' + \
                           '<div style="clear: both;">&nbsp;</div>' + \
                           '<div class="entry">User: '******'</div>' + \
                           '<div class="entry">' + str(journal.last_updated) + '</div>' + \
                       '</div>' + body
            return show_annotated_content(request, body)
        else:
            # Se comprueba si el recurso que me piden coincide con algun /usuario existente
            try:
                user = User.objects.get(username=resource)
            except User.DoesNotExist:
                return HttpResponseNotFound('404 Not Found')

            # se procede a listar las noticias que sigue el usuario
            # Sacamos el id del usuario al que pertenece la revista
            try:
                user = User.objects.get(username=str(resource))
            except User.DoesNotExist:
                return show_annotated_content(request,
                                              "Error: User does not found")

            # Nos quedamos solamente con el id de las noticias del usuario al que pertenece la revista
            news = New_User.objects.filter(UserId=user.id)

            for n in reversed(news):
                # Sacamos el canal para concatenar su titulo y su id en la presentacion de la noticia
                new_channel = News_Channels.objects.get(NewId=n.NewId)
                channel = Channels.objects.get(id=new_channel.ChannelId)
                # Sacamos la noticia para concatenar sus campos en la presentacion
                new = News.objects.get(id=str(n.NewId))
                body += concatenate_new_presentation(request, channel.id,
                                                     channel.title, new.id,
                                                     new.title, new.contenido,
                                                     new.url, new.PubDate,
                                                     n.date)

            presentation = '<h3>Comments</h3><div class="post">'
            # Sacamos los comentarios que haya de esa revista y los preparamos en formato html
            comments = Comments.objects.filter(
                Users_Journal=str(request.path)[1:])
            for n in reversed(comments):
                presentation += '<div class="entry">' + n.Comment + '</div>'

            body += presentation + '</div>'

            # Incluimos en el body, el formulario para comentarios, en caso de que sea un usuario logueado
            if request.user.is_authenticated():
                body += '<form action="" method="post">' + \
                            'Title:</br> <input type="text" name="title"></br>' + \
                            'Comments:</br>' + \
                            '<textarea name="comments" id="comments" rows="8" cols="98">' + \
                            'Hey... say something!' + \
                            '</textarea></br>' + \
                            '<input type="submit" value="Send" />' + \
                        '</form>'

            return show_annotated_content(request, body)

    # Dependiendo de lo que venga en la query haremos una cosa u otra
    elif request.method == 'POST':
        print(str(request.POST))
        # Un user quiere cambiar el titulo de su revista
        if 'newtitle' in request.POST:
            new_title = (str(request.POST)).split("'")[6]
            user_conf = User_Conf.objects.get(user_name=request.user)
            user_conf.journal_title = new_title
            user_conf.save()
            return HttpResponseRedirect(request.path)
        # Un user quiere valorar una noticia
        elif 'like' in str(request.POST):
            print str(request.POST)
            # Por defecto es un like, por tanto se suma 1
            score = 1
            # Sacamos el id de la noticia que se esta valorando
            NewId = (str(request.POST)).split("'")[11]
            # Sacamos el id del user
            user = User.objects.get(username=str(request.user))
            # Comprobamos si es like o dislike, y se sumara +1 o -1 respectivamente al contador
            if 'dislike' in str(request.POST):
                score = -1
            # Comprobamos si la noticia se ha valorado antes, si no es asi, se crea un nuevo campo
            try:
                rating = likes.objects.get(NewId=NewId)
            except likes.DoesNotExist:
                new_rating = likes(UserId=user.id, Counter=score, NewId=NewId)
                new_rating.save()
                new_record = user_like(UserId=user.id, NewId=NewId)
                new_record.save()
                return HttpResponseRedirect(request.path)
            # Comprobamos si ese usuario ha puntuado esa noticia antes, para evitar que puntue varias veces
            record = user_like.objects.filter(NewId=NewId)
            for n in record:
                if str(n.UserId) == str(user.id):
                    return HttpResponseRedirect(request.path)

            # Como no ha puntuado antes, sumamos el score y creamos un campo en el registro de likes
            rating.Counter = str(int(rating.Counter) + score)
            rating.save()

            new_record = user_like(UserId=user.id, NewId=NewId)
            new_record.save()
            return HttpResponseRedirect(request.path)
        # Un user ha enviado un comentario
        elif 'comments' in request.POST:
            # sacamos el id del usuario que envia el comentario
            user_name = str(request.user)
            user = User.objects.get(username=user_name)
            title = (str(request.POST)).split("'")[7]
            comment = (str(request.POST)).split("'")[3]
            comment_presentation = '<font size="3"><b>' + user_name + ':</b></font size></br>' + \
                                   '(<b>' + title + '</b>): ' + comment
            # Incluimos el comentario en la tabla Comments
            new_comment = Comments(UserId=user.id,
                                   Comment=comment_presentation,
                                   Users_Journal=str(request.path)[1:])
            new_comment.save()
            return HttpResponseRedirect(request.path)
        # Un user quiere personalizar el css
        elif 'personalize' in request.POST:
            new_color = (str(request.POST)).split("'")[3]
            new_font = (str(request.POST)).split("'")[7]
            new_back = (str(request.POST)).split("'")[15]
            # Sacamos el ID del user conectado
            user = User.objects.get(username=request.user)
            # Comprobamos si tiene una personalizacion antrior
            # si no, la creamos
            try:
                record = User_Custom.objects.get(UserId=user.id)
            except:
                new = User_Custom(UserId=user.id,
                                  background=new_back,
                                  font_size=new_font,
                                  color=new_color)
                new.save()
                return HttpResponseRedirect(request.path)

            record.background = new_back
            record.font_size = new_font
            record.color = new_color
            record.save()

            return HttpResponseRedirect(request.path)
        # Un user quiere seguir una noticia que se encuentra en una revista
        else:
            # sacamos el link de la noticia y lo usamos como identificador
            new_link = (str(request.POST)).split("'")[3]
            try:
                record = News.objects.get(url=new_link)
            except News.DoesNotExist:
                return show_annotated_content(
                    request, "Error: new's url does not found")

            #sacamos el id del ususario que se encuentra logueado
            try:
                user = User.objects.get(username=str(request.user))
            except User.DoesNotExist:
                return show_annotated_content(request,
                                              "Error: User does not found")

            # Comprobamos que el usuario no haya incluido esa noticia anterior mente
            News_list = New_User.objects.filter(UserId=user.id)
            for new in News_list:
                if int(new.NewId) == int(record.id):
                    return HttpResponseRedirect(request.path)

            # Actualizamos la conf del user, si el usuario no existe, se crea su revista
            try:
                user_conf = User_Conf.objects.get(user_name=user.username)
            except User_Conf.DoesNotExist:
                create_user_conf(user.username)
                user_conf = User_Conf.objects.get(user_name=user.username)

            # Actualizazmos el user_conf del usuario
            user_conf.last_updated = str(datetime.datetime.now())
            user_conf.save()

            # incluimos la noticia en la tabla de usuario/noticia
            follow_new = New_User(NewId=record.id,
                                  UserId=user.id,
                                  date=str(datetime.datetime.now()))
            follow_new.save()

            return HttpResponseRedirect(request.path)

    else:
        return HttpResponseNotAllowed('403 METHOD NOT ALLOWED')
Exemplo n.º 4
0
def server(request, resource):
    if do_login_logout(request):
        return HttpResponseRedirect(request.path)

    body = ''
    if request.method == 'GET':
        # Me estan pidiendo el recurso /
        if resource == '':
            body = ''
            journals_list = User_Conf.objects.all().order_by('last_updated')
            for journal in journals_list:
                body = '<div class="post"> ' + \
                           '<h2 class="title"><a href="/' + journal.user_name + '">' + journal.journal_title + '</a></h2>' + \
                           '<div style="clear: both;">&nbsp;</div>' + \
                           '<div class="entry">User: '******'</div>' + \
                           '<div class="entry">' + str(journal.last_updated) + '</div>' + \
                       '</div>' + body
            return show_annotated_content(request, body)
        else:
            # Se comprueba si el recurso que me piden coincide con algun /usuario existente
            try:
                user = User.objects.get(username=resource)
            except User.DoesNotExist:
                return HttpResponseNotFound('404 Not Found')

            # se procede a listar las noticias que sigue el usuario
            # Sacamos el id del usuario al que pertenece la revista
            try:
                user = User.objects.get(username=str(resource))
            except User.DoesNotExist:
                return show_annotated_content(request, "Error: User does not found")

            # Nos quedamos solamente con el id de las noticias del usuario al que pertenece la revista
            news = New_User.objects.filter(UserId=user.id)

            for n in reversed(news):
                # Sacamos el canal para concatenar su titulo y su id en la presentacion de la noticia
                new_channel = News_Channels.objects.get(NewId=n.NewId)
                channel = Channels.objects.get(id=new_channel.ChannelId)
                # Sacamos la noticia para concatenar sus campos en la presentacion
                new = News.objects.get(id=str(n.NewId))
                body += concatenate_new_presentation(request, channel.id, channel.title, new.id, new.title, new.contenido, new.url,
                                                     new.PubDate, n.date)

            presentation = '<h3>Comments</h3><div class="post">'
            # Sacamos los comentarios que haya de esa revista y los preparamos en formato html
            comments = Comments.objects.filter(Users_Journal=str(request.path)[1:])
            for n in reversed(comments):
                presentation += '<div class="entry">' + n.Comment + '</div>'
                                
            body += presentation + '</div>'
                 
            # Incluimos en el body, el formulario para comentarios, en caso de que sea un usuario logueado
            if request.user.is_authenticated():
                body += '<form action="" method="post">' + \
                            'Title:</br> <input type="text" name="title"></br>' + \
                            'Comments:</br>' + \
                            '<textarea name="comments" id="comments" rows="8" cols="98">' + \
                            'Hey... say something!' + \
                            '</textarea></br>' + \
                            '<input type="submit" value="Send" />' + \
                        '</form>'

            return show_annotated_content(request, body)

    # Dependiendo de lo que venga en la query haremos una cosa u otra
    elif request.method == 'POST':
        print (str(request.POST))
        # Un user quiere cambiar el titulo de su revista
        if 'newtitle' in request.POST:
            new_title = (str(request.POST)).split("'")[6]
            user_conf = User_Conf.objects.get(user_name=request.user)
            user_conf.journal_title = new_title
            user_conf.save()
            return HttpResponseRedirect(request.path)
        # Un user quiere valorar una noticia
        elif 'like' in str(request.POST):
             print str(request.POST)
             # Por defecto es un like, por tanto se suma 1
             score = 1
             # Sacamos el id de la noticia que se esta valorando
             NewId = (str(request.POST)).split("'")[11]
             # Sacamos el id del user
             user = User.objects.get(username=str(request.user))
             # Comprobamos si es like o dislike, y se sumara +1 o -1 respectivamente al contador
             if 'dislike' in str(request.POST):
                 score = -1
             # Comprobamos si la noticia se ha valorado antes, si no es asi, se crea un nuevo campo
             try:
                 rating = likes.objects.get(NewId=NewId)
             except likes.DoesNotExist:
                 new_rating = likes(UserId=user.id, Counter=score, NewId=NewId)
                 new_rating.save()
                 new_record = user_like(UserId=user.id, NewId=NewId)
                 new_record.save()
                 return HttpResponseRedirect(request.path)
             # Comprobamos si ese usuario ha puntuado esa noticia antes, para evitar que puntue varias veces
             record = user_like.objects.filter(NewId=NewId)
             for n in record:
                 if str(n.UserId) == str(user.id):
                     return HttpResponseRedirect(request.path)

             # Como no ha puntuado antes, sumamos el score y creamos un campo en el registro de likes
             rating.Counter = str(int(rating.Counter) + score)
             rating.save()

             new_record = user_like(UserId=user.id, NewId=NewId)
             new_record.save()
             return HttpResponseRedirect(request.path)
        # Un user ha enviado un comentario
        elif 'comments' in request.POST:
            # sacamos el id del usuario que envia el comentario
            user_name = str(request.user)
            user = User.objects.get(username=user_name)
            title = (str(request.POST)).split("'")[7]
            comment = (str(request.POST)).split("'")[3]
            comment_presentation = '<font size="3"><b>' + user_name + ':</b></font size></br>' + \
                                   '(<b>' + title + '</b>): ' + comment
            # Incluimos el comentario en la tabla Comments
            new_comment = Comments(UserId=user.id, Comment=comment_presentation, Users_Journal=str(request.path)[1:])
            new_comment.save()
            return HttpResponseRedirect(request.path)
        # Un user quiere personalizar el css
        elif 'personalize' in request.POST:
            new_color = (str(request.POST)).split("'")[3]
            new_font = (str(request.POST)).split("'")[7]
            new_back = (str(request.POST)).split("'")[15]
            # Sacamos el ID del user conectado
            user = User.objects.get(username=request.user)
            # Comprobamos si tiene una personalizacion antrior
            # si no, la creamos
            try:
                record = User_Custom.objects.get(UserId=user.id)
            except:
                new = User_Custom(UserId=user.id, background=new_back, font_size=new_font, color=new_color)
                new.save()
                return HttpResponseRedirect(request.path)

            record.background = new_back
            record.font_size = new_font
            record.color = new_color
            record.save()

            return HttpResponseRedirect(request.path)
        # Un user quiere seguir una noticia que se encuentra en una revista
        else:
            # sacamos el link de la noticia y lo usamos como identificador
            new_link = (str(request.POST)).split("'")[3]
            try:
                record = News.objects.get(url=new_link)
            except News.DoesNotExist:
                return show_annotated_content(request, "Error: new's url does not found")

            #sacamos el id del ususario que se encuentra logueado
            try:
                user = User.objects.get(username=str(request.user))
            except User.DoesNotExist:
                return show_annotated_content(request, "Error: User does not found")

            # Comprobamos que el usuario no haya incluido esa noticia anterior mente
            News_list = New_User.objects.filter(UserId=user.id)
            for new in News_list:
                if int(new.NewId) == int(record.id):
                    return HttpResponseRedirect(request.path)

            # Actualizamos la conf del user, si el usuario no existe, se crea su revista
            try:
                user_conf = User_Conf.objects.get(user_name=user.username)
            except User_Conf.DoesNotExist:
                create_user_conf(user.username)
                user_conf = User_Conf.objects.get(user_name=user.username)

            # Actualizazmos el user_conf del usuario
            user_conf.last_updated = str(datetime.datetime.now())
            user_conf.save()

            # incluimos la noticia en la tabla de usuario/noticia
            follow_new = New_User(NewId=record.id, UserId=user.id, date=str(datetime.datetime.now()))
            follow_new.save()
        
            return HttpResponseRedirect(request.path)

    else:
        return HttpResponseNotAllowed('403 METHOD NOT ALLOWED')