Beispiel #1
0
def vote():
    '''
    Gestiona las votaciones de archivos y comentarios
    '''
    try:
        vote_type=request.form.get("type",None)
        server=int(request.form.get("where",None))
        file_id=url2mid(request.form.get("file",None))
        file_name=request.form.get("name",None)
        comment_id=request.form.get("comment",None)
        vote=int(request.form.get("vote",0))
        if not vote_type or server<=0 or not file_id or not file_name or vote not in (0,1):
            raise Exception
    except:
        return _("error_500_message"),404

    json={}
    if current_user.type in (None, 0): #comprobación de usuario normal o anónimo
        if vote_type=="file": #voto para archivos: se guarda y actualiza el archivo
            results=usersdb.set_file_vote(file_id, current_user, g.lang,vote)
            filesdb.update_file({"_id":file_id, "vs":results, "s":server}, direct_connection=True)
            json=results.get(g.lang, None)
            if json is None and None in results:
                json = results[None]

        elif vote_type=="comment": #voto para comentarios solo usuarios normales
            json=usersdb.set_file_comment_vote( comment_id, current_user, file_id, vote )["1"]

    json["vote"]=1 if vote==1 else 0
    return jsonify(json)
Beispiel #2
0
def vote():
    '''
    Gestiona las votaciones de archivos
    '''
    ok = False
    try:
        file_id = url2mid(request.form.get("file_id", None))
        server = int(request.form.get("server", 0))
        vote = int(request.form.get("vote", 0))
        if server > 1 and file_id and vote in (0, 1):
            file_info = usersdb.set_file_vote(file_id, current_user, g.lang,
                                              vote)
            filesdb.update_file({
                "_id": file_id,
                "vs": file_info,
                "s": server
            },
                                direct_connection=True)
            ok = True
    except BaseException as e:
        logging.error("Error on vote.")

    response = make_response("true" if ok else "false")
    response.mimetype = "application/json"
    return response
Beispiel #3
0
def download_ajax(file_id):
    file_id=url2mid(file_id)
    try:
        data = filesdb.get_file(file_id, bl = None)
    except filesdb.BogusMongoException as e:
        logging.exception(e)
        abort(503)

    if data:
        if not data["bl"] in (0, None):
            if data["bl"] == 1:
                flash("link_not_exist", "error")
            elif data["bl"] == 3:
                flash("error_link_removed", "error")

            goback = True
            abort(404)
    else:
        flash("link_not_exist", "error")
        abort(404)

    #si el usuario esta logueado se comprueba si ha votado el archivo para el idioma activo
    vote=None
    if current_user.is_authenticated():
        vote=usersdb.get_file_vote(file_id,current_user,g.lang)

    if vote is None:
        vote={"k":0}

    return render_template('files_ajax/download_ajax.html',file=fill_data(data,True),vote=vote)
Beispiel #4
0
def copyright():
    '''
    Muestra el formulario para reportar enlaces
    '''
    g.cache_code = "S"
    g.category = False
    g.page_description = _("torrentsfm_desc")
    g.keywords.clear()
    g.keywords.update(["torrents search engine popular largest copyright"])
    g.title.append(_("Copyright form"))
    form = ComplaintForm(request.form)
    if request.method=='POST':
        if "file_id" in request.form:
            try:
                file_id = request.form["file_id"]
                file_name = request.form.get("file_name",None)
                data = torrents_data(get_file_metadata(url2mid(file_id), file_name))
                if data:
                    form.urlreported.data=url_for("files.download",file_id=file_id,file_name=file_name,_external=True, _secure=False)
                    form.linkreported.data=data['view']["sources"]["tmagnet"]["urls"][0] if "tmagnet" in data['view']["sources"] else data['view']["sources"]["download"]["urls"][0] if "download" in data['view']["sources"] else data['view']["sources"]["download_ind"]["urls"][0]
            except BaseException as e:
                logging.exception(e)
        elif form.validate():
            pagesdb.create_complaint(dict([("ip",request.remote_addr)]+[(field.name,field.data) for field in form]))
            return empty_redirect(url_for('.home', _anchor="sent"))
    return render_template('copyright.html',form=form)
Beispiel #5
0
def download_ajax(file_id,file_name=None):
    #validar id de download
    try:
        file_mid=url2mid(file_id)
    except:
        file_mid=file_id=None

    download=download2(file_mid,file_name)
    return jsonify(html=download["html"],play=download["play"])
Beispiel #6
0
def vote(t,server,file_id,comment_id=None,vote=0,login=0):
    '''
    Gestiona las votaciones de archivos y comentarios
    '''
    g.title += " - Vote "
    #voto no permitido a administradores ni con valores extraños
    json={}
    if (current_user.type is None or current_user.type==0) and (vote==1 or vote==2):
        #si es el voto para archivos se guarda y actualiza el archivo
        if t=="file":
            json=usersdb.set_file_vote(url2mid(file_id),current_user,g.lang,vote)
            filesdb.update_file({"_id":url2mid(file_id),"vs":json,"s":server},direct_connection=True)
            json=json[g.lang]
        #si es para comentarios idem
        elif t=="comment":
            json=usersdb.set_file_comment_vote(comment_id,current_user,url2mid(file_id),vote)["1"]

    if login==0:
        return redirect(url_for(".download",file_id=file_id))
    else:
        return jsonify(json)
Beispiel #7
0
def api_embed(embed_size, fileid, nameid):
    if not embed_size in ("s","m","b"):
        embed_size = "m"

    file_id = url2mid(fileid)
    filename = ""

    download_url = None
    size = 0

    if embed_size == "b":
        try:
            data = get_file_metadata(file_id, nameid)
            download_url = data["view"]["url"]
        except DatabaseError:
            abort(503)
        except FileNotExist:
            flash("link_not_exist", "error")
            abort(404)
        except FileRemoved:
            flash("error_link_removed", "error")
            abort(404)
        except FileUnknownBlock:
            abort(404)

    else:
        data = filesdb.get_file(file_id)

        size = None
        if "z" in data:
            size = data['z']

        if "torrent:name" in data["md"]:
            filename = data["md"]["torrent:name"]
        elif nameid in data["fn"]:
            filename = data["fn"][nameid]['n']
        elif data["fn"]:
            filename = data["fn"].values()[0]['n']
        else:
            filename = ""

        download_url = url_for("files.download", file_id=mid2url(data["_id"]), file_name="%s.html" % filename)

    return render_template("api/embed.html",
        filename = filename,
        size = size,
        file = data,
        embed_size = embed_size,
        download_url = download_url
        )
Beispiel #8
0
def vote():
    '''
    Gestiona las votaciones de archivos
    '''
    ok = False
    try:
        file_id=url2mid(request.form.get("file_id",None))
        server=int(request.form.get("server",0))
        vote=int(request.form.get("vote",0))
        if server>1 and file_id and vote in (0,1):
            file_info = usersdb.set_file_vote(file_id, current_user, g.lang, vote)
            filesdb.update_file({"_id":file_id, "vs":file_info, "s":server}, direct_connection=True)
            ok = True
    except BaseException as e:
        logging.error("Error on vote.")

    response = make_response("true" if ok else "false")
    response.mimetype = "application/json"
    return response
Beispiel #9
0
def favorite(favorite_type=None,action=None,server=0,file_id=None,file_name=None,favorite_name=None,redirection=0):
    try:
        favorite_type=request.form.get("type",favorite_type)
        action=request.form.get("action",action)
        server=int(request.form.get("where",server)) #where
        file_id=url2mid(request.form.get("file",file_id))
        file_name=request.form.get("name",file_name)
        favorite_name=request.form.get("favorite_name",favorite_name)
        redirection=int(request.form.get("login",redirection)) #login
        if not favorite_type or not action or server<=0 or not file_id or not file_name or redirection<=0:
            raise Exception
    except:
        return _("error_500_message"),404

    if action=="add":
        if favorite_type == "file":
            usersdb.add_fav_file(current_user, file_id, server, file_name)
        elif favorite_type == "user" and favorite_name:
            usersdb.add_fav_user_file(current_user, file_id, server, file_name, favorite_name)
        elif favorite_type == "search":
            pass # TODO (felipe): implementar
        else:
            return _("error_500_message"),404
    elif action=="delete":
        if favorite_type == "file":
            usersdb.remove_fav_file(current_user, file_id)
        elif favorite_type == "user":
            usersdb.remove_fav_user_file(current_user, file_id, favorite_name)
        elif favorite_type == "search":
            pass # TODO (felipe): implementar
        else:
            return _("error_500_message"),404

    if redirection==0:
        return redirect(url_for("files.download",file_id=file_id,file_name=file_name))
    elif redirection==1:
        return jsonify(OK = True)
    elif redirection==2:
        return redirect(url_for(".profile"))
Beispiel #10
0
def complaint(file_id=None,file_name=None):
    '''
    Muestra el formulario para reportar enlaces
    '''
    form = ReportLinkForm(request.form)
    if request.method=='POST':
        if "file_id" in request.form:
            try:
                file_id = request.form["file_id"]
                file_name = request.form.get("file_name",None)
                data = filesdb.get_file(url2mid(file_id), bl = None)
                if data:
                    form.urlreported.data=url_for("files.download",file_id=file_id,file_name=file_name,_external=True).replace("%21","!")
                    form.linkreported.data=data["src"].itervalues().next()["url"]
            except BaseException as e:
                logging.exception(e)
        elif form.validate():
            pagesdb.create_complaint(dict([("ip",request.remote_addr)]+[(field.name,field.data) for field in form]))
            flash("message_sent")
            return redirect(url_for('index.home'))

    g.title+=_("complaint")
    return render_template('pages/complaint.html',page_title=_("complaint"),pagination=["privacy","legal",4,4],form=form,pname="complaint")
Beispiel #11
0
def download(file_id, file_name=""):
    g.page_type = FILE_PAGE_TYPE
    if request.referrer:
        try:
            posibles_queries = referrer_parser.match(request.referrer)
            if posibles_queries:
                query = posibles_queries.group(1) or posibles_queries.group(2) or ""
                if query:
                    get_query_info(u(urllib2.unquote_plus(query).decode("utf-8")))
        except:
            pass

    error = None
    file_data=None
    if file_id is not None: #si viene un id se comprueba que sea correcto
        try: #intentar convertir el id que viene de la url a uno interno
            file_id=url2mid(file_id)
        except TypeError as e:
            try: #comprueba si se trate de un ID antiguo
                possible_file_id = filesdb.get_newid(file_id)
                if possible_file_id is None:
                    logging.warn("Identificadores numericos antiguos sin resolver: %s."%e, extra={"fileid":file_id})
                    error=404
                else:
                    logging.warn("Identificadores numericos antiguos encontrados: %s."%e, extra={"fileid":file_id})
                    return {"html": empty_redirect(url_for(".download", file_id=mid2url(possible_file_id), file_name=file_name), 301),"error":301}

            except BaseException as e:
                logging.exception(e)
                error=503

            file_id=None

        if file_id:
            try:
                file_data=get_file_metadata(file_id, file_name.replace("-"," "))
            except DatabaseError:
                error=503
            except FileNotExist:
                error=404
            except (FileRemoved, FileFoofindRemoved, FileNoSources):
                error=410
            except FileUnknownBlock:
                error=404

            if error is None and not file_data: #si no ha habido errores ni hay datos, es porque existe y no se ha podido recuperar
                error=503

    if error:
        abort(error)

    # completa datos de torrent
    file_data = torrents_data(file_data, True, g.category)
    if not file_data:
        abort(404)

    if file_data["view"]["category"]:
        g.category = file_data["view"]["category"]
        if file_data["view"]["category"].tag=="p**n":
            g.is_adult_content = True
    else:
        g.category = file_data["view"]["category_type"]

    # no permite acceder ficheros que deberian ser bloqueados
    prepared_phrase = blacklists.prepare_phrase(file_data['view']['nfn'])
    if prepared_phrase in blacklists["forbidden"] or (prepared_phrase in blacklists["misconduct"] and prepared_phrase in blacklists["underage"]):
        g.blacklisted_content = "File"
        if not g.show_blacklisted_content:
            abort(404)

    query = download_search(file_data, file_name, "torrent").replace("-"," ")
    related = single_search(query, category=None, not_category=(None if g.is_adult_content else "p**n"), title=("Related torrents",3,None), zone="File / Related", last_items=[], limit=30, max_limit=15, ignore_ids=[mid2hex(file_id)], show_order=None)

    # elige el titulo de la página
    title = file_data['view']['fn']

    # recorta el titulo hasta el proximo separador
    if len(title)>101:
        for pos in xrange(101, 30, -1):
            if title[pos] in SEPPER:
                title = title[:pos].strip()
                break
        else:
            title = title[:101]

    g.title = [title]

    page_description = ""
    if "description" in file_data["view"]["md"]:
        page_description = file_data["view"]["md"]["description"].replace("\n", " ")

    if not page_description:
        if g.category:
            page_description = _("download_category_desc", category=singular_filter(g.category.title).lower(), categorys=g.category.title.lower()).capitalize()
        else:
            page_description = _("download_desc")


    if len(page_description)<50:
        if page_description:
           page_description += ". "
        page_description += " ".join(text.capitalize()+"." for text in related[1]["files_text"])

    if len(page_description)>180:
        last_stop = page_description[:180].rindex(".") if "." in page_description[:180] else 0
        if last_stop<100:
            last_stop = page_description[:180].rindex(" ") if " " in page_description[:180] else 0
        if last_stop<100:
            last_stop = 180
        page_description = page_description[:last_stop]+"."

    g.page_description = page_description

    is_canonical_filename = file_data["view"]["seo-fn"]==file_name

    # registra visita al fichero
    if g.search_bot:
        searchd.log_bot_event(g.search_bot, True)
    else:
        save_visited([file_data])

    if related[0]:
        g.must_cache = 3600

    # last-modified
    g.last_modified = file_data["file"]["ls"]

    return render_template('file.html', related_query = query, file_data=file_data, related_files=related, is_canonical_filename=is_canonical_filename, featured=get_featured(related[1]["count"]+len(file_data["view"]["md"]), 1))
Beispiel #12
0
def lock_file(complaint_id=None):
    '''
    Información y bloqueo de ficheros, puede recibir un id de queja, o una lista de ids (en hex) de ficheros separados por la letra "g"
    '''
    page = request.args.get("page", 0, int)
    mode = request.args.get("show", "old", str)
    size = request.args.get("size", 15, int)

    filenames = {}
    bugged = []
    fileids = ()
    if request.method == 'POST':
        if not "fileids" in request.form:
            searchform = BlockFileSearchForm(request.form)
            identifiers = searchform.identifier.data.split()
            if searchform.mode.data == "hexid":
                fileids = [ mid2hex(hex2mid(i))
                    for i in identifiers
                    if all(x in "0123456789abcdef" for x in i)
                    ]
            elif searchform.mode.data == "b64id":
                fileids = [
                    mid2hex(url2mid(i))
                    for i in identifiers
                    if all(x in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!-" for x in i)
                        and (len(i)*8)%6 == 0
                    ]
            elif searchform.mode.data == "url":
                filenames.update(
                    (
                        mid2hex(fileurl2mid(i)),
                        u".".join(urllib2.unquote(i.split("/")[-1]).split(".")[:-1])
                        )
                    for i in identifiers
                    if i.startswith("http") and len(i.split("//")[1].split("/")) > 3
                    )
                fileids = filenames.keys()
            if not fileids:
                return redirect(url_for('admin.locks', page=page, mode=mode, size=size))
        else:
            block = request.form.get("block", False, bool)
            unblock = request.form.get("unblock", False, bool)
            if block or unblock: # submit confirmar
                if complaint_id: pagesdb.update_complaint({"_id":complaint_id,"processed":True})
                fileids = dict(i.split(":") for i in request.form["fileids"].split(","))
                sphinx_block = []
                sphinx_unblock = []
                for fileid, server in fileids.iteritems():
                    (sphinx_block if block and not unblock else sphinx_unblock).append(fileid)
                    req = {"_id":fileid, "bl": int(block and not unblock)}
                    if server: req["s"] = int(server) # si recibo el servidor, lo uso por eficiencia
                    try:
                        # TODO(felipe): comprobar en qué casos se puede llegar aquí sin "s"
                        filesdb.update_file(req, direct_connection=True, update_sphinx=False)
                    except:
                        flash("No se ha podido actualizar el fichero con id %s" % fileid, "error")
                if sphinx_block:
                    block_files_in_sphinx(mongo_ids=sphinx_block, block=True)
                if sphinx_unblock:
                    block_files_in_sphinx(mongo_ids=sphinx_unblock, block=False)
                flash("admin_locks_locked" if block else "admin_locks_unlocked", "success")
            elif request.form.get("cancel", False, bool): # submit cancelar
                if complaint_id:
                    pagesdb.update_complaint({"_id":complaint_id,"processed":True})
                flash("admin_locks_not_locked", "success")
            return redirect(url_for('admin.locks', page=page, mode=mode, size=size))

    complaint_data = None # Hay un único o ningún registro de queja por formulario
    files_data = OrderedDict() # Pueden haber varios ficheros por formulario
    if complaint_id: # Si hay queja, sólo hay una url, la de la queja
        complaint_data = pagesdb.get_complaint(complaint_id)
        if complaint_data and "urlreported" in complaint_data:
            # extracción el id de complaint["urlreported"] de base64 a hexadecimal
            files_data[mid2hex(fileurl2mid(complaint_data["urlreported"]))] = None
    elif fileids: # Si no hay queja, los ficheros se sacan de la url
        files_data.update((i,None) for i in fileids)

    # Suponemos si queremos bloquear, desbloquear, o mostrar las dos opciones
    # dependiendo de sí de los ficheros están bloqueados o no
    # además rellenamos la información de los ficheros
    blocked = 0
    unblocked = 0
    for fileid in files_data.iterkeys():
        data = filesdb.get_file(fileid, bl=None)
        if data is None and fileid in filenames:
            bugged.append(fileid)
            sid = get_id_server_from_search(fileid, filenames[fileid])
            if sid:
                data = filesdb.get_file(fileid, sid = sid, bl = None)
        files_data[fileid] = data or {}
        if not "bl" in files_data[fileid] or files_data[fileid]["bl"] == 0: unblocked += 1
        else: blocked += 1

    return render_template('admin/lock_file.html',
        page_title=_('admin_locks_fileinfo'),
        complaint_data=complaint_data,
        files_data=files_data,
        filenames = filenames,
        bugged = bugged,
        fileids=",".join(
            "%s:%s" % (fileid, prop["s"] if "s" in prop else "")
            for fileid, prop in files_data.iteritems()),
        blocked=None if blocked and unblocked else blocked > 0,
        list_mode=mode,
        page=page,
        title=admin_title('admin_losfdcks_fileinfo'))
Beispiel #13
0
def download(file_id,file_name=None):
    '''
    Muestra el archivo a descargar, votos, comentarios y archivos relacionados
    '''
    def choose_filename_related(file_data):
        '''
        Devuelve el nombre de fichero elegido
        '''
        f=init_data(file_data)
        choose_filename(f)
        return f

    def comment_votes(file_id,comment):
        '''
        Obtiene los votos de comentarios
        '''
        comment_votes={}
        if "vs" in comment:
            for i,comment_vote in enumerate(usersdb.get_file_comment_votes(file_id)):
                if not comment_vote["_id"] in comment_votes:
                    comment_votes[comment_vote["_id"][0:40]]=[0,0,0]

                if comment_vote["k"]>0:
                    comment_votes[comment_vote["_id"][0:40]][0]+=1
                else:
                    comment_votes[comment_vote["_id"][0:40]][1]+=1

                #si el usuario esta logueado y ha votado se guarda para mostrarlo activo
                if current_user.is_authenticated() and comment_vote["u"]==current_user.id:
                    comment_votes[comment_vote["_id"][0:40]][2]=comment_vote["k"]

        return comment_votes

    #guardar los parametros desde donde se hizo la busqueda si procede
    args={}
    if request.referrer:
        querystring = urlparse(request.referrer).query
        if querystring:
            for params in u(querystring).encode("UTF-8").split("&"):
                param=params.split("=")
                if len(param) == 2:
                    args[param[0]]=u(urllib.unquote_plus(param[1]))

    try:
        file_id=url2mid(file_id)
    except Exception as e:
        # Comprueba que se trate de un ID antiguo
        try:
            possible_file_id = filesdb.get_newid(file_id)
            if possible_file_id is None:
                logging.warn("%s - %s" % (e, file_id))
                flash("link_not_exist", "error")
                abort(404)
            return redirect(
                url_for(".download", file_id=mid2url(possible_file_id), file_name=file_name),
                code=301)
        except filesdb.BogusMongoException as e:
            logging.exception(e)
            abort(503)

    try:
        data = filesdb.get_file(file_id, bl = None)
    except filesdb.BogusMongoException as e:
        logging.exception(e)
        abort(503)

    # intenta sacar el id del servidor de sphinx,
    # resuelve inconsistencias de los datos
    if not data:
        sid = get_id_server_from_search(file_id, file_name)
        if sid:
            try:
                data = filesdb.get_file(file_id, sid = sid, bl = None)
            except filesdb.BogusMongoException as e:
                logging.exception(e)
                abort(503)

    if data:
        if not data["bl"] in (0, None):
            if data["bl"] == 1: flash("link_not_exist", "error")
            elif data["bl"] == 3: flash("error_link_removed", "error")
            goback = True
            #block_files( mongo_ids=(data["_id"],) )
            abort(404)
    else:
        flash("link_not_exist", "error")
        abort(404)

    #obtener los datos
    file_data=fill_data(data, True, file_name)
    if file_data["view"]["sources"]=={}: #si tiene todos los origenes bloqueados
        flash("error_link_removed", "error")
        abort(404)

    save_visited([file_data])
    # Título
    title = u(file_data['view']['fn'])
    g.title = u"%s \"%s%s\"%s%s" % (
        _(file_data['view']['action']).capitalize(),
        title[:50],
        "..." if len(title) > 50 else "",
        " - " if g.title else "",
        g.title)

    #obtener los archivos relacionados
    related_files = search_related(split_file(file_data["file"])[0][:10])
    bin_file_id=mid2bin(file_id)
    ids=sorted({fid[0:3] for related in related_files for fid in get_ids(related) if fid[0]!=bin_file_id})[:5]
    files_related=[choose_filename_related(data) for data in get_files(ids)]

    #si el usuario esta logueado se comprueba si ha votado el archivo para el idioma activo
    vote=None
    if current_user.is_authenticated():
        vote=usersdb.get_file_vote(file_id,current_user,g.lang)

    if vote is None:
        vote={"k":0}

    #formulario para enviar comentarios
    form = CommentForm(request.form)
    if request.method=='POST' and current_user.is_authenticated() and (current_user.type is None or current_user.type==0) and form.validate():
        usersdb.set_file_comment(file_id,current_user,g.lang,form.t.data)
        form.t.data=""
        flash("comment_published_succesfully")
        #actualizar el fichero con la suma de los comentarios por idioma
        filesdb.update_file({"_id":file_id,"cs":usersdb.get_file_comments_sum(file_id),"s":file_data["file"]["s"]},direct_connection=True)

    #si tiene comentarios se guarda el número del comentario, el usuario que lo ha escrito, el comentario en si y los votos que tiene
    comments=[]
    if "cs" in file_data["file"]:
        comments=[(i,usersdb.find_userid(comment["_id"][0:24]),comment,comment_votes(file_id,comment)) for i,comment in enumerate(usersdb.get_file_comments(file_id,g.lang),1)]

    return render_template('files/download.html',file=file_data,args=args,vote=vote,files_related=files_related,comments=comments,form=form)
Beispiel #14
0
def download(file_id,file_name=None):
    '''
    Muestra el archivo a descargar, votos, comentarios y archivos relacionados
    '''
    def choose_filename_related(file_data):
        '''
        Devuelve el nombre de fichero elegido
        '''
        f=init_data(file_data)
        choose_filename(f)
        return f

    def comment_votes(file_id,comment):
        '''
        Obtiene los votos de comentarios
        '''
        comment_votes={}
        if "vs" in comment:
            for i,comment_vote in enumerate(usersdb.get_file_comment_votes(file_id)):
                if not comment_vote["_id"] in comment_votes:
                    comment_votes[comment_vote["_id"][0:40]]=[0,0,0]

                if comment_vote["k"]>0:
                    comment_votes[comment_vote["_id"][0:40]][0]+=1
                else:
                    comment_votes[comment_vote["_id"][0:40]][1]+=1

                #si el usuario esta logueado y ha votado se guarda para mostrarlo activo
                if current_user.is_authenticated() and comment_vote["u"]==current_user.id:
                    comment_votes[comment_vote["_id"][0:40]][2]=comment_vote["k"]

        return comment_votes

    if file_name is not None:
        g.title = _("download").capitalize()+" "+file_name+" - "+g.title
    else:
        g.title =_("download").capitalize()

    #guardar los parametros desde donde se hizo la busqueda si procede
    args={}
    if request.referrer:
        querystring = urlparse(request.referrer).query
        if querystring:
            for params in querystring.split("&"):
                param=params.split("=")
                if len(param) == 2:
                    args[param[0]]=u(urllib.unquote_plus(param[1]))

    try:
        file_id=url2mid(file_id)
    except BaseException as e:
        logging.warn((e, file_id))
        abort(404)

    data = filesdb.get_file(file_id, bl = None)

    if data:
        if not data["bl"] in (0, None):
            if data["bl"] == 1: flash("link_not_exist", "error")
            elif data["bl"] == 3: flash("error_link_removed", "error")
            goback = True
            #block_files( mongo_ids=(data["_id"],) )
            abort(404)
    else:
        flash("link_not_exist", "error")
        abort(404)

    #obtener los datos
    file_data=fill_data(data, True, file_name)
    save_visited([file_data])

    #obtener los archivos relacionados
    related_files = search_related(split_file(file_data["file"])[0][0:50])
    bin_file_id=mid2bin(file_id)
    ids=sorted({fid for related in related_files for fid in get_ids(related) if fid[0]!=bin_file_id})[:5]
    files_related=[choose_filename_related(data) for data in get_files(ids)]

    #si el usuario esta logueado se comprueba si ha votado el archivo para el idioma activo
    vote=None
    if current_user.is_authenticated():
        vote=usersdb.get_file_vote(file_id,current_user,g.lang)

    if vote is None:
        vote={"k":0}

    #formulario para enviar comentarios
    form = CommentForm(request.form)
    if request.method=='POST' and current_user.is_authenticated() and (current_user.type is None or current_user.type==0) and form.validate():
        usersdb.set_file_comment(file_id,current_user,g.lang,form.t.data)
        form.t.data=""
        flash("comment_published_succesfully")
        #actualizar el fichero con la suma de los comentarios por idioma
        filesdb.update_file({"_id":file_id,"cs":usersdb.get_file_comments_sum(file_id),"s":file_data["file"]["s"]},direct_connection=True)

    #si tiene comentarios se guarda el número del comentario, el usuario que lo ha escrito, el comentario en si y los votos que tiene
    comments=[]
    if "cs" in file_data["file"]:
        comments=[(i,usersdb.find_userid(comment["_id"][0:24]),comment,comment_votes(file_id,comment)) for i,comment in enumerate(usersdb.get_file_comments(file_id,g.lang),1)]

    return render_template('files/download.html',file=file_data,args=args,vote=vote,files_related=files_related,comments=comments,form=form)
Beispiel #15
0
def download_file(file_id,file_name=None):
    '''
    Devuelve el archivo a descargar, votos, comentarios y archivos relacionados
    '''
    error=(None,"") #guarda el id y el texto de un error
    file_data=None
    if file_id is not None: #si viene un id se comprueba que sea correcto
        if is_valid_url_fileid(file_id):
            try: #intentar convertir el id que viene de la url a uno interno
                file_id=url2mid(file_id)
            except (bson.objectid.InvalidId, TypeError) as e:
                try: #comprueba si se trate de un ID antiguo
                    possible_file_id = filesdb.get_newid(file_id)
                    if possible_file_id is None:
                        logging.warn("Identificadores numericos antiguos sin resolver: %s."%e, extra={"fileid":file_id})
                        error=(404,"link_not_exist")
                    else:
                        logging.warn("Identificadores numericos antiguos encontrados: %s."%e, extra={"fileid":file_id})
                        return {"html": redirect(url_for(".download", file_id=mid2url(possible_file_id), file_name=file_name), 301),"error":(301,"")}

                except BaseException as e:
                    logging.exception(e)
                    error=(503,"")

                file_id=None
        else:
            abort(404)

        if file_id:
            try:
                file_data=get_file_metadata(file_id, file_name)
            except DatabaseError:
                error=(503,"")
            except FileNotExist:
                error=(404,"link_not_exist")
            except (FileRemoved, FileFoofindRemoved, FileNoSources):
                error=(410,"error_link_removed")
            except FileUnknownBlock:
                error=(404,"")

            if error[0] is None and not file_data: #si no ha habido errores ni hay datos, es porque existe y no se ha podido recuperar
                error=(503,"")

    if file_id is None or error[0] is not None:
        html=""
        if error[0] is not None:  #si hay algun error se devuelve renderizado
            message_msgid="error_%s_message" % error[0]
            message_msgstr=_(message_msgid)
            g.title="%s %s" % (error[0], message_msgstr if message_msgstr!=message_msgid else _("error_500_message"))
            html=render_template('error.html',error=error,full_screen=True)

        return {"html": html,"play":None,"file_data":file_data,"error":error}
    else:
        save_visited([file_data])
        title = u(file_data['view']['fn'])
        g.title = u"%s \"%s\" - %s" % (
            _(file_data['view']['action']).capitalize(),
            title[:100],
            g.title)
        g.page_description = u"%s %s"%(_(file_data['view']['action']).capitalize(), seoize_text(title," ",True))

        #si el usuario esta logueado se comprueba si ha votado el archivo para el idioma activo y si ha marcado el archivo como favorito
        vote=None
        favorite = False
        if current_user.is_authenticated():
            vote=usersdb.get_file_vote(file_id,current_user,g.lang)
            favorite=any(file_id==favorite["id"] for favorite in usersdb.get_fav_files(current_user))

        #formulario para enviar comentarios
        form = CommentForm(request.form)
        if request.method=='POST' and current_user.is_authenticated() and (current_user.type is None or current_user.type==0) and form.validate():
            usersdb.set_file_comment(file_id,current_user,g.lang,form.t.data)
            form.t.data=""
            flash("comment_published_succesfully")
            #actualizar el fichero con la suma de los comentarios por idioma
            filesdb.update_file({"_id":file_id,"cs":usersdb.get_file_comments_sum(file_id),"s":file_data["file"]["s"]},direct_connection=True)

        #si tiene comentarios se guarda el número del comentario, el usuario que lo ha escrito, el comentario en si y los votos que tiene
        comments=[]
        if "cs" in file_data["file"]:
            comments=[(i,usersdb.find_userid(comment["_id"].split("_")[0]),comment,comment_votes(file_id,comment)) for i,comment in enumerate(usersdb.get_file_comments(file_id,g.lang),1)]

        # en la pagina de download se intentan obtener palabras para buscar si no las hay
        if g.args.get("q", None) is None:
            query = download_search(file_data, file_name, "foofind")
            if query:
                g.args["q"] = query.replace(":","")

        return {
            "html":render_template('files/download.html',file=file_data,vote={"k":0} if vote is None else vote,favorite=favorite,form=form,comments=comments),
            "play":file_data["view"]["play"] if "play" in file_data["view"] else "",
            "file_data":file_data,
        }