예제 #1
0
파일: ajax.py 프로젝트: gage/proto
def related_contact(request, selector='all'):
    """ contact autocomplete
        indexes: first_name, last_name, email, phone, site_user
        type: 'all' (all), 'site' (site use only), 'no_site' (exclude site user)
    """
    q = request.GET.get('q', None)
    contact_id = request.GET.get('contact_id', None)
    limit = 5

    # Exclude already slaved contacts
    exclude_idl = list(Contact.objects.all_filter(master_contact=contact_id).values_list('id', flat=True))
    exclude_idl.append(contact_id)

    """ query handler """
    if q is None or q == '':
        return HttpJsonResponse()
    results = None
    has_query = False
    if not '@' in q:
        query_list = process_query(q)
        for q_o in query_list:
            if q_o:
                if not has_query:
                    has_query = True
                    results = SearchQuerySet().filter(SQ(first_name__startswith=q_o) | SQ(last_name__startswith=q_o) | \
                                 SQ(email__startswith=q_o) | SQ(phone__startswith=q_o) | SQ(site_user__startswith=q_o))
                else:
                    results = results.filter(SQ(first_name__startswith=q_o) | SQ(last_name__startswith=q_o) | \
                                 SQ(email__startswith=q_o) | SQ(phone__startswith=q_o) | SQ(site_user__startswith=q_o))
    else:
        has_query = True
        results = SearchQuerySet().auto_query(q)

    if has_query:
        results = results.filter(user=request.user.pk).exclude(is_slave=True).models(Contact).load_all()
    else:
        results = []

    if has_query:
        if selector == 'site':
            results = results.filter(site_user__range=['*','*'])
        elif selector == "no_site":
            results = results.exclude(site_user__range=['*','*'])
        results = results.exclude(cid__in=exclude_idl)
        results = results.load_all()[:limit]
    else:
        results = []

    tmp_response = []
    html_content = ""
    for result in results:
        # Use html to render the contact
        if not result:
            continue
        html_content += render_to_string('inc_contact_related.html', {'contact':result.object}, context_instance = RequestContext(request))
    data = {'html':html_content}
    return HttpJsonResponse(data)
예제 #2
0
파일: handlers.py 프로젝트: gage/proto
    def read(self, request):
        """ Search """
        query_term = request.CLEANED['q']
        filter_type = request.CLEANED['filter_type']
        search_fields = request.CLEANED['search_fields']
        offset = int(request.CLEANED['offset']) if request.CLEANED['offset'] else None
        endpoint = int(request.CLEANED['endpoint']) if request.CLEANED['offset'] else None
        total_count = request.CLEANED['total_count'] == True if 'total_count' in request.CLEANED else False
        if not request.CLEANED.has_key('distance'):
            raise Exception('Call super read_validate when overwrite')
        distance = request.CLEANED['distance']
        if request.CLEANED.has_key('custom_query'):
            query_set = request.CLEANED['custom_query']
        else:
            if type(self.query_model)==list:
                query_set = SearchQuerySet().models(*self.query_model).load_all()
            else:
                query_set = SearchQuerySet().models(self.query_model).load_all()

        if self.about_privacy:
            # TODO
            pass

        query_list = []
        query_args = {}
        if filter_type == 'auto_query':
            query_set = query_set.auto_query(query_term)

        elif filter_type == 'auto_complete':
            query_set = query_set.filter(SQ(auto_complete=query_term))

        elif filter_type == 'startswith' or filter_type == 'location':
            query_term_list = process_query(query_term)
            for term in query_term_list:
                query_list.append(reduce(lambda a, b: a | b, [SQ(**{field + '__startswith':term}) for field in search_fields] + [SQ(**{field:term}) for field in search_fields]))
        if filter_type == 'location':
            latitude, longitude = request.CLEANED['location']
            query_set = spatial_ranking(query_set, latitude, longitude, distance, pure_dist=True)

        results = query_set.filter(*query_list)
        if total_count:
            return (results._clone().count(), get_clear_search_results(results[offset:endpoint]))
        else:
            return get_clear_search_results(results[offset:endpoint])
예제 #3
0
파일: ajax.py 프로젝트: gage/proto
def auto_complete_main(request):
    """ main search input autocomplete
    """

    q = request.GET.get('q', None)
    """ query handler """
    if q is None or q == '':
        return HttpResponse('', mimetype="text/plain")

    query_list = process_query(q)
    results = None

    latitude, longitude = get_user_location(request)

    has_query = False
    for q_o in query_list:
        if q_o:
            if not has_query:
                has_query = True
                results = personal_ranking(s_qs=SearchQuerySet().filter(searchable=True).filter(SQ(name=q_o)|SQ(name__startswith=q_o)|SQ(nickname__startswith=q_o)), user=request.user)
                print results
            else:
                results = results.filter(SQ(name=q_o)|SQ(name__startswith=q_o)|SQ(nickname__startswith=q_o))

    search_results = {}

    def p_search(search_set, model_name):
        if model_name in ['event', 'user']:
            search_results[model_name]['result'] = get_clear_search_results(search_set.load_all()[:3])
        elif model_name in ['place', ]:
            search_results[model_name]['result'] = get_clear_search_results(spatial_ranking(search_set, latitude, longitude).load_all()[:3])

    MODELS_ORDER = ['place', 'user', 'event']
    for model in MODELS_ORDER:
        if has_query:
            search_set = results.models(*TYPE[model])
            search_results[model] = {}
            search_results[model]['thread'] = threading.Thread(target=p_search, args=(search_set, model))

    for model_search in search_results:
        search_results[model_search]['thread'].start()

    for model_search in search_results:
        search_results[model_search]['thread'].join()

    all_results = []

    for model in MODELS_ORDER:
        print search_results
        all_results.append(search_results[model]['result'])

    response = []
    for key in range(len(all_results)):
        tmp_response = []
        item = []
        num = 0
        for result in all_results[key]:
            if result.pk in request.user.get_profile().blocked_by_user_set:
                continue
            num = num+1
            if num == 1:
                response.append('title|%s' % MODELS_ORDER[key])
            score_field = 'rank_score'
            score = result.__dict__[score_field] if score_field in result.__dict__ else 'x'
            try:
                if result.model_name == 'user':
                    img_url = result.object.get_profile().get_my_photo(request).image50x50.url
                else:
                    img_url = result.object.get_display_photo().image50x50.url
            except:
                img_url = ''

            extra = ""

            if result.model_name == 'user':
                # name = result.object.username
                name = result.object.get_profile().get_nickname(request)
                url = result.object.get_profile().get_absolute_url()
            elif result.model_name == 'place':
                extra = result.object.address
                name = result.object.get_display_name()
                url = result.object.get_absolute_url()
            else:
                name = result.object.get_display_name()
                url = result.object.get_absolute_url()

            item = [
				result.pk,
				name,
				result.model_name,
				'%s' % score,
				url,
				img_url,
                extra,
			]
            tmp_response.append(item)
        # tmp_response.sort(key=lambda obj: obj[1].lower().startswith(q),reverse=True)
        response.extend(["|".join(r) for r in tmp_response])
    response_txt = '\n'.join(response)

    return HttpResponse(response_txt, mimetype="text/plain")
예제 #4
0
파일: ajax.py 프로젝트: gage/proto
def auto_complete_people(request, selector='all'):
    """ people autocomplete
        indexes: first_name, last_name, email, phone, site_user
        type: 'all' (all), 'site' (site use only)
    """
    q = request.GET.get('q', None)
    selected = request.GET.get('selected', None)
    limit = request.GET.get('limit', 5)
    """ query handler """
    if q is None or q == '':
        return HttpResponse('', mimetype="text/plain")
    results = None
    has_query = False
    if not '@' in q:
        query_list = process_query(q)
        for q_o in query_list:
            if q_o:
                if not has_query:
                    has_query = True
                    results = SearchQuerySet().filter(SQ(first_name__startswith=q_o) | SQ(last_name__startswith=q_o) | \
                                 SQ(email__startswith=q_o) | SQ(phone__startswith=q_o) | SQ(site_user__startswith=q_o))
                else:
                    results = results.filter(SQ(first_name__startswith=q_o) | SQ(last_name__startswith=q_o) | \
                                 SQ(email__startswith=q_o) | SQ(phone__startswith=q_o) | SQ(site_user__startswith=q_o))
    else:
        has_query = True
        results = SearchQuerySet().auto_query(q)

    if has_query:
        if request.user.is_anonymous() and 'viewer_site_user' in request.session:
            site_user = request.session['viewer_site_user']
        else:
            site_user = request.user

        results = results.filter(user=site_user.pk).exclude(is_slave=True).models(Contact).load_all()
    else:
        results = []

    if selector == 'site' and has_query:
        results = results.filter(site_user__range=['*','*'])

    if selected and has_query:
        selected = json.loads(selected)
        for _key, value in selected.items():
            results = results.exclude(cid=value)

    if has_query:
        results = results.load_all()[:limit]
    else:
        results = []

    tmp_response = []
    for result in results:
        score = 0
        if not result:
            continue
        img_url = result.object.get_display_photo_url(size='26x26')
        img_url_l = result.object.get_display_photo_url(size='50x50')
        url = ''
        name = result.object.get_display_name()
        item = [
            result.pk,
            name,
            result.model_name,
            '%s' % score,
            url,
            img_url,
            img_url_l,
        ]
        tmp_response.append(item)
    # tmp_response.sort(key=lambda obj: obj[1].lower().startswith(q),reverse=True)
    response = ["|".join(r) for r in tmp_response]
    response_txt = '\n'.join(response)
    return HttpResponse(response_txt, mimetype="text/plain")
예제 #5
0
파일: ajax.py 프로젝트: gage/proto
def auto_complete_place(request):
    """ place autocomplete
    """
    q = request.GET.get('q', None)
    params = request.GET.get('other_params', None)
    limit = request.GET.get('limit', 10)

    latlon = None

    if params:
        params = json.loads(params)
        if 'lat' in params and 'lon' in params:
            latlon = (float(params['lat']), float(params['lon']))

    """ query handler """
    if q is None or q == '':
        return HttpResponse('', mimetype="text/plain")

    query_list = process_query(q)
    results = None

    # handle = open("/tmp/search.log","w")
    # ISOTIMEFORMAT='%Y-%m-%d %X'
    if latlon:
        latitude, longitude = latlon
    else:
        latitude, longitude = get_user_location(request)
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('start search:%s\n'%t)
    has_query = False
    for q_o in query_list:
        if q_o:
            if not has_query:
                has_query = True
                results = personal_ranking(s_qs=SearchQuerySet().filter(name__startswith=q_o), user=request.user)
            else:
                results = results.filter(name__startswith=q_o)
    if has_query:
        results = get_clear_search_results( spatial_ranking(results.models(Place), latitude, longitude, pure_dist=True).load_all()[:limit] )
    else:
        results = []
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('end search:%s\n'%t)
    tmp_response = []
    for result in results:
        # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
        # handle.write('result:%s\n'%t)
        score_field = '%s_d'%request.user.id
        score = result.__dict__[score_field] if score_field in result.__dict__ else 'x'
        img_url = result.object.get_display_photo().image26x26.url
        img_url_l = result.object.get_display_photo().image105x105.url
        url = result.object.get_absolute_url()
        name = result.object.get_display_name()
        category = result.object.category
        if len(name) > 30:
            name = '%s..' % name[:30]
        item = [
            result.pk,
            name,
            result.model_name,
            '%s' % score,
            url,
            img_url,
            img_url_l,
            category,
        ]
        tmp_response.append(item)
    # tmp_response.sort(key=lambda obj: obj[1].lower().startswith(q),reverse=True)
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('End of all:%s\n'%t)
    response = ["|".join(r) for r in tmp_response]
    response_txt = '\n'.join(response)
    return HttpResponse(response_txt, mimetype="text/plain")