def fill_data(file_data, text=None, ntts={}): ''' Añade los datos necesarios para mostrar los archivos ''' if text: slug_text = slugify(text) text = (text, slug_text, frozenset(slug_text.split(" "))) # se asegura que esten cargados los datos de origenes y servidor de imagen antes de empezar fetch_global_data() f=init_data(file_data, ntts) choose_file_type(f) # al elegir nombre de fichero, averigua si aparece el texto buscado search_text_shown = choose_filename(f,text) build_source_links(f) embed_info(f) get_images(f) # si hace falta, muestra metadatos extras con el texto buscado format_metadata(f,text, search_text_shown) return f
def highlight(text_parts,match,limit_length=False): ''' Resalta la parte de una cadena que coincide con otra dada ''' separators = u"".join({i for i in match if i in SEPPER or i=="'"}) parts = list(multipartition(match,separators)) parts_type = [0 if part in separators else 1 if slugify(part) in text_parts else -1 for part in parts] parts_type.extend([0, 0]) result = [] strong = False for position, part in enumerate(parts): # abre tag si toca if not strong and parts_type[position]==1: result.append("<strong>") strong = True result.append(escape(part, True)) # cierra tag si toca if strong and parts_type[position+1]<1 and not (parts_type[position+1]==0 and parts_type[position+2]==1): result.append("</strong>") strong = False result = u"".join(result) if limit_length: #si se quiere acortar el nombre del archivo para que aparezca al principio la primera palabra resaltada first_term = result.find("<strong>") first_part = None if first_term>15 and len(match)>25: first_part = result[:first_term] if first_part[-1]==" ": #hace que el ultimo espacio siempre se vea first_part = first_part[:-1]+u" " return (result,"<span>"+first_part+"</span>"+result[first_term:] if first_part else result) else: return result
def choose_filename(f,text_cache=None): ''' Elige el archivo correcto ''' srcs = f['file']['src'] fns = f['file']['fn'] chosen = None max_count = -1 current_weight = -1 if text_cache and text_cache[0] in fns: # Si text es en realidad un ID de fn chosen = text_cache[0] else: for hexuri,src in srcs.items(): if 'bl' in src and src['bl']!=0: continue for crc,srcfn in src['fn'].items(): if crc not in fns: #para los sources que tienen nombre pero no estan en el archivo continue #si no tiene nombre no se tiene en cuenta m = srcfn['m'] if len(fns[crc]['n'])>0 else 0 if 'c' in fns[crc]: fns[crc]['c']+=m else: fns[crc]['c']=m text_weight = 0 if text_cache: fn_parts = slugify(fns[crc]['n']).strip().split(" ") if len(fn_parts)>0: text_words = slugify(text_cache[0]).split(" ") # valora numero y orden coincidencias last_pos = -1 max_length = length = 0 occurrences = [0]*len(text_words) for part in fn_parts: pos = text_words.index(part) if part in text_words else -1 if pos != -1 and (last_pos==-1 or pos==last_pos+1): length += 1 else: if length > max_length: max_length = length length = 0 if pos != -1: occurrences[pos]=1 last_pos = pos if length > max_length: max_length = length text_weight = sum(occurrences)*100 + max_length f['file']['fn'][crc]['tht'] = text_weight better = fns[crc]['c']>max_count if text_weight > current_weight or (better and text_weight==current_weight): current_weight = text_weight chosen = crc max_count = fns[crc]['c'] f['view']['url'] = mid2url(hex2mid(f['file']['_id'])) f['view']['fnid'] = chosen if chosen: filename = fns[chosen]['n'] ext = fns[chosen]['x'] else: #uses filename from src filename = "" for hexuri,src in srcs.items(): if src['url'].find("/")!=-1: filename = src['url'] if filename=="": return filename = filename[filename.rfind("/")+1:] ext = filename[filename.rfind(".")+1:] filename = filename[0:filename.rfind(".")] #TODO si no viene nombre de archivo buscar en los metadatos para formar uno (por ejemplo serie - titulo capitulo) filename = extension_filename(filename,ext) f['view']['fn'] = filename.replace("?", "") f['view']['qfn'] = qfn = u(filename).encode("UTF-8") #nombre del archivo escapado para generar las url de descarga f['view']['pfn'] = urllib.quote(qfn).replace(" ", "%20") # P2P filename nfilename = seoize_text(filename, " ",True, 0) f['view']['nfn'] = nfilename # añade el nombre del fichero como palabra clave g.keywords.update(set(keyword for keyword in nfilename.split(" ") if len(keyword)>1)) #nombre del archivo con las palabras que coinciden con la busqueda resaltadas if text_cache: f['view']['fnh'], f['view']['fnhs'] = highlight(text_cache[2],filename,True) else: f['view']['fnh'] = filename #esto es solo para download que nunca tiene text return current_weight>0 # indica si ha encontrado el texto buscado
def get_id_server_from_search(self, file_id, file_name, timeout=1000): return self.sphinx.get_id_server_from_search(mid2bin(file_id), escape_string(" ".join(slugify(file_name).split(" ")[:4])) if file_name else "", timeout)